diff --git a/lib/db/db_version_migration.dart b/lib/db/db_version_migration.dart index fcf632669..7fc07c2bb 100644 --- a/lib/db/db_version_migration.dart +++ b/lib/db/db_version_migration.dart @@ -29,6 +29,8 @@ import '../utilities/constants.dart'; import '../utilities/flutter_secure_storage_interface.dart'; import '../utilities/logger.dart'; import '../utilities/prefs.dart'; +import '../utilities/stack_file_system.dart'; +import '../utilities/util.dart'; import '../wallets/crypto_currency/crypto_currency.dart'; import 'hive/db.dart'; import 'isar/main_db.dart'; @@ -43,7 +45,7 @@ class DbVersionMigrator with WalletDB { // safe to skip to v11 for campfire fromVersion = 11; } - Logging.instance.log( + Logging.instance.logd( "Running migrate fromVersion $fromVersion", level: LogLevel.Warning, ); @@ -103,7 +105,7 @@ class DbVersionMigrator with WalletDB { } catch (e) { // default to 2 for now latestSetId = 2; - Logging.instance.log( + Logging.instance.logd( "Failed to fetch latest coin id during firo db migrate: $e \nUsing a default value of 2", level: LogLevel.Warning, ); @@ -144,7 +146,6 @@ class DbVersionMigrator with WalletDB { ), }); } - Logger.print("newcoins $coins", normalLength: false); await DB.instance.put( boxName: walletInfo.walletId, key: '_lelantus_coins', @@ -443,6 +444,20 @@ class DbVersionMigrator with WalletDB { // try to continue migrating return await migrate(13, secureStore: secureStore); + case 13: + // migrate + await _v13(secureStore); + + // update version + await DB.instance.put( + boxName: DB.boxNameDBInfo, + key: "hive_data_version", + value: 14, + ); + + // try to continue migrating + return await migrate(14, secureStore: secureStore); + default: // finally return return; @@ -734,4 +749,31 @@ class DbVersionMigrator with WalletDB { ); } } + + Future _v13(SecureStorageInterface secureStore) async { + if (!(Util.isArmLinux || Util.isTestEnv)) { + // open logs db + final isar = await Isar.open( + [isar_models.LogSchema], + directory: (await StackFileSystem.applicationIsarDirectory()).path, + inspector: false, + maxSizeMiB: 512, + ); + + // fetch all logs + final allLogs = await isar.logs.where().findAll(); + + // migrate to simple file based logs. Date/time may be out of order + for (final log in allLogs) { + Logging.instance.log( + log.logLevel.getLoggerLevel(), + "MIGRATED LOG::=> ${log.message}", + time: DateTime.fromMillisecondsSinceEpoch(log.timestampInMillisUTC), + ); + } + + // finally delete logs db + await isar.close(deleteFromDisk: true); + } + } } diff --git a/lib/db/hive/db.dart b/lib/db/hive/db.dart index c71826fbc..be289d4cd 100644 --- a/lib/db/hive/db.dart +++ b/lib/db/hive/db.dart @@ -166,7 +166,7 @@ class DB { AppConfig.getCryptoCurrencyFor(jsonObject["coin"] as String); return false; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error, ${jsonObject["coin"]} does not exist, $name wallet cannot be loaded", level: LogLevel.Error, ); @@ -343,7 +343,7 @@ class DB { await DB.instance.deleteBoxFromDisk(boxName: "theme"); return true; } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Error); + Logging.instance.logd("$e $s", level: LogLevel.Error); return false; } } diff --git a/lib/db/sqlite/firo_cache.dart b/lib/db/sqlite/firo_cache.dart index d32db1bf3..a3b2b8359 100644 --- a/lib/db/sqlite/firo_cache.dart +++ b/lib/db/sqlite/firo_cache.dart @@ -23,7 +23,7 @@ part 'firo_cache_writer.dart'; /// Temporary debugging log function for this file void _debugLog(Object? object) { if (kDebugMode) { - Logging.instance.log( + Logging.instance.logd( object, level: LogLevel.Debug, ); diff --git a/lib/db/sqlite/firo_cache_coordinator.dart b/lib/db/sqlite/firo_cache_coordinator.dart index a002dc222..84ad64b23 100644 --- a/lib/db/sqlite/firo_cache_coordinator.dart +++ b/lib/db/sqlite/firo_cache_coordinator.dart @@ -42,11 +42,11 @@ abstract class FiroCacheCoordinator { ? await usedTagsCacheFile.length() : 0; - Logging.instance.log( + Logging.instance.logd( "Spark cache used tags size: $tagsSize", level: LogLevel.Debug, ); - Logging.instance.log( + Logging.instance.logd( "Spark cache anon set size: $setSize", level: LogLevel.Debug, ); @@ -111,7 +111,7 @@ abstract class FiroCacheCoordinator { progressUpdated?.call(prevSize, meta.size); if (prevMeta?.blockHash == meta.blockHash) { - Logging.instance.log( + Logging.instance.logd( "prevMeta?.blockHash == meta.blockHash", level: LogLevel.Debug, ); diff --git a/lib/electrumx_rpc/cached_electrumx_client.dart b/lib/electrumx_rpc/cached_electrumx_client.dart index 8b1ff10c8..558561f13 100644 --- a/lib/electrumx_rpc/cached_electrumx_client.dart +++ b/lib/electrumx_rpc/cached_electrumx_client.dart @@ -100,7 +100,7 @@ class CachedElectrumXClient { } // save set to db await box.put(groupId, set); - Logging.instance.log( + Logging.instance.logd( "Updated current anonymity set for ${cryptoCurrency.identifier} with group ID $groupId", level: LogLevel.Info, ); @@ -108,7 +108,7 @@ class CachedElectrumXClient { return set; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to process CachedElectrumX.getAnonymitySet(): $e\n$s", level: LogLevel.Error, ); @@ -162,7 +162,7 @@ class CachedElectrumXClient { return Map.from(cachedTx); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to process CachedElectrumX.getTransaction(): $e\n$s", level: LogLevel.Error, ); @@ -212,7 +212,7 @@ class CachedElectrumXClient { return resultingList; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to process CachedElectrumX.getUsedCoinSerials(): $e\n$s", level: LogLevel.Error, ); diff --git a/lib/electrumx_rpc/client_manager.dart b/lib/electrumx_rpc/client_manager.dart index aea7e34e6..3199b840f 100644 --- a/lib/electrumx_rpc/client_manager.dart +++ b/lib/electrumx_rpc/client_manager.dart @@ -69,7 +69,7 @@ class ClientManager { _heightCompleters[key]!.complete(event.height); } }, - onError: (Object err, StackTrace s) => Logging.instance.log( + onError: (Object err, StackTrace s) => Logging.instance.logd( "ClientManager listen: $err\n$s", level: LogLevel.Error, ), diff --git a/lib/electrumx_rpc/electrumx_client.dart b/lib/electrumx_rpc/electrumx_client.dart index 8ff04712a..92bc7ab8a 100644 --- a/lib/electrumx_rpc/electrumx_client.dart +++ b/lib/electrumx_rpc/electrumx_client.dart @@ -233,7 +233,7 @@ class ElectrumXClient { if (!_prefs.torKillSwitch) { // Then we'll just proceed and connect to ElectrumX through // clearnet at the bottom of this function. - Logging.instance.log( + Logging.instance.logd( "Tor preference set but Tor is not enabled, killswitch not set," " connecting to Electrum adapter through clearnet", level: LogLevel.Warning, @@ -400,7 +400,7 @@ class ElectrumXClient { } } catch (e) { final errorMessage = e.toString(); - Logging.instance.log("$host $e", level: LogLevel.Debug); + Logging.instance.logd("$host $e", level: LogLevel.Debug); if (errorMessage.contains("JSON-RPC error")) { currentFailoverIndex = _failovers.length; } @@ -535,7 +535,7 @@ class ElectrumXClient { ).timeout( const Duration(seconds: 30), onTimeout: () { - Logging.instance.log( + Logging.instance.logd( "ElectrumxClient.ping timed out with retryCount=$retryCount, host=$_host", level: LogLevel.Debug, ); @@ -562,7 +562,7 @@ class ElectrumXClient { command: 'blockchain.headers.subscribe', ); if (response == null) { - Logging.instance.log( + Logging.instance.logd( "getBlockHeadTip returned null response", level: LogLevel.Error, ); @@ -761,7 +761,7 @@ class ElectrumXClient { // add empty list on error result.add([]); - Logging.instance.log( + Logging.instance.logd( "getBatchUTXOs failed to parse response=${response[i]}: $e", level: LogLevel.Error, ); @@ -826,13 +826,13 @@ class ElectrumXClient { bool verbose = true, String? requestID, }) async { - Logging.instance.log( + Logging.instance.logd( "attempting to fetch blockchain.transaction.get...", level: LogLevel.Info, ); await checkElectrumAdapter(); final dynamic response = await getElectrumAdapter()!.getTransaction(txHash); - Logging.instance.log( + Logging.instance.logd( "Fetching blockchain.transaction.get finished", level: LogLevel.Info, ); @@ -863,7 +863,7 @@ class ElectrumXClient { String blockhash = "", String? requestID, }) async { - Logging.instance.log( + Logging.instance.logd( "attempting to fetch lelantus.getanonymityset...", level: LogLevel.Info, ); @@ -871,7 +871,7 @@ class ElectrumXClient { final Map response = await (getElectrumAdapter() as FiroElectrumClient) .getLelantusAnonymitySet(groupId: groupId, blockHash: blockhash); - Logging.instance.log( + Logging.instance.logd( "Fetching lelantus.getanonymityset finished", level: LogLevel.Info, ); @@ -886,14 +886,14 @@ class ElectrumXClient { dynamic mints, String? requestID, }) async { - Logging.instance.log( + Logging.instance.logd( "attempting to fetch lelantus.getmintmetadata...", level: LogLevel.Info, ); await checkElectrumAdapter(); final dynamic response = await (getElectrumAdapter() as FiroElectrumClient) .getLelantusMintData(mints: mints); - Logging.instance.log( + Logging.instance.logd( "Fetching lelantus.getmintmetadata finished", level: LogLevel.Info, ); @@ -906,7 +906,7 @@ class ElectrumXClient { String? requestID, required int startNumber, }) async { - Logging.instance.log( + Logging.instance.logd( "attempting to fetch lelantus.getusedcoinserials...", level: LogLevel.Info, ); @@ -919,7 +919,7 @@ class ElectrumXClient { response = await (getElectrumAdapter() as FiroElectrumClient) .getLelantusUsedCoinSerials(startNumber: startNumber); // TODO add 2 minute timeout. - Logging.instance.log( + Logging.instance.logd( "Fetching lelantus.getusedcoinserials finished", level: LogLevel.Info, ); @@ -934,14 +934,14 @@ class ElectrumXClient { /// /// ex: 1 Future getLelantusLatestCoinId({String? requestID}) async { - Logging.instance.log( + Logging.instance.logd( "attempting to fetch lelantus.getlatestcoinid...", level: LogLevel.Info, ); await checkElectrumAdapter(); final int response = await (getElectrumAdapter() as FiroElectrumClient).getLatestCoinId(); - Logging.instance.log( + Logging.instance.logd( "Fetching lelantus.getlatestcoinid finished", level: LogLevel.Info, ); @@ -977,7 +977,7 @@ class ElectrumXClient { coinGroupId: coinGroupId, startBlockHash: startBlockHash, ); - Logging.instance.log( + Logging.instance.logd( "Finished ElectrumXClient.getSparkAnonymitySet(coinGroupId" "=$coinGroupId, startBlockHash=$startBlockHash). " "coins.length: ${(response["coins"] as List?)?.length}" @@ -1068,20 +1068,20 @@ class ElectrumXClient { String? requestID, }) async { try { - Logging.instance.log( + Logging.instance.logd( "attempting to fetch spark.getsparklatestcoinid...", level: LogLevel.Info, ); await checkElectrumAdapter(); final int response = await (getElectrumAdapter() as FiroElectrumClient) .getSparkLatestCoinId(); - Logging.instance.log( + Logging.instance.logd( "Fetching spark.getsparklatestcoinid finished", level: LogLevel.Info, ); return response; } catch (e) { - Logging.instance.log(e, level: LogLevel.Error); + Logging.instance.logd(e, level: LogLevel.Error); rethrow; } } @@ -1101,7 +1101,7 @@ class ElectrumXClient { .map((e) => e.toHexReversedFromBase64) .toSet(); - Logging.instance.log( + Logging.instance.logd( "Finished ElectrumXClient.getMempoolTxids(). " "Duration=${DateTime.now().difference(start)}", level: LogLevel.Info, @@ -1109,7 +1109,7 @@ class ElectrumXClient { return txids; } catch (e) { - Logging.instance.log(e, level: LogLevel.Error); + Logging.instance.logd(e, level: LogLevel.Error); rethrow; } } @@ -1146,7 +1146,7 @@ class ElectrumXClient { ); } - Logging.instance.log( + Logging.instance.logd( "Finished ElectrumXClient.getMempoolSparkData(txids: $txids). " "Duration=${DateTime.now().difference(start)}", level: LogLevel.Info, @@ -1154,7 +1154,7 @@ class ElectrumXClient { return result; } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); rethrow; } } @@ -1178,7 +1178,7 @@ class ElectrumXClient { final map = Map.from(response as Map); final tags = List>.from(map["tagsandtxids"] as List); - Logging.instance.log( + Logging.instance.logd( "Finished ElectrumXClient.getSparkUnhashedUsedCoinsTagsWithTxHashes(" "startNumber=$startNumber). # of tags fetched=${tags.length}, " "Duration=${DateTime.now().difference(start)}", @@ -1187,7 +1187,7 @@ class ElectrumXClient { return tags; } catch (e) { - Logging.instance.log(e, level: LogLevel.Error); + Logging.instance.logd(e, level: LogLevel.Error); rethrow; } } @@ -1199,7 +1199,7 @@ class ElectrumXClient { }) async { try { const command = "spark.getsparkanonymitysetmeta"; - Logging.instance.log( + Logging.instance.logd( "[${getElectrumAdapter()?.host}] => attempting to fetch $command...", level: LogLevel.Info, ); @@ -1222,7 +1222,7 @@ class ElectrumXClient { size: map["size"] as int, ); - Logging.instance.log( + Logging.instance.logd( "Finished ElectrumXClient.getSparkAnonymitySetMeta(" "requestID=$requestID, " "coinGroupId=$coinGroupId" @@ -1233,7 +1233,7 @@ class ElectrumXClient { return result; } catch (e) { - Logging.instance.log(e, level: LogLevel.Error); + Logging.instance.logd(e, level: LogLevel.Error); rethrow; } } @@ -1264,7 +1264,7 @@ class ElectrumXClient { final result = map["coins"] as List; - Logging.instance.log( + Logging.instance.logd( "Finished ElectrumXClient.getSparkAnonymitySetBySector(" "requestID=$requestID, " "coinGroupId=$coinGroupId, " @@ -1278,7 +1278,7 @@ class ElectrumXClient { return result; } catch (e) { - Logging.instance.log(e, level: LogLevel.Error); + Logging.instance.logd(e, level: LogLevel.Error); rethrow; } } @@ -1301,7 +1301,7 @@ class ElectrumXClient { ], ); - Logging.instance.log( + Logging.instance.logd( "Finished ElectrumXClient.isMasterNodeCollateral, " "response: $response, " "Duration=${DateTime.now().difference(start)}", @@ -1310,7 +1310,7 @@ class ElectrumXClient { return response as bool; } catch (e) { - Logging.instance.log(e, level: LogLevel.Error); + Logging.instance.logd(e, level: LogLevel.Error); rethrow; } } @@ -1369,7 +1369,7 @@ class ElectrumXClient { } catch (e, s) { final String msg = "Error parsing fee rate. Response: $response" "\nResult: $response\nError: $e\nStack trace: $s"; - Logging.instance.log(msg, level: LogLevel.Fatal); + Logging.instance.logd(msg, level: LogLevel.Fatal); throw Exception(msg); } } catch (e) { diff --git a/lib/main.dart b/lib/main.dart index e2cae6f72..43e076879 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -21,7 +21,6 @@ import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:google_fonts/google_fonts.dart'; -import 'package:isar/isar.dart'; import 'package:keyboard_dismisser/keyboard_dismisser.dart'; import 'package:path_provider/path_provider.dart'; import 'package:window_size/window_size.dart'; @@ -35,7 +34,6 @@ import 'db/sqlite/firo_cache.dart'; import 'models/exchange/change_now/exchange_transaction.dart'; import 'models/exchange/change_now/exchange_transaction_status.dart'; import 'models/exchange/response_objects/trade.dart'; -import 'models/isar/models/isar_models.dart'; import 'models/models.dart'; import 'models/node_model.dart'; import 'models/notification_model.dart'; @@ -56,8 +54,6 @@ import 'providers/global/base_currencies_provider.dart'; import 'providers/global/trades_service_provider.dart'; import 'providers/providers.dart'; import 'route_generator.dart'; -// import 'package:stackwallet/services/buy/buy_data_loading_service.dart'; -import 'services/debug_service.dart'; import 'services/exchange/exchange_data_loading_service.dart'; import 'services/locale_service.dart'; import 'services/node_service.dart'; @@ -75,6 +71,7 @@ import 'utilities/prefs.dart'; import 'utilities/stack_file_system.dart'; import 'utilities/util.dart'; import 'wallets/isar/providers/all_wallets_info_provider.dart'; +import 'wallets/wallet/wallet_mixin_interfaces/spark_interface.dart'; import 'widgets/crypto_notifications.dart'; final openedFromSWBFileStringStateProvider = @@ -118,19 +115,6 @@ void main(List args) async { } // FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding); - if (!(Logging.isArmLinux || Logging.isTestEnv)) { - final isar = await Isar.open( - [LogSchema], - directory: (await StackFileSystem.applicationIsarDirectory()).path, - inspector: false, - maxSizeMiB: 512, - ); - await Logging.instance.init(isar); - await DebugService.instance.init(isar); - - // clear out all info logs on startup. No need to await and block - unawaited(DebugService.instance.deleteLogsOlderThan()); - } // Registering Transaction Model Adapters DB.instance.hive.registerAdapter(TransactionDataAdapter()); @@ -179,6 +163,14 @@ void main(List args) async { await DB.instance.hive.openBox(DB.boxNamePrefs); await Prefs.instance.init(); + await Logging.instance.initialize( + (await StackFileSystem.applicationLogsDirectory(Prefs.instance)).path, + level: Prefs.instance.logLevel, + ); + + // setup lib spark logging + initSparkLogging(Prefs.instance.logLevel); + if (AppConfig.appName == "Campfire" && !Util.isDesktop && !CampfireMigration.didRun) { @@ -217,7 +209,7 @@ void main(List args) async { ), ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Cannot migrate mobile database\n$e $s", level: LogLevel.Error, printFullLength: true, @@ -404,7 +396,7 @@ class _MaterialAppWithThemeState extends ConsumerState // .userID; // Just reading the ref should set it if it's not already set // We shouldn't need to do this, instead only generating an ID when (or if) the userID is looked up when creating a quote } catch (e, s) { - Logger.print("$e $s", normalLength: false); + Logging.instance.e("load failure", error: e, stackTrace: s); } } @@ -566,7 +558,7 @@ class _MaterialAppWithThemeState extends ConsumerState // call reset to clear cached value await resetOpenPath(); - Logging.instance.log( + Logging.instance.logd( "This is the .swb content from intent: ${ref.read(openedFromSWBFileStringStateProvider.state).state}", level: LogLevel.Info, ); diff --git a/lib/models/exchange/change_now/cn_exchange_estimate.dart b/lib/models/exchange/change_now/cn_exchange_estimate.dart index 8d3c43566..c1aa4e7fb 100644 --- a/lib/models/exchange/change_now/cn_exchange_estimate.dart +++ b/lib/models/exchange/change_now/cn_exchange_estimate.dart @@ -9,6 +9,7 @@ */ import 'package:decimal/decimal.dart'; + import '../../../utilities/logger.dart'; enum CNEstimateType { direct, reverse } @@ -113,7 +114,7 @@ class CNExchangeEstimate { ); } catch (e, s) { Logging.instance - .log("Failed to parse: $json \n$e\n$s", level: LogLevel.Fatal); + .logd("Failed to parse: $json \n$e\n$s", level: LogLevel.Fatal); rethrow; } } diff --git a/lib/models/exchange/change_now/estimated_exchange_amount.dart b/lib/models/exchange/change_now/estimated_exchange_amount.dart index 550b39489..9cc634215 100644 --- a/lib/models/exchange/change_now/estimated_exchange_amount.dart +++ b/lib/models/exchange/change_now/estimated_exchange_amount.dart @@ -58,7 +58,7 @@ class EstimatedExchangeAmount { ); } catch (e, s) { Logging.instance - .log("Failed to parse: $json \n$e\n$s", level: LogLevel.Fatal); + .logd("Failed to parse: $json \n$e\n$s", level: LogLevel.Fatal); rethrow; } } diff --git a/lib/models/exchange/change_now/exchange_transaction_status.dart b/lib/models/exchange/change_now/exchange_transaction_status.dart index 3c3aebb7f..055a3757c 100644 --- a/lib/models/exchange/change_now/exchange_transaction_status.dart +++ b/lib/models/exchange/change_now/exchange_transaction_status.dart @@ -187,7 +187,7 @@ class ExchangeTransactionStatus { }); factory ExchangeTransactionStatus.fromJson(Map json) { - Logging.instance.log(json, printFullLength: true, level: LogLevel.Info); + Logging.instance.logd(json, printFullLength: true, level: LogLevel.Info); try { return ExchangeTransactionStatus( status: changeNowTransactionStatusFromStringIgnoreCase( @@ -228,7 +228,7 @@ class ExchangeTransactionStatus { payload: json["payload"] as Object?, ); } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Fatal); + Logging.instance.logd("$e\n$s", level: LogLevel.Fatal); rethrow; } } diff --git a/lib/models/exchange/response_objects/estimate.dart b/lib/models/exchange/response_objects/estimate.dart index d51fda17c..eddcd4c5d 100644 --- a/lib/models/exchange/response_objects/estimate.dart +++ b/lib/models/exchange/response_objects/estimate.dart @@ -9,6 +9,7 @@ */ import 'package:decimal/decimal.dart'; + import '../../../utilities/logger.dart'; class Estimate { @@ -46,7 +47,8 @@ class Estimate { kycRating: kycRating, ); } catch (e, s) { - Logging.instance.log("Estimate.fromMap(): $e\n$s", level: LogLevel.Error); + Logging.instance + .logd("Estimate.fromMap(): $e\n$s", level: LogLevel.Error); rethrow; } } diff --git a/lib/models/exchange/response_objects/fixed_rate_market.dart b/lib/models/exchange/response_objects/fixed_rate_market.dart index 103d9d99f..faa9d4268 100644 --- a/lib/models/exchange/response_objects/fixed_rate_market.dart +++ b/lib/models/exchange/response_objects/fixed_rate_market.dart @@ -9,6 +9,7 @@ */ import 'package:decimal/decimal.dart'; + import '../../../utilities/logger.dart'; class FixedRateMarket { @@ -53,7 +54,7 @@ class FixedRateMarket { minerFee: Decimal.tryParse(json["minerFee"].toString()), ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "FixedRateMarket.fromMap(): $e\n$s", level: LogLevel.Error, ); diff --git a/lib/models/exchange/simpleswap/sp_currency.dart b/lib/models/exchange/simpleswap/sp_currency.dart index 96905f44c..17bd6ebf5 100644 --- a/lib/models/exchange/simpleswap/sp_currency.dart +++ b/lib/models/exchange/simpleswap/sp_currency.dart @@ -59,7 +59,7 @@ class SPCurrency { warningsTo: json["warnings_to"] as List, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "SPCurrency.fromJson failed to parse: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/models/isar/stack_theme.dart b/lib/models/isar/stack_theme.dart index ce5002a1d..d7b8023b9 100644 --- a/lib/models/isar/stack_theme.dart +++ b/lib/models/isar/stack_theme.dart @@ -1884,7 +1884,7 @@ class StackTheme { (map[mainNetId] as String).toBigIntFromHex.toInt(), ); } else { - Logging.instance.log( + Logging.instance.logd( "Color not found in theme for $mainNetId", level: LogLevel.Error, ); diff --git a/lib/networking/http.dart b/lib/networking/http.dart index ae2a3b97b..fcb8beea3 100644 --- a/lib/networking/http.dart +++ b/lib/networking/http.dart @@ -53,7 +53,7 @@ class HTTP { response.statusCode, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "HTTP.get() rethrew: $e\n$s", level: LogLevel.Info, ); @@ -99,7 +99,7 @@ class HTTP { response.statusCode, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "HTTP.post() rethrew: $e\n$s", level: LogLevel.Info, ); @@ -119,7 +119,7 @@ class HTTP { onDone: () => completer.complete( Uint8List.fromList(bytes), ), - onError: (Object err, StackTrace s) => Logging.instance.log( + onError: (Object err, StackTrace s) => Logging.instance.logd( "Http wrapper layer listen: $err\n$s", level: LogLevel.Error, ), diff --git a/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_2.dart b/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_2.dart index a57148fee..0c7c666be 100644 --- a/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_2.dart +++ b/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_2.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; + import '../../../../../frost_route_generator.dart'; -import '../../../../wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart'; import '../../../../../providers/frost_wallet/frost_wallet_providers.dart'; import '../../../../../services/frost.dart'; import '../../../../../utilities/logger.dart'; @@ -15,6 +15,7 @@ import '../../../../../widgets/dialogs/frost/frost_error_dialog.dart'; import '../../../../../widgets/frost_step_user_steps.dart'; import '../../../../../widgets/stack_dialog.dart'; import '../../../../../widgets/textfields/frost_step_field.dart'; +import '../../../../wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart'; class FrostCreateStep2 extends ConsumerStatefulWidget { const FrostCreateStep2({ @@ -177,7 +178,7 @@ class _FrostCreateStep2State extends ConsumerState { .routeName, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_3.dart b/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_3.dart index 20130a2da..e1d7c081e 100644 --- a/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_3.dart +++ b/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_3.dart @@ -178,7 +178,7 @@ class _FrostCreateStep3State extends ConsumerState { .routeName, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_5.dart b/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_5.dart index 4640e0abb..fed7cf360 100644 --- a/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_5.dart +++ b/lib/pages/add_wallet_views/frost_ms/new/steps/frost_create_step_5.dart @@ -219,7 +219,7 @@ class _FrostCreateStep5State extends ConsumerState { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1a.dart b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1a.dart index a83e22d40..36d7138c0 100644 --- a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1a.dart +++ b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1a.dart @@ -81,7 +81,7 @@ class _FrostReshareStep1aState extends ConsumerState { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1b.dart b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1b.dart index e29d1110b..4dc485795 100644 --- a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1b.dart +++ b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1b.dart @@ -117,7 +117,7 @@ class _FrostReshareStep1bState extends ConsumerState { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1c.dart b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1c.dart index 962e207bf..4432ebd0d 100644 --- a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1c.dart +++ b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_1c.dart @@ -204,7 +204,7 @@ class _FrostReshareStep1cState extends ConsumerState { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_2abd.dart b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_2abd.dart index 65c22e2f6..3a2a7a64e 100644 --- a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_2abd.dart +++ b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_2abd.dart @@ -79,7 +79,7 @@ class _FrostReshareStep2abdState extends ConsumerState { .routeName, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_2c.dart b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_2c.dart index b134ea5e4..fe53e562b 100644 --- a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_2c.dart +++ b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_2c.dart @@ -59,7 +59,7 @@ class _FrostReshareStep2cState extends ConsumerState { .routeName, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_3abd.dart b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_3abd.dart index a899ddda1..e027d294c 100644 --- a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_3abd.dart +++ b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_3abd.dart @@ -70,7 +70,7 @@ class _FrostReshareStep3abdState extends ConsumerState { .routeName, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_4.dart b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_4.dart index 41d94cdd1..c3147c656 100644 --- a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_4.dart +++ b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_4.dart @@ -88,7 +88,7 @@ class _FrostReshareStep4State extends ConsumerState { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_5.dart b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_5.dart index 834a0a638..ce9f250f2 100644 --- a/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_5.dart +++ b/lib/pages/add_wallet_views/frost_ms/reshare/frost_reshare_step_5.dart @@ -104,7 +104,7 @@ class _FrostReshareStep5State extends ConsumerState { } } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/frost_ms/restore/restore_frost_ms_wallet_view.dart b/lib/pages/add_wallet_views/frost_ms/restore/restore_frost_ms_wallet_view.dart index 14e1d45e5..f7aec5a82 100644 --- a/lib/pages/add_wallet_views/frost_ms/restore/restore_frost_ms_wallet_view.dart +++ b/lib/pages/add_wallet_views/frost_ms/restore/restore_frost_ms_wallet_view.dart @@ -171,7 +171,7 @@ class _RestoreFrostMsWalletViewState ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); @@ -234,7 +234,7 @@ class _RestoreFrostMsWalletViewState ); if (qrResult == null) { - Logging.instance.log( + Logging.instance.logd( "Qr scanning cancelled", level: LogLevel.Info, ); @@ -248,7 +248,7 @@ class _RestoreFrostMsWalletViewState } } } on PlatformException catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to get camera permissions while trying to scan qr code: $e\n$s", level: LogLevel.Warning, ); diff --git a/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart b/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart index aa49a9038..034cb6dbc 100644 --- a/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart +++ b/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart @@ -274,7 +274,7 @@ class _NewWalletRecoveryPhraseWarningViewState return (wallet, fetchedMnemonic); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart b/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart index eb01ea9c7..06619e582 100644 --- a/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart +++ b/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart @@ -628,7 +628,7 @@ class _RestoreWalletViewState extends ConsumerState { final results = AddressUtils.decodeQRSeedData(qrResult.rawContent); - Logging.instance.log("scan parsed: $results", level: LogLevel.Info); + Logging.instance.logd("scan parsed: $results", level: LogLevel.Info); if (results["mnemonic"] != null) { final list = (results["mnemonic"] as List) @@ -636,16 +636,16 @@ class _RestoreWalletViewState extends ConsumerState { .toList(growable: false); if (list.isNotEmpty) { _clearAndPopulateMnemonic(list); - Logging.instance.log("mnemonic populated", level: LogLevel.Info); + Logging.instance.logd("mnemonic populated", level: LogLevel.Info); } else { Logging.instance - .log("mnemonic failed to populate", level: LogLevel.Info); + .logd("mnemonic failed to populate", level: LogLevel.Info); } } } on PlatformException catch (e) { // likely failed to get camera permissions Logging.instance - .log("Restore wallet qr scan failed: $e", level: LogLevel.Warning); + .logd("Restore wallet qr scan failed: $e", level: LogLevel.Warning); } } diff --git a/lib/pages/add_wallet_views/restore_wallet_view/sub_widgets/restore_failed_dialog.dart b/lib/pages/add_wallet_views/restore_wallet_view/sub_widgets/restore_failed_dialog.dart index 1ae4a5efd..1f8952c15 100644 --- a/lib/pages/add_wallet_views/restore_wallet_view/sub_widgets/restore_failed_dialog.dart +++ b/lib/pages/add_wallet_views/restore_wallet_view/sub_widgets/restore_failed_dialog.dart @@ -10,6 +10,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; + import '../../../../providers/global/secure_store_provider.dart'; import '../../../../providers/providers.dart'; import '../../../../themes/stack_colors.dart'; @@ -72,7 +73,7 @@ class _RestoreFailedDialogState extends ConsumerState { ref.read(secureStoreProvider), ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error while getting wallet info in restore failed dialog\n" "Error: $e\nStack trace: $s", level: LogLevel.Error, diff --git a/lib/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart b/lib/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart index e95e33539..1f6177192 100644 --- a/lib/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart +++ b/lib/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart @@ -306,7 +306,7 @@ class _VerifyRecoveryPhraseViewState throw ex!; } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/address_book_views/subviews/new_contact_address_entry_form.dart b/lib/pages/address_book_views/subviews/new_contact_address_entry_form.dart index d84cee567..dfe2155bd 100644 --- a/lib/pages/address_book_views/subviews/new_contact_address_entry_form.dart +++ b/lib/pages/address_book_views/subviews/new_contact_address_entry_form.dart @@ -115,7 +115,7 @@ class _NewContactAddressEntryFormState // .read(shouldShowLockscreenOnResumeStateProvider // .state) // .state = true; - Logging.instance.log( + Logging.instance.logd( "Failed to get camera permissions to scan address qr code: $e\n$s", level: LogLevel.Warning, ); diff --git a/lib/pages/buy_view/buy_form.dart b/lib/pages/buy_view/buy_form.dart index f47831547..729e0e1c2 100644 --- a/lib/pages/buy_view/buy_form.dart +++ b/lib/pages/buy_view/buy_form.dart @@ -311,7 +311,7 @@ class _BuyFormState extends ConsumerState { .read(simplexProvider) .updateSupportedCryptos(response.value!); // TODO validate } else { - Logging.instance.log( + Logging.instance.logd( "_loadSimplexCurrencies: $response", level: LogLevel.Warning, ); @@ -326,7 +326,7 @@ class _BuyFormState extends ConsumerState { .read(simplexProvider) .updateSupportedFiats(response.value!); // TODO validate } else { - Logging.instance.log( + Logging.instance.logd( "_loadSimplexCurrencies: $response", level: LogLevel.Warning, ); @@ -626,7 +626,7 @@ class _BuyFormState extends ConsumerState { ref.read(simplexProvider).updateQuote(response.value!); return BuyResponse(value: response.value!); } else { - Logging.instance.log( + Logging.instance.logd( "_loadQuote: $response", level: LogLevel.Warning, ); @@ -724,7 +724,7 @@ class _BuyFormState extends ConsumerState { final qrResult = await scanner.scan(); - Logging.instance.log( + Logging.instance.logd( "qrResult content: ${qrResult.rawContent}", level: LogLevel.Info, ); @@ -734,7 +734,7 @@ class _BuyFormState extends ConsumerState { logging: Logging.instance, ); - Logging.instance.log( + Logging.instance.logd( "qrResult parsed: $paymentData", level: LogLevel.Info, ); @@ -760,7 +760,7 @@ class _BuyFormState extends ConsumerState { } on PlatformException catch (e, s) { // here we ignore the exception caused by not giving permission // to use the camera to scan a qr code - Logging.instance.log( + Logging.instance.logd( "Failed to get camera permissions while trying to scan qr code in SendView: $e\n$s", level: LogLevel.Warning, ); @@ -1241,7 +1241,7 @@ class _BuyFormState extends ConsumerState { } }); } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Info); + Logging.instance.logd("$e\n$s", level: LogLevel.Info); } }, ), diff --git a/lib/pages/buy_view/sub_widgets/crypto_selection_view.dart b/lib/pages/buy_view/sub_widgets/crypto_selection_view.dart index 3bc0b220b..890ed2cd9 100644 --- a/lib/pages/buy_view/sub_widgets/crypto_selection_view.dart +++ b/lib/pages/buy_view/sub_widgets/crypto_selection_view.dart @@ -304,7 +304,7 @@ class CoinIconForTicker extends ConsumerWidget { height: size, ); } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Fatal); + Logging.instance.logd("$e\n$s", level: LogLevel.Fatal); rethrow; } } diff --git a/lib/pages/exchange_view/confirm_change_now_send.dart b/lib/pages/exchange_view/confirm_change_now_send.dart index 1b52dfdbe..552b7f3a9 100644 --- a/lib/pages/exchange_view/confirm_change_now_send.dart +++ b/lib/pages/exchange_view/confirm_change_now_send.dart @@ -162,7 +162,7 @@ class _ConfirmChangeNowSendViewState Navigator.of(context).popUntil(ModalRoute.withName(routeOnSuccessName)); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Broadcast transaction failed: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/pages/exchange_view/exchange_step_views/step_2_view.dart b/lib/pages/exchange_view/exchange_step_views/step_2_view.dart index 028ce0ac4..b2873feb2 100644 --- a/lib/pages/exchange_view/exchange_step_views/step_2_view.dart +++ b/lib/pages/exchange_view/exchange_step_views/step_2_view.dart @@ -98,7 +98,7 @@ class _Step2ViewState extends ConsumerState { }); } } on PlatformException catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to get camera permissions while trying to scan qr code in SendView: $e\n$s", level: LogLevel.Warning, ); @@ -135,7 +135,7 @@ class _Step2ViewState extends ConsumerState { }); } } on PlatformException catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to get camera permissions while trying to scan qr code in SendView: $e\n$s", level: LogLevel.Warning, ); @@ -304,7 +304,7 @@ class _Step2ViewState extends ConsumerState { }); } catch (e, s) { Logging.instance - .log("$e\n$s", level: LogLevel.Info); + .logd("$e\n$s", level: LogLevel.Info); } }, ), @@ -543,7 +543,7 @@ class _Step2ViewState extends ConsumerState { }); }); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Info, ); diff --git a/lib/pages/exchange_view/exchange_step_views/step_4_view.dart b/lib/pages/exchange_view/exchange_step_views/step_4_view.dart index 69bd4ea01..4196fb332 100644 --- a/lib/pages/exchange_view/exchange_step_views/step_4_view.dart +++ b/lib/pages/exchange_view/exchange_step_views/step_4_view.dart @@ -317,7 +317,7 @@ class _Step4ViewState extends ConsumerState { } } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); if (mounted && !wasCancelled) { // pop building dialog Navigator.of(context).pop(); diff --git a/lib/pages/exchange_view/send_from_view.dart b/lib/pages/exchange_view/send_from_view.dart index f499775b1..ec5778e30 100644 --- a/lib/pages/exchange_view/send_from_view.dart +++ b/lib/pages/exchange_view/send_from_view.dart @@ -387,7 +387,7 @@ class _SendFromCardState extends ConsumerState { } } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); if (mounted) { // pop building dialog Navigator.of(context).pop(); diff --git a/lib/pages/exchange_view/sub_widgets/exchange_provider_option.dart b/lib/pages/exchange_view/sub_widgets/exchange_provider_option.dart index 7ba126659..1dc2ca237 100644 --- a/lib/pages/exchange_view/sub_widgets/exchange_provider_option.dart +++ b/lib/pages/exchange_view/sub_widgets/exchange_provider_option.dart @@ -173,7 +173,7 @@ class _ExchangeOptionState extends ConsumerState { ], ); } else { - Logging.instance.log( + Logging.instance.logd( "$runtimeType rate unavailable for ${widget.exchange.name}: $data", level: LogLevel.Warning, ); diff --git a/lib/pages/paynym/subwidgets/paynym_followers_list.dart b/lib/pages/paynym/subwidgets/paynym_followers_list.dart index 43fdf0223..c362a5dba 100644 --- a/lib/pages/paynym/subwidgets/paynym_followers_list.dart +++ b/lib/pages/paynym/subwidgets/paynym_followers_list.dart @@ -12,7 +12,7 @@ import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'paynym_card_button.dart'; + import '../../../providers/global/paynym_api_provider.dart'; import '../../../providers/global/wallets_provider.dart'; import '../../../providers/wallet/my_paynym_account_state_provider.dart'; @@ -24,6 +24,7 @@ import '../../../utilities/util.dart'; import '../../../wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart'; import '../../../widgets/conditional_parent.dart'; import '../../../widgets/rounded_white_container.dart'; +import 'paynym_card_button.dart'; class PaynymFollowersList extends ConsumerStatefulWidget { const PaynymFollowersList({ @@ -93,7 +94,7 @@ class _PaynymFollowersListState extends ConsumerState { account.value!; } } catch (e) { - Logging.instance.log( + Logging.instance.logd( "Failed pull down refresh of paynym home page: $e", level: LogLevel.Warning, ); diff --git a/lib/pages/paynym/subwidgets/paynym_following_list.dart b/lib/pages/paynym/subwidgets/paynym_following_list.dart index 486e138e2..a1cda9b9a 100644 --- a/lib/pages/paynym/subwidgets/paynym_following_list.dart +++ b/lib/pages/paynym/subwidgets/paynym_following_list.dart @@ -12,7 +12,7 @@ import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'paynym_card_button.dart'; + import '../../../providers/global/paynym_api_provider.dart'; import '../../../providers/global/wallets_provider.dart'; import '../../../providers/wallet/my_paynym_account_state_provider.dart'; @@ -24,6 +24,7 @@ import '../../../utilities/util.dart'; import '../../../wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart'; import '../../../widgets/conditional_parent.dart'; import '../../../widgets/rounded_white_container.dart'; +import 'paynym_card_button.dart'; class PaynymFollowingList extends ConsumerStatefulWidget { const PaynymFollowingList({ @@ -93,7 +94,7 @@ class _PaynymFollowingListState extends ConsumerState { account.value!; } } catch (e) { - Logging.instance.log( + Logging.instance.logd( "Failed pull down refresh of paynym home page: $e", level: LogLevel.Warning, ); diff --git a/lib/pages/receive_view/generate_receiving_uri_qr_code_view.dart b/lib/pages/receive_view/generate_receiving_uri_qr_code_view.dart index dfe85d934..9fc8adb41 100644 --- a/lib/pages/receive_view/generate_receiving_uri_qr_code_view.dart +++ b/lib/pages/receive_view/generate_receiving_uri_qr_code_view.dart @@ -188,7 +188,7 @@ class _GenerateUriQrCodeViewState extends State { queryParams, ); - Logging.instance.log( + Logging.instance.logd( "Generated receiving QR code for: $uriString", level: LogLevel.Info, ); diff --git a/lib/pages/send_view/frost_ms/recipient.dart b/lib/pages/send_view/frost_ms/recipient.dart index ce38153e7..5820b7375 100644 --- a/lib/pages/send_view/frost_ms/recipient.dart +++ b/lib/pages/send_view/frost_ms/recipient.dart @@ -133,7 +133,7 @@ class _RecipientState extends ConsumerState { final qrResult = await ref.read(pBarcodeScanner).scan(); - Logging.instance.log( + Logging.instance.logd( "qrResult content: ${qrResult.rawContent}", level: LogLevel.Info, ); @@ -143,7 +143,7 @@ class _RecipientState extends ConsumerState { logging: Logging.instance, ); - Logging.instance.log( + Logging.instance.logd( "qrResult parsed: $paymentData", level: LogLevel.Info, ); @@ -175,7 +175,7 @@ class _RecipientState extends ConsumerState { _updateRecipientData(); } on PlatformException catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to get camera permissions while " "trying to scan qr code in SendView: $e\n$s", level: LogLevel.Warning, diff --git a/lib/pages/send_view/frost_ms/send_steps/frost_send_step_1a.dart b/lib/pages/send_view/frost_ms/send_steps/frost_send_step_1a.dart index 0ec725d00..3bb7a9bd0 100644 --- a/lib/pages/send_view/frost_ms/send_steps/frost_send_step_1a.dart +++ b/lib/pages/send_view/frost_ms/send_steps/frost_send_step_1a.dart @@ -67,7 +67,7 @@ class _FrostSendStep1aState extends ConsumerState { .routeName, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Error, ); diff --git a/lib/pages/send_view/frost_ms/send_steps/frost_send_step_1b.dart b/lib/pages/send_view/frost_ms/send_steps/frost_send_step_1b.dart index b7c95ea2c..a67afe7d3 100644 --- a/lib/pages/send_view/frost_ms/send_steps/frost_send_step_1b.dart +++ b/lib/pages/send_view/frost_ms/send_steps/frost_send_step_1b.dart @@ -108,7 +108,7 @@ class _FrostSendStep1bState extends ConsumerState { .routeName, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Error, ); diff --git a/lib/pages/send_view/frost_ms/send_steps/frost_send_step_2.dart b/lib/pages/send_view/frost_ms/send_steps/frost_send_step_2.dart index 724e62092..14bee2844 100644 --- a/lib/pages/send_view/frost_ms/send_steps/frost_send_step_2.dart +++ b/lib/pages/send_view/frost_ms/send_steps/frost_send_step_2.dart @@ -291,7 +291,7 @@ class _FrostSendStep2State extends ConsumerState { // arguments: widget.walletId, // ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/send_view/frost_ms/send_steps/frost_send_step_3.dart b/lib/pages/send_view/frost_ms/send_steps/frost_send_step_3.dart index c96f15233..0b8c79c8b 100644 --- a/lib/pages/send_view/frost_ms/send_steps/frost_send_step_3.dart +++ b/lib/pages/send_view/frost_ms/send_steps/frost_send_step_3.dart @@ -233,7 +233,7 @@ class _FrostSendStep3State extends ConsumerState { .routeName, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/send_view/frost_ms/send_steps/frost_send_step_4.dart b/lib/pages/send_view/frost_ms/send_steps/frost_send_step_4.dart index a560d7151..ec9eb3e2a 100644 --- a/lib/pages/send_view/frost_ms/send_steps/frost_send_step_4.dart +++ b/lib/pages/send_view/frost_ms/send_steps/frost_send_step_4.dart @@ -237,7 +237,7 @@ class _FrostSendStep4State extends ConsumerState { } } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/send_view/send_view.dart b/lib/pages/send_view/send_view.dart index 1dd9b68ef..a3598fbe5 100644 --- a/lib/pages/send_view/send_view.dart +++ b/lib/pages/send_view/send_view.dart @@ -158,7 +158,7 @@ class _SendViewState extends ConsumerState { // .state = true, // ); - Logging.instance.log( + Logging.instance.logd( "qrResult content: ${qrResult.rawContent}", level: LogLevel.Info, ); @@ -216,7 +216,7 @@ class _SendViewState extends ConsumerState { // .state = true; // here we ignore the exception caused by not giving permission // to use the camera to scan a qr code - Logging.instance.log( + Logging.instance.logd( "Failed to get camera permissions while trying to scan qr code in SendView: $e\n$s", level: LogLevel.Warning, ); @@ -248,8 +248,8 @@ class _SendViewState extends ConsumerState { return; } _cachedAmountToSend = amount; - Logging.instance - .log("it changed $amount $_cachedAmountToSend", level: LogLevel.Info); + Logging.instance.logd("it changed $amount $_cachedAmountToSend", + level: LogLevel.Info); final amountString = ref.read(pAmountFormatter(coin)).format( amount, @@ -285,7 +285,7 @@ class _SendViewState extends ConsumerState { return; } _cachedAmountToSend = amount; - Logging.instance.log( + Logging.instance.logd( "it changed $amount $_cachedAmountToSend", level: LogLevel.Info, ); @@ -828,7 +828,7 @@ class _SendViewState extends ConsumerState { ); } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); if (mounted) { // pop building dialog Navigator.of(context).pop(); diff --git a/lib/pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart b/lib/pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart index 0ca0dba47..e45026981 100644 --- a/lib/pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart +++ b/lib/pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart @@ -831,7 +831,7 @@ class _TransactionFeeSelectionSheetState return null; } } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Warning); + Logging.instance.logd("$e $s", level: LogLevel.Warning); return null; } } diff --git a/lib/pages/send_view/token_send_view.dart b/lib/pages/send_view/token_send_view.dart index 4837b9773..112e15073 100644 --- a/lib/pages/send_view/token_send_view.dart +++ b/lib/pages/send_view/token_send_view.dart @@ -159,7 +159,7 @@ class _TokenSendViewState extends ConsumerState { // .state = true, // ); - Logging.instance.log( + Logging.instance.logd( "qrResult content: ${qrResult.rawContent}", level: LogLevel.Info, ); @@ -170,7 +170,7 @@ class _TokenSendViewState extends ConsumerState { ); Logging.instance - .log("qrResult parsed: $paymentData", level: LogLevel.Info); + .logd("qrResult parsed: $paymentData", level: LogLevel.Info); if (paymentData != null && paymentData.coin?.uriScheme == coin.uriScheme) { @@ -221,7 +221,7 @@ class _TokenSendViewState extends ConsumerState { // .state = true; // here we ignore the exception caused by not giving permission // to use the camera to scan a qr code - Logging.instance.log( + Logging.instance.logd( "Failed to get camera permissions while trying to scan qr code in SendView: $e\n$s", level: LogLevel.Warning, ); @@ -255,7 +255,7 @@ class _TokenSendViewState extends ConsumerState { return; } _cachedAmountToSend = _amountToSend; - Logging.instance.log( + Logging.instance.logd( "it changed $_amountToSend $_cachedAmountToSend", level: LogLevel.Info, ); @@ -293,7 +293,7 @@ class _TokenSendViewState extends ConsumerState { return; } _cachedAmountToSend = _amountToSend; - Logging.instance.log( + Logging.instance.logd( "it changed $_amountToSend $_cachedAmountToSend", level: LogLevel.Info, ); @@ -535,7 +535,7 @@ class _TokenSendViewState extends ConsumerState { ); } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); if (mounted) { // pop building dialog Navigator.of(context).pop(); diff --git a/lib/pages/settings_views/global_settings_view/advanced_views/advanced_settings_view.dart b/lib/pages/settings_views/global_settings_view/advanced_views/advanced_settings_view.dart index 6f04cce80..d86f17526 100644 --- a/lib/pages/settings_views/global_settings_view/advanced_views/advanced_settings_view.dart +++ b/lib/pages/settings_views/global_settings_view/advanced_views/advanced_settings_view.dart @@ -23,7 +23,7 @@ import '../../../../widgets/custom_buttons/app_bar_icon_button.dart'; import '../../../../widgets/custom_buttons/draggable_switch_button.dart'; import '../../../../widgets/rounded_white_container.dart'; import '../../../stack_privacy_calls.dart'; -import 'debug_view.dart'; +import 'logging_settings_view.dart'; import 'manage_coin_units/manage_coin_units_view.dart'; import 'manage_explorer_view.dart'; @@ -68,7 +68,8 @@ class AdvancedSettingsView extends StatelessWidget { ), ), onPressed: () { - Navigator.of(context).pushNamed(DebugView.routeName); + Navigator.of(context) + .pushNamed(LoggingSettingsView.routeName); }, child: Padding( padding: const EdgeInsets.symmetric( @@ -78,7 +79,7 @@ class AdvancedSettingsView extends StatelessWidget { child: Row( children: [ Text( - "Debug info", + "Logging", style: STextStyles.titleBold12(context), textAlign: TextAlign.left, ), diff --git a/lib/pages/settings_views/global_settings_view/advanced_views/debug_view.dart b/lib/pages/settings_views/global_settings_view/advanced_views/debug_view.dart deleted file mode 100644 index 92e5cc256..000000000 --- a/lib/pages/settings_views/global_settings_view/advanced_views/debug_view.dart +++ /dev/null @@ -1,609 +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:device_info_plus/device_info_plus.dart'; -import 'package:event_bus/event_bus.dart'; -import 'package:file_picker/file_picker.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_libepiccash/git_versions.dart' as EPIC_VERSIONS; -// import 'package:flutter_libmonero/git_versions.dart' as MONERO_VERSIONS; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:flutter_svg/svg.dart'; -import 'package:lelantus/git_versions.dart' as FIRO_VERSIONS; -import 'package:package_info_plus/package_info_plus.dart'; - -import '../../../../app_config.dart'; -import '../../../../models/isar/models/log.dart'; -import '../../../../notifications/show_flush_bar.dart'; -import '../../../../providers/global/debug_service_provider.dart'; -import '../../../../themes/stack_colors.dart'; -import '../../../../utilities/assets.dart'; -import '../../../../utilities/clipboard_interface.dart'; -import '../../../../utilities/constants.dart'; -import '../../../../utilities/logger.dart'; -import '../../../../utilities/stack_file_system.dart'; -import '../../../../utilities/text_styles.dart'; -import '../../../../utilities/util.dart'; -import '../../../../widgets/background.dart'; -import '../../../../widgets/custom_buttons/app_bar_icon_button.dart'; -import '../../../../widgets/custom_buttons/blue_text_button.dart'; -import '../../../../widgets/custom_loading_overlay.dart'; -import '../../../../widgets/icon_widgets/x_icon.dart'; -import '../../../../widgets/rounded_container.dart'; -import '../../../../widgets/stack_dialog.dart'; -import '../../../../widgets/stack_text_field.dart'; -import '../../../../widgets/textfield_icon_button.dart'; -import '../stack_backup_views/helpers/swb_file_system.dart'; - -class DebugView extends ConsumerStatefulWidget { - const DebugView({super.key}); - - static const String routeName = "/debug"; - - @override - ConsumerState createState() => _DebugViewState(); -} - -class _DebugViewState extends ConsumerState { - final _searchController = TextEditingController(); - final _searchFocusNode = FocusNode(); - - final scrollController = ScrollController(); - - String _searchTerm = ""; - - List filtered(List unfiltered, String filter) { - if (filter == "") { - return unfiltered; - } - return unfiltered - .where( - (e) => (e.toString().toLowerCase().contains(filter.toLowerCase())), - ) - .toList(); - } - - BorderRadius? _borderRadius(int index, int listLength) { - if (index == 0 && listLength == 1) { - return BorderRadius.circular( - Constants.size.circularBorderRadius, - ); - } else if (index == 0) { - return BorderRadius.vertical( - bottom: Radius.circular( - Constants.size.circularBorderRadius, - ), - ); - } else if (index == listLength - 1) { - return BorderRadius.vertical( - top: Radius.circular( - Constants.size.circularBorderRadius, - ), - ); - } - return null; - } - - @override - void initState() { - super.initState(); - } - - @override - void dispose() { - _searchController.dispose(); - scrollController.dispose(); - _searchFocusNode.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return Background( - child: Scaffold( - backgroundColor: Theme.of(context).extension()!.background, - appBar: AppBar( - leading: AppBarBackButton( - onPressed: () async { - Navigator.of(context).pop(); - }, - ), - title: Text( - "Debug", - style: STextStyles.navBarTitle(context), - ), - actions: [ - Padding( - padding: const EdgeInsets.only( - top: 10, - bottom: 10, - right: 10, - ), - child: AspectRatio( - aspectRatio: 1, - child: AppBarIconButton( - key: const Key("deleteLogsAppBarButtonKey"), - size: 36, - shadows: const [], - color: Theme.of(context).extension()!.background, - icon: SvgPicture.asset( - Assets.svg.trash, - color: Theme.of(context) - .extension()! - .accentColorDark, - width: 20, - height: 20, - ), - onPressed: () async { - await showDialog( - context: context, - builder: (_) => StackDialog( - title: "Delete logs?", - message: - "You are about to delete all logs permanently. Are you sure?", - leftButton: TextButton( - style: Theme.of(context) - .extension()! - .getSecondaryEnabledButtonStyle(context), - child: Text( - "Cancel", - style: STextStyles.itemSubtitle12(context), - ), - onPressed: () { - Navigator.of(context).pop(); - }, - ), - rightButton: TextButton( - style: Theme.of(context) - .extension()! - .getPrimaryEnabledButtonStyle(context), - child: Text( - "Delete logs", - style: STextStyles.button(context), - ), - onPressed: () async { - Navigator.of(context).pop(); - - bool shouldPop = false; - unawaited( - showDialog( - barrierDismissible: false, - context: context, - builder: (_) => WillPopScope( - onWillPop: () async { - return shouldPop; - }, - child: const CustomLoadingOverlay( - message: "Deleting logs...", - eventBus: null, - ), - ), - ), - ); - - await ref - .read(debugServiceProvider) - .deleteAllLogs(); - - shouldPop = true; - - if (mounted) { - Navigator.pop(context); - unawaited( - showFloatingFlushBar( - type: FlushBarType.info, - context: context, - message: 'Logs cleared!', - ), - ); - - setState(() {}); - } - }, - ), - ), - ); - }, - ), - ), - ), - ], - ), - body: Padding( - padding: const EdgeInsets.only( - top: 12, - left: 16, - right: 16, - ), - child: NestedScrollView( - floatHeaderSlivers: true, - headerSliverBuilder: (context, innerBoxIsScrolled) { - return [ - SliverOverlapAbsorber( - handle: - NestedScrollView.sliverOverlapAbsorberHandleFor(context), - sliver: SliverToBoxAdapter( - child: Padding( - padding: const EdgeInsets.only(bottom: 16), - child: Column( - children: [ - ClipRRect( - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius, - ), - child: TextField( - autocorrect: Util.isDesktop ? false : true, - enableSuggestions: Util.isDesktop ? false : true, - controller: _searchController, - focusNode: _searchFocusNode, - onChanged: (newString) { - setState(() => _searchTerm = newString); - }, - style: STextStyles.field(context), - decoration: standardInputDecoration( - "Search", - _searchFocusNode, - context, - ).copyWith( - prefixIcon: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 10, - vertical: 16, - ), - child: SvgPicture.asset( - Assets.svg.search, - width: 16, - height: 16, - ), - ), - suffixIcon: _searchController.text.isNotEmpty - ? Padding( - padding: - const EdgeInsets.only(right: 0), - child: UnconstrainedBox( - child: Row( - children: [ - TextFieldIconButton( - child: const XIcon(), - onTap: () async { - setState(() { - _searchController.text = ""; - _searchTerm = ""; - }); - }, - ), - ], - ), - ), - ) - : null, - ), - ), - ), - const SizedBox( - height: 12, - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - CustomTextButton( - text: "Save Debug Info to clipboard", - onTap: () async { - try { - final packageInfo = - await PackageInfo.fromPlatform(); - final version = packageInfo.version; - final build = packageInfo.buildNumber; - final signature = - packageInfo.buildSignature; - final appName = packageInfo.appName; - final String firoCommit = - FIRO_VERSIONS.getPluginVersion(); - final String epicCashCommit = - EPIC_VERSIONS.getPluginVersion(); - // final String moneroCommit = - // MONERO_VERSIONS.getPluginVersion(); - final DeviceInfoPlugin deviceInfoPlugin = - DeviceInfoPlugin(); - final deviceInfo = - await deviceInfoPlugin.deviceInfo; - final deviceInfoMap = deviceInfo.toMap(); - deviceInfoMap.remove("systemFeatures"); - - final logs = filtered( - ref.watch( - debugServiceProvider.select( - (value) => value.recentLogs, - ), - ), - _searchTerm, - ).reversed.toList(growable: false); - final List errorLogs = []; - for (final log in logs) { - if (log.logLevel == LogLevel.Error || - log.logLevel == LogLevel.Fatal) { - errorLogs.add( - "${log.logLevel}: ${log.message}", - ); - } - } - - final finalDebugMap = { - "version": version, - "build": build, - "signature": signature, - "appName": appName, - "firoCommit": firoCommit, - "epicCashCommit": epicCashCommit, - // "moneroCommit": moneroCommit, - "deviceInfoMap": deviceInfoMap, - "errorLogs": errorLogs, - }; - Logging.instance.log( - json.encode(finalDebugMap), - level: LogLevel.Info, - printFullLength: true, - ); - const ClipboardInterface clipboard = - ClipboardWrapper(); - await clipboard.setData( - ClipboardData( - text: json.encode(finalDebugMap), - ), - ); - } catch (e, s) { - Logging.instance - .log("$e $s", level: LogLevel.Error); - } - }, - ), - const Spacer(), - CustomTextButton( - text: "Save logs to file", - onTap: () async { - final systemfile = SWBFileSystem(); - await systemfile.prepareStorage(); - Directory rootPath = await StackFileSystem - .applicationRootDirectory(); - - if (Platform.isAndroid) { - rootPath = - Directory("/storage/emulated/0/"); - } - - Directory dir = - Directory('${rootPath.path}/Documents'); - if (Platform.isIOS) { - dir = Directory(rootPath.path); - } - try { - if (!dir.existsSync()) { - dir.createSync(); - } - } catch (e, s) { - Logging.instance - .log("$e\n$s", level: LogLevel.Error); - } - String? path; - if (Platform.isAndroid) { - path = dir.path; - } else { - path = await FilePicker.platform - .getDirectoryPath( - dialogTitle: "Choose Log Save Location", - initialDirectory: - systemfile.startPath!.path, - lockParentWindow: true, - ); - } - - if (path != null) { - final eventBus = EventBus(); - bool shouldPop = false; - unawaited( - showDialog( - barrierDismissible: false, - context: context, - builder: (_) => WillPopScope( - onWillPop: () async { - return shouldPop; - }, - child: CustomLoadingOverlay( - message: - "Generating ${AppConfig.prefix} logs file", - eventBus: eventBus, - ), - ), - ), - ); - - bool logsSaved = true; - String? filename; - try { - filename = await ref - .read(debugServiceProvider) - .exportToFile(path, eventBus); - } catch (e, s) { - logsSaved = false; - Logging.instance - .log("$e $s", level: LogLevel.Error); - } - - shouldPop = true; - - if (mounted) { - Navigator.pop(context); - - if (Platform.isAndroid) { - unawaited( - showDialog( - context: context, - builder: (context) => StackOkDialog( - title: logsSaved - ? "Logs saved to" - : "Error Saving Logs", - message: "${path!}/$filename", - ), - ), - ); - } else { - unawaited( - showFloatingFlushBar( - type: FlushBarType.info, - context: context, - message: logsSaved - ? 'Logs file saved' - : "Error Saving Logs", - ), - ); - } - } - } - }, - ), - ], - ), - ], - ), - ), - ), - ), - ]; - }, - body: Builder( - builder: (context) { - final logs = filtered( - ref.watch( - debugServiceProvider.select((value) => value.recentLogs), - ), - _searchTerm, - ).reversed.toList(growable: false); - - return CustomScrollView( - reverse: true, - // shrinkWrap: true, - controller: scrollController, - slivers: [ - SliverOverlapInjector( - handle: NestedScrollView.sliverOverlapAbsorberHandleFor( - context, - ), - ), - SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) { - final log = logs[index]; - - return Container( - key: Key( - "log_${log.id}_${log.timestampInMillisUTC}", - ), - decoration: BoxDecoration( - color: Theme.of(context) - .extension()! - .popupBG, - borderRadius: _borderRadius(index, logs.length), - ), - child: Padding( - padding: const EdgeInsets.all(4), - child: RoundedContainer( - padding: const EdgeInsets.all(0), - color: Theme.of(context) - .extension()! - .popupBG, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Text( - " [${log.logLevel.name}]", - style: STextStyles.baseXS(context) - .copyWith( - fontSize: 8, - color: (log.logLevel == - LogLevel.Info - ? Theme.of(context) - .extension()! - .topNavIconGreen - : (log.logLevel == - LogLevel.Warning - ? Theme.of(context) - .extension< - StackColors>()! - .topNavIconYellow - : (log.logLevel == - LogLevel.Error - ? Colors.orange - : Theme.of(context) - .extension< - StackColors>()! - .topNavIconRed))), - ), - ), - Text( - "[${DateTime.fromMillisecondsSinceEpoch(log.timestampInMillisUTC, isUtc: true)}]: ", - style: STextStyles.baseXS(context) - .copyWith( - fontSize: 8, - color: Theme.of(context) - .extension()! - .textDark3, - ), - ), - ], - ), - Row( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - const SizedBox( - width: 20, - ), - Flexible( - child: Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - SelectableText( - log.message, - style: - STextStyles.baseXS(context) - .copyWith(fontSize: 8), - ), - ], - ), - ), - ], - ), - ], - ), - ), - ), - ); - }, - childCount: logs.length, - ), - ), - ], - ); - }, - ), - ), - ), - ), - ); - } -} diff --git a/lib/pages/settings_views/global_settings_view/advanced_views/logging_settings_view.dart b/lib/pages/settings_views/global_settings_view/advanced_views/logging_settings_view.dart new file mode 100644 index 000000000..dc6c24013 --- /dev/null +++ b/lib/pages/settings_views/global_settings_view/advanced_views/logging_settings_view.dart @@ -0,0 +1,258 @@ +/* + * 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:io'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +// import 'package:flutter_libmonero/git_versions.dart' as MONERO_VERSIONS; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_svg/svg.dart'; + +import '../../../../app_config.dart'; +import '../../../../providers/global/prefs_provider.dart'; +import '../../../../themes/stack_colors.dart'; +import '../../../../utilities/assets.dart'; +import '../../../../utilities/logger.dart'; +import '../../../../utilities/text_styles.dart'; +import '../../../../widgets/background.dart'; +import '../../../../widgets/custom_buttons/app_bar_icon_button.dart'; +import '../../../../widgets/desktop/primary_button.dart'; +import '../../../../widgets/log_level_preference_widget.dart'; +import '../../../../widgets/rounded_white_container.dart'; +import '../../../../widgets/stack_dialog.dart'; + +class LoggingSettingsView extends ConsumerStatefulWidget { + const LoggingSettingsView({super.key}); + + static const String routeName = "/loggingView"; + + @override + ConsumerState createState() => + _LoggingSettingsViewState(); +} + +class _LoggingSettingsViewState extends ConsumerState { + late final TextEditingController fileLocationController; + bool _lock = false; + + Future _edit() async { + final currentPath = ref.read(prefsChangeNotifierProvider).logsPath ?? + Logging.instance.logsDirPath; + final newPath = await _pickDir(context, currentPath); + + // test if has permission to write + if (newPath != null) { + final file = File( + "$newPath${Platform.pathSeparator}._test", + ); + if (!file.existsSync()) { + file.createSync(); + file.deleteSync(); + } + } + + // success + ref.read(prefsChangeNotifierProvider).logsPath = newPath; + + if (mounted) { + setState(() { + fileLocationController.text = + ref.read(prefsChangeNotifierProvider).logsPath ?? + Logging.instance.logsDirPath; + }); + } + } + + Future _pickDir(BuildContext context, String currentPath) async { + final String? chosenPath; + // if (Platform.isIOS) { + // chosenPath = currentPath; + // } else { + final String path = + Platform.isWindows ? currentPath.replaceAll("/", "\\") : currentPath; + chosenPath = await FilePicker.platform.getDirectoryPath( + dialogTitle: "Choose Log Save location", + initialDirectory: path, + lockParentWindow: true, + ); + // } + return chosenPath; + } + + @override + void initState() { + super.initState(); + fileLocationController = TextEditingController(); + fileLocationController.text = + ref.read(prefsChangeNotifierProvider).logsPath ?? + Logging.instance.logsDirPath; + } + + @override + void dispose() { + fileLocationController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Background( + child: Scaffold( + backgroundColor: Theme.of(context).extension()!.background, + appBar: AppBar( + leading: AppBarBackButton( + onPressed: () async { + Navigator.of(context).pop(); + }, + ), + title: Text( + "Logging", + style: STextStyles.navBarTitle(context), + ), + ), + body: SafeArea( + child: Padding( + padding: const EdgeInsets.only( + top: 12, + left: 16, + right: 16, + ), + child: Column( + children: [ + Row( + children: [ + Text( + "Log files location", + style: STextStyles.fieldLabel(context), + textAlign: TextAlign.left, + ), + ], + ), + const SizedBox( + height: 16, + ), + TextField( + autocorrect: false, + enableSuggestions: false, + controller: fileLocationController, + style: STextStyles.field(context), + decoration: InputDecoration( + hintText: "Save to...", + hintStyle: STextStyles.fieldLabel(context), + suffixIcon: UnconstrainedBox( + child: Row( + children: [ + const SizedBox( + width: 16, + ), + SvgPicture.asset( + Assets.svg.folder, + color: Theme.of(context) + .extension()! + .textDark3, + width: 16, + height: 16, + ), + const SizedBox( + width: 12, + ), + ], + ), + ), + ), + key: const Key( + "logsDirPathLocationControllerKey", + ), + readOnly: true, + toolbarOptions: const ToolbarOptions( + copy: true, + cut: false, + paste: false, + selectAll: false, + ), + onChanged: (newValue) {}, + ), + const SizedBox( + height: 16, + ), + const LogLevelPreferenceWidget(), + const SizedBox( + height: 16, + ), + Row( + children: [ + Expanded( + child: RoundedWhiteContainer( + child: Text( + "NOTE: ${AppConfig.appName} must be restarted in order" + " for changes to take effect.", + style: STextStyles.subtitle500(context), + ), + ), + ), + ], + ), + const SizedBox( + height: 16, + ), + const Spacer(), + PrimaryButton( + label: "Select log save location", + onPressed: () async { + if (_lock) { + return; + } + _lock = true; + try { + await _edit(); + } catch (e, s) { + Logging.instance.e( + "Failed to change logs path", + error: e, + stackTrace: s, + ); + if (context.mounted) { + final String err; + if (e + .toString() + .contains("OS Error: Operation not permitted")) { + err = "Cannot use chosen location"; + } else { + err = e.toString(); + } + + unawaited( + showDialog( + context: context, + builder: (context) => StackOkDialog( + title: "Failed to change logs path", + message: err, + ), + ), + ); + } + } finally { + _lock = false; + } + }, + ), + const SizedBox( + height: 16, + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/pages/settings_views/global_settings_view/appearance_settings/sub_widgets/install_theme_from_file_dialog.dart b/lib/pages/settings_views/global_settings_view/appearance_settings/sub_widgets/install_theme_from_file_dialog.dart index b95384ba1..b274ae093 100644 --- a/lib/pages/settings_views/global_settings_view/appearance_settings/sub_widgets/install_theme_from_file_dialog.dart +++ b/lib/pages/settings_views/global_settings_view/appearance_settings/sub_widgets/install_theme_from_file_dialog.dart @@ -15,6 +15,7 @@ import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; + import '../../../../../themes/stack_colors.dart'; import '../../../../../themes/theme_service.dart'; import '../../../../../utilities/assets.dart'; @@ -54,7 +55,7 @@ class _InstallThemeFromFileDialogState ]); return true; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to install theme: $e\n$s", level: LogLevel.Warning, ); @@ -77,7 +78,7 @@ class _InstallThemeFromFileDialogState }); } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); } } diff --git a/lib/pages/settings_views/global_settings_view/appearance_settings/sub_widgets/stack_theme_card.dart b/lib/pages/settings_views/global_settings_view/appearance_settings/sub_widgets/stack_theme_card.dart index 3ab865653..b9f991ab8 100644 --- a/lib/pages/settings_views/global_settings_view/appearance_settings/sub_widgets/stack_theme_card.dart +++ b/lib/pages/settings_views/global_settings_view/appearance_settings/sub_widgets/stack_theme_card.dart @@ -64,7 +64,7 @@ class _StackThemeCardState extends ConsumerState { await service.install(themeArchiveData: data); return true; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed _downloadAndInstall of ${widget.data.id}: $e\n$s", level: LogLevel.Warning, ); diff --git a/lib/pages/settings_views/global_settings_view/hidden_settings.dart b/lib/pages/settings_views/global_settings_view/hidden_settings.dart index c0ed42019..99fb927cb 100644 --- a/lib/pages/settings_views/global_settings_view/hidden_settings.dart +++ b/lib/pages/settings_views/global_settings_view/hidden_settings.dart @@ -15,7 +15,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../../../notifications/show_flush_bar.dart'; -import '../../../providers/global/debug_service_provider.dart'; import '../../../providers/providers.dart'; import '../../../themes/stack_colors.dart'; import '../../../utilities/assets.dart'; @@ -148,6 +147,29 @@ class HiddenSettings extends StatelessWidget { ); }, ), + const SizedBox( + height: 12, + ), + Consumer( + builder: (_, ref, __) { + return GestureDetector( + onTap: () async { + ref.read(prefsChangeNotifierProvider).logsPath = + null; + }, + child: RoundedWhiteContainer( + child: Text( + "Reset log location", + style: STextStyles.button(context).copyWith( + color: Theme.of(context) + .extension()! + .accentColorDark, + ), + ), + ), + ); + }, + ), // const SizedBox( // height: 12, // ), @@ -176,40 +198,40 @@ class HiddenSettings extends StatelessWidget { // ), // ); // }), - const SizedBox( - height: 12, - ), - Consumer( - builder: (_, ref, __) { - return GestureDetector( - onTap: () async { - await ref - .read(debugServiceProvider) - .deleteAllLogs(); - - if (context.mounted) { - unawaited( - showFloatingFlushBar( - type: FlushBarType.success, - message: "Debug Logs deleted", - context: context, - ), - ); - } - }, - child: RoundedWhiteContainer( - child: Text( - "Delete Debug Logs", - style: STextStyles.button(context).copyWith( - color: Theme.of(context) - .extension()! - .accentColorDark, - ), - ), - ), - ); - }, - ), + // const SizedBox( + // height: 12, + // ), + // Consumer( + // builder: (_, ref, __) { + // return GestureDetector( + // onTap: () async { + // await ref + // .read(debugServiceProvider) + // .deleteAllLogs(); + // + // if (context.mounted) { + // unawaited( + // showFloatingFlushBar( + // type: FlushBarType.success, + // message: "Debug Logs deleted", + // context: context, + // ), + // ); + // } + // }, + // child: RoundedWhiteContainer( + // child: Text( + // "Delete Debug Logs", + // style: STextStyles.button(context).copyWith( + // color: Theme.of(context) + // .extension()! + // .accentColorDark, + // ), + // ), + // ), + // ); + // }, + // ), const SizedBox( height: 12, ), diff --git a/lib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart b/lib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart index 5bbbe37d1..d437c8a86 100644 --- a/lib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart +++ b/lib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart @@ -351,7 +351,7 @@ class _AddEditNodeViewState extends ConsumerState { ); if (qrResult == null) { - Logging.instance.log( + Logging.instance.logd( "Qr scanning cancelled", level: LogLevel.Info, ); @@ -359,14 +359,14 @@ class _AddEditNodeViewState extends ConsumerState { try { await _processQrData(qrResult); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error processing QR code data: $e\n$s", level: LogLevel.Error, ); } } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error opening QR code scanner dialog: $e\n$s", level: LogLevel.Error, ); @@ -376,7 +376,7 @@ class _AddEditNodeViewState extends ConsumerState { final result = await BarcodeScanner.scan(); await _processQrData(result.rawContent); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Warning, ); @@ -412,7 +412,7 @@ class _AddEditNodeViewState extends ConsumerState { }); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Warning, ); diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/create_auto_backup_view.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/create_auto_backup_view.dart index 4e1fdea36..228132010 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/create_auto_backup_view.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/create_auto_backup_view.dart @@ -175,8 +175,8 @@ class _EnableAutoBackupViewState extends ConsumerState { }); } } catch (e, s) { - Logging.instance - .log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", + level: LogLevel.Error); } }, controller: fileLocationController, @@ -578,8 +578,8 @@ class _EnableAutoBackupViewState extends ConsumerState { } on Exception catch (e, s) { final String err = getErrorMessageFromSWBException(e); - Logging.instance - .log("$err\n$s", level: LogLevel.Error); + Logging.instance.logd("$err\n$s", + level: LogLevel.Error); // pop encryption progress dialog Navigator.of(context).pop(); showFloatingFlushBar( @@ -590,7 +590,7 @@ class _EnableAutoBackupViewState extends ConsumerState { return; } catch (e, s) { Logging.instance - .log("$e\n$s", level: LogLevel.Error); + .logd("$e\n$s", level: LogLevel.Error); // pop encryption progress dialog Navigator.of(context).pop(); showFloatingFlushBar( diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/create_backup_view.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/create_backup_view.dart index 4bf75c0bf..b3c1a4369 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/create_backup_view.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/create_backup_view.dart @@ -208,7 +208,7 @@ class _RestoreFromFileViewState extends State { } } catch (e, s) { Logging.instance - .log("$e\n$s", level: LogLevel.Error); + .logd("$e\n$s", level: LogLevel.Error); } }, controller: fileLocationController, diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/edit_auto_backup_view.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/edit_auto_backup_view.dart index ae88abd24..61555ee23 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/edit_auto_backup_view.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/edit_auto_backup_view.dart @@ -159,7 +159,7 @@ class _EditAutoBackupViewState extends ConsumerState { adkVersion = adk.item1; } on Exception catch (e, s) { final String err = getErrorMessageFromSWBException(e); - Logging.instance.log("$err\n$s", level: LogLevel.Error); + Logging.instance.logd("$err\n$s", level: LogLevel.Error); // pop encryption progress dialog Navigator.of(context).pop(); unawaited( @@ -171,7 +171,7 @@ class _EditAutoBackupViewState extends ConsumerState { ); return; } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); // pop encryption progress dialog Navigator.of(context).pop(); unawaited( @@ -374,7 +374,7 @@ class _EditAutoBackupViewState extends ConsumerState { }); } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); } }, controller: fileLocationController, diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart index 68d9bb1f0..43d0160b6 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart @@ -100,9 +100,9 @@ abstract class SWB { _cancelCompleter = Completer(); _shouldCancelRestore = true; Logging.instance - .log("SWB cancel restore requested", level: LogLevel.Info); + .logd("SWB cancel restore requested", level: LogLevel.Info); } else { - Logging.instance.log( + Logging.instance.logd( "SWB cancel restore requested while a cancellation request is currently in progress", level: LogLevel.Warning, ); @@ -147,10 +147,10 @@ abstract class SWB { backupFile .writeAsStringSync(Format.uint8listToString(encryptedContent)); } - Logging.instance.log(backupFile.absolute, level: LogLevel.Info); + Logging.instance.logd(backupFile.absolute, level: LogLevel.Info); return true; } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); return false; } } @@ -174,10 +174,10 @@ abstract class SWB { backupFile .writeAsStringSync(Format.uint8listToString(encryptedContent)); } - Logging.instance.log(backupFile.absolute, level: LogLevel.Info); + Logging.instance.logd(backupFile.absolute, level: LogLevel.Info); return true; } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); return false; } } @@ -194,7 +194,7 @@ abstract class SWB { Tuple2(encryptedText, passphrase), ); } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); return null; } } @@ -214,7 +214,7 @@ abstract class SWB { final jsonBackup = utf8.decode(decryptedContent); return jsonBackup; } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); return null; } } @@ -224,24 +224,24 @@ abstract class SWB { required SecureStorageInterface secureStorage, }) async { Logging.instance - .log("Starting createStackWalletJSON...", level: LogLevel.Info); + .logd("Starting createStackWalletJSON...", level: LogLevel.Info); final _wallets = Wallets.sharedInstance; final Map backupJson = {}; final NodeService nodeService = NodeService(secureStorageInterface: secureStorage); final _secureStore = secureStorage; - Logging.instance.log( + Logging.instance.logd( "createStackWalletJSON awaiting DB.instance.mutex...", level: LogLevel.Info, ); // prevent modification of data await DB.instance.mutex.protect(() async { - Logging.instance.log( + Logging.instance.logd( "...createStackWalletJSON DB.instance.mutex acquired", level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( "SWB backing up nodes", level: LogLevel.Warning, ); @@ -253,7 +253,7 @@ abstract class SWB { }).toList(); backupJson['primaryNodes'] = await Future.wait(primaryNodes); } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Warning); + Logging.instance.logd("$e $s", level: LogLevel.Warning); } try { final nodesFuture = nodeService.nodes.map((e) async { @@ -264,10 +264,10 @@ abstract class SWB { final nodes = await Future.wait(nodesFuture); backupJson['nodes'] = nodes; } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Error); + Logging.instance.logd("$e $s", level: LogLevel.Error); } - Logging.instance.log( + Logging.instance.logd( "SWB backing up prefs", level: LogLevel.Warning, ); @@ -291,7 +291,7 @@ abstract class SWB { backupJson['prefs'] = prefs; - Logging.instance.log( + Logging.instance.logd( "SWB backing up addressbook", level: LogLevel.Warning, ); @@ -301,7 +301,7 @@ abstract class SWB { backupJson['addressBookEntries'] = addresses.map((e) => e.toMap()).toList(); - Logging.instance.log( + Logging.instance.logd( "SWB backing up wallets", level: LogLevel.Warning, ); @@ -330,7 +330,7 @@ abstract class SWB { final String err = "${wallet.info.coin.identifier} wallet ${wallet.info.name} " "has null keys or config"; - Logging.instance.log(err, level: LogLevel.Fatal); + Logging.instance.logd(err, level: LogLevel.Fatal); throw Exception(err); } //This case should never actually happen in practice unless the whole @@ -368,7 +368,7 @@ abstract class SWB { } backupJson['wallets'] = backupWallets; - Logging.instance.log( + Logging.instance.logd( "SWB backing up trades", level: LogLevel.Warning, ); @@ -385,7 +385,7 @@ abstract class SWB { tradeTxidLookupDataService.all.map((e) => e.toMap()).toList(); backupJson["tradeTxidLookupData"] = lookupData; - Logging.instance.log( + Logging.instance.logd( "SWB backing up trade notes", level: LogLevel.Warning, ); @@ -395,7 +395,7 @@ abstract class SWB { final tradeNotes = tradeNotesService.all; backupJson["tradeNotes"] = tradeNotes; }); - Logging.instance.log( + Logging.instance.logd( "createStackWalletJSON DB.instance.mutex released", level: LogLevel.Info, ); @@ -408,7 +408,7 @@ abstract class SWB { // .toList(growable: false); Logging.instance - .log("...createStackWalletJSON complete", level: LogLevel.Info); + .logd("...createStackWalletJSON complete", level: LogLevel.Info); return backupJson; } @@ -590,7 +590,7 @@ abstract class SWB { await restoringFuture; - Logging.instance.log( + Logging.instance.logd( "SWB restored: ${info.walletId} ${info.name} ${info.coin.prettyName}", level: LogLevel.Info, ); @@ -606,7 +606,7 @@ abstract class SWB { mnemonicPassphrase: mnemonicPassphrase, ); } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Warning); + Logging.instance.logd("$e $s", level: LogLevel.Warning); uiState?.update( walletId: info.walletId, restoringStatus: StackRestoringStatus.failed, @@ -640,7 +640,7 @@ abstract class SWB { uiState?.preferences = StackRestoringStatus.restoring; - Logging.instance.log( + Logging.instance.logd( "SWB restoring prefs", level: LogLevel.Warning, ); @@ -649,7 +649,7 @@ abstract class SWB { uiState?.preferences = StackRestoringStatus.success; uiState?.addressBook = StackRestoringStatus.restoring; - Logging.instance.log( + Logging.instance.logd( "SWB restoring addressbook", level: LogLevel.Warning, ); @@ -660,7 +660,7 @@ abstract class SWB { uiState?.addressBook = StackRestoringStatus.success; uiState?.nodes = StackRestoringStatus.restoring; - Logging.instance.log( + Logging.instance.logd( "SWB restoring nodes", level: LogLevel.Warning, ); @@ -675,7 +675,7 @@ abstract class SWB { // restore trade history if (trades != null) { - Logging.instance.log( + Logging.instance.logd( "SWB restoring trades", level: LogLevel.Warning, ); @@ -684,7 +684,7 @@ abstract class SWB { // restore trade history lookup data for trades send from stack wallet if (tradeTxidLookupData != null) { - Logging.instance.log( + Logging.instance.logd( "SWB restoring trade look up data", level: LogLevel.Warning, ); @@ -694,7 +694,7 @@ abstract class SWB { // restore trade notes if (tradeNotes != null) { - Logging.instance.log( + Logging.instance.logd( "SWB restoring trade notes", level: LogLevel.Warning, ); @@ -729,13 +729,13 @@ abstract class SWB { ) async { if (!Platform.isLinux) await WakelockPlus.enable(); - Logging.instance.log( + Logging.instance.logd( "SWB creating temp backup", level: LogLevel.Warning, ); final preRestoreJSON = await createStackWalletJSON(secureStorage: secureStorageInterface); - Logging.instance.log( + Logging.instance.logd( "SWB temp backup created", level: LogLevel.Warning, ); @@ -832,7 +832,7 @@ abstract class SWB { otherData = Map.from(data as Map); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "SWB restore walletinfo otherdata error: $e\n$s", level: LogLevel.Error, ); @@ -950,7 +950,7 @@ abstract class SWB { return false; } - Logging.instance.log("done with SWB restore", level: LogLevel.Warning); + Logging.instance.logd("done with SWB restore", level: LogLevel.Warning); await Wallets.sharedInstance .loadAfterStackRestore(_prefs, uiState?.wallets ?? [], Util.isDesktop); @@ -1100,7 +1100,7 @@ abstract class SWB { node: nodeService.getNodeById(id: node['id'] as String)!, ); } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Error); + Logging.instance.logd("$e $s", level: LogLevel.Error); } } } @@ -1193,7 +1193,7 @@ abstract class SWB { _cancelCompleter!.complete(); _shouldCancelRestore = false; - Logging.instance.log("Revert SWB complete", level: LogLevel.Info); + Logging.instance.logd("Revert SWB complete", level: LogLevel.Info); } static Future _restorePrefs(Map prefs) async { @@ -1310,7 +1310,7 @@ abstract class SWB { node: nodeService.getNodeById(id: node['id'] as String)!, ); } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Error); + Logging.instance.logd("$e $s", level: LogLevel.Error); } } } diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/restore_from_file_view.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/restore_from_file_view.dart index c994d6c7c..1a73743ac 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/restore_from_file_view.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/restore_from_file_view.dart @@ -172,7 +172,7 @@ class _RestoreFromFileViewState extends ConsumerState { }); } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); } }, controller: fileLocationController, diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_views/stack_restore_progress_view.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_views/stack_restore_progress_view.dart index b160eb2e1..7064dfa5a 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_views/stack_restore_progress_view.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_views/stack_restore_progress_view.dart @@ -169,7 +169,7 @@ class _StackRestoreProgressViewState ref.read(secureStoreProvider), ); } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Warning); + Logging.instance.logd("$e\n$s", level: LogLevel.Warning); } if (finished != null && finished && uiState.done) { diff --git a/lib/pages/settings_views/global_settings_view/tor_settings/tor_settings_view.dart b/lib/pages/settings_views/global_settings_view/tor_settings/tor_settings_view.dart index 425a7accc..5f34b89fa 100644 --- a/lib/pages/settings_views/global_settings_view/tor_settings/tor_settings_view.dart +++ b/lib/pages/settings_views/global_settings_view/tor_settings/tor_settings_view.dart @@ -604,7 +604,7 @@ Future connectTor(WidgetRef ref, BuildContext context) async { // Toggle the useTor preference on success. ref.read(prefsChangeNotifierProvider).useTor = true; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error starting tor: $e\n$s", level: LogLevel.Error, ); @@ -627,7 +627,7 @@ Future disconnectTor(WidgetRef ref, BuildContext context) async { // Toggle the useTor preference on success. ref.read(prefsChangeNotifierProvider).useTor = false; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error stopping tor: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/pages/settings_views/wallet_settings_view/frost_ms/initiate_resharing/complete_reshare_config_view.dart b/lib/pages/settings_views/wallet_settings_view/frost_ms/initiate_resharing/complete_reshare_config_view.dart index 7adb5b4c3..efb5ce11a 100644 --- a/lib/pages/settings_views/wallet_settings_view/frost_ms/initiate_resharing/complete_reshare_config_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/frost_ms/initiate_resharing/complete_reshare_config_view.dart @@ -148,7 +148,7 @@ class _CompleteReshareConfigViewState ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_settings_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_settings_view.dart index 8e889ed7c..18b18d9e1 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_settings_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_settings_view.dart @@ -49,7 +49,6 @@ import '../../../widgets/stack_dialog.dart'; import '../../address_book_views/address_book_view.dart'; import '../../home_view/home_view.dart'; import '../../pinpad_views/lock_screen_view.dart'; -import '../global_settings_view/advanced_views/debug_view.dart'; import '../global_settings_view/syncing_preferences_views/syncing_preferences_view.dart'; import '../sub_widgets/settings_list_button.dart'; import 'frost_ms/frost_ms_options_view.dart'; @@ -558,17 +557,17 @@ class _WalletSettingsViewState extends ConsumerState { ); }, ), - const SizedBox( - height: 8, - ), - SettingsListButton( - iconAssetName: Assets.svg.ellipsis, - title: "Debug Info", - onPressed: () { - Navigator.of(context) - .pushNamed(DebugView.routeName); - }, - ), + // const SizedBox( + // height: 8, + // ), + // SettingsListButton( + // iconAssetName: Assets.svg.ellipsis, + // title: "Debug Info", + // onPressed: () { + // Navigator.of(context) + // .pushNamed(DebugView.routeName); + // }, + // ), ], ), ), diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/lelantus_settings_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/lelantus_settings_view.dart index f0ebcfbf0..34628565f 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/lelantus_settings_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/lelantus_settings_view.dart @@ -114,7 +114,7 @@ class _LelantusSettingsViewState extends ConsumerState { } } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); if (mounted) { // show error await showDialog( diff --git a/lib/pages/wallet_view/transaction_views/transaction_details_view.dart b/lib/pages/wallet_view/transaction_views/transaction_details_view.dart index 1071ffdae..70246ee93 100644 --- a/lib/pages/wallet_view/transaction_views/transaction_details_view.dart +++ b/lib/pages/wallet_view/transaction_views/transaction_details_view.dart @@ -219,7 +219,7 @@ class _TransactionDetailsViewState return address; } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Warning); + Logging.instance.logd("$e\n$s", level: LogLevel.Warning); return address; } } diff --git a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart index 7081f5929..55ecb0cb0 100644 --- a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart +++ b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart @@ -406,7 +406,7 @@ class _TransactionV2DetailsViewState return address; } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Warning); + Logging.instance.logd("$e\n$s", level: LogLevel.Warning); return address; } } diff --git a/lib/pages/wallet_view/wallet_view.dart b/lib/pages/wallet_view/wallet_view.dart index 52d6e05a4..4247e96da 100644 --- a/lib/pages/wallet_view/wallet_view.dart +++ b/lib/pages/wallet_view/wallet_view.dart @@ -1199,7 +1199,7 @@ class _WalletViewState extends ConsumerState { .read(paynymAPIProvider) .nym(code.toString()); - Logging.instance.log( + Logging.instance.logd( "my nym account: $account", level: LogLevel.Info, ); diff --git a/lib/pages_desktop_specific/coin_control/freeze_button.dart b/lib/pages_desktop_specific/coin_control/freeze_button.dart index dddcc92fa..440a65fd8 100644 --- a/lib/pages_desktop_specific/coin_control/freeze_button.dart +++ b/lib/pages_desktop_specific/coin_control/freeze_button.dart @@ -11,11 +11,12 @@ import 'package:async/async.dart'; import 'package:flutter/material.dart'; import 'package:isar/isar.dart'; + import '../../db/isar/main_db.dart'; import '../../models/isar/models/blockchain_data/utxo.dart'; -import 'utxo_row.dart'; import '../../utilities/logger.dart'; import '../../widgets/desktop/primary_button.dart'; +import 'utxo_row.dart'; class FreezeButton extends StatefulWidget { const FreezeButton({ @@ -78,7 +79,7 @@ class _FreezeButtonState extends State { break; default: - Logging.instance.log( + Logging.instance.logd( "Unknown utxo method name found in $runtimeType", level: LogLevel.Fatal, ); diff --git a/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_2.dart b/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_2.dart index a7f76c7e8..a7f096d22 100644 --- a/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_2.dart +++ b/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_2.dart @@ -83,7 +83,7 @@ class _DesktopStep2State extends ConsumerState { ref.read(desktopExchangeModelProvider)!.recipientAddress = info.item2; } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Info); + Logging.instance.logd("$e\n$s", level: LogLevel.Info); } widget.enableNextChanged.call( @@ -116,7 +116,7 @@ class _DesktopStep2State extends ConsumerState { ref.read(desktopExchangeModelProvider)!.refundAddress = info.item2; } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Info); + Logging.instance.logd("$e\n$s", level: LogLevel.Info); } widget.enableNextChanged.call( _next(), diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart index 9893a6cae..3676f1192 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart @@ -298,7 +298,7 @@ class _DesktopWalletViewState extends ConsumerState { ), Text( WalletDevTools.checkFiroTransactionTally( - widget.walletId, + wallet, ), ), ], diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart index 0fb65c635..ddf4f14f6 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart @@ -150,7 +150,7 @@ class _DesktopSendState extends ConsumerState { builder: (context) => const QrCodeScannerDialog(), ); if (qrResult == null) { - Logging.instance.log( + Logging.instance.logd( "Qr scanning cancelled", level: LogLevel.Info, ); @@ -158,14 +158,14 @@ class _DesktopSendState extends ConsumerState { try { _processQrCodeData(qrResult); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error processing QR code data: $e\n$s", level: LogLevel.Error, ); } } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error opening QR code scanner dialog: $e\n$s", level: LogLevel.Error, ); @@ -513,7 +513,7 @@ class _DesktopSendState extends ConsumerState { ); } } catch (e, s) { - Logging.instance.log("Desktop send: $e\n$s", level: LogLevel.Error); + Logging.instance.logd("Desktop send: $e\n$s", level: LogLevel.Error); if (mounted) { // pop building dialog Navigator.of( @@ -618,7 +618,7 @@ class _DesktopSendState extends ConsumerState { if (_cachedAmountToSend != null && _cachedAmountToSend == amount) { return; } - Logging.instance.log( + Logging.instance.logd( "it changed $amount $_cachedAmountToSend", level: LogLevel.Info, ); @@ -708,7 +708,7 @@ class _DesktopSendState extends ConsumerState { } } catch (e, s) { Logging.instance - .log("Error processing QR code data: $e\n$s", level: LogLevel.Error); + .logd("Error processing QR code data: $e\n$s", level: LogLevel.Error); } } @@ -858,8 +858,8 @@ class _DesktopSendState extends ConsumerState { return; } _cachedAmountToSend = amount; - Logging.instance - .log("it changed $amount $_cachedAmountToSend", level: LogLevel.Info); + Logging.instance.logd("it changed $amount $_cachedAmountToSend", + level: LogLevel.Info); final amountString = ref.read(pAmountFormatter(coin)).format( amount!, diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart index 158beed86..43d3c23a5 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart @@ -406,7 +406,7 @@ class _DesktopTokenSendState extends ConsumerState { _cachedAmountToSend == _amountToSend) { return; } - Logging.instance.log( + Logging.instance.logd( "it changed $_amountToSend $_cachedAmountToSend", level: LogLevel.Info, ); @@ -471,7 +471,7 @@ class _DesktopTokenSendState extends ConsumerState { final qrResult = await scanner.scan(); - Logging.instance.log( + Logging.instance.logd( "qrResult content: ${qrResult.rawContent}", level: LogLevel.Info, ); @@ -482,7 +482,7 @@ class _DesktopTokenSendState extends ConsumerState { ); Logging.instance - .log("qrResult parsed: $paymentData", level: LogLevel.Info); + .logd("qrResult parsed: $paymentData", level: LogLevel.Info); if (paymentData != null && paymentData.coin?.uriScheme == coin.uriScheme) { @@ -529,7 +529,7 @@ class _DesktopTokenSendState extends ConsumerState { } on PlatformException catch (e, s) { // here we ignore the exception caused by not giving permission // to use the camera to scan a qr code - Logging.instance.log( + Logging.instance.logd( "Failed to get camera permissions while trying to scan qr code in SendView: $e\n$s", level: LogLevel.Warning, ); @@ -586,7 +586,7 @@ class _DesktopTokenSendState extends ConsumerState { return; } _cachedAmountToSend = _amountToSend; - Logging.instance.log( + Logging.instance.logd( "it changed $_amountToSend $_cachedAmountToSend", level: LogLevel.Info, ); diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart index be0f080b1..2d874fffd 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart @@ -319,7 +319,7 @@ class _DesktopWalletFeaturesState extends ConsumerState { final account = await ref.read(paynymAPIProvider).nym(code.toString()); - Logging.instance.log( + Logging.instance.logd( "my nym account: $account", level: LogLevel.Info, ); diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/more_features/more_features_dialog.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/more_features/more_features_dialog.dart index 5559e45bc..38e91701c 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/more_features/more_features_dialog.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/more_features/more_features_dialog.dart @@ -213,7 +213,7 @@ class _MoreFeaturesDialogState extends ConsumerState { } } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); if (mounted) { // show error await showDialog( diff --git a/lib/pages_desktop_specific/password/delete_password_warning_view.dart b/lib/pages_desktop_specific/password/delete_password_warning_view.dart index e8a4c5256..1b6c3d5b1 100644 --- a/lib/pages_desktop_specific/password/delete_password_warning_view.dart +++ b/lib/pages_desktop_specific/password/delete_password_warning_view.dart @@ -87,7 +87,7 @@ class _ForgotPasswordDesktopViewState await DB.instance.init(); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/pages_desktop_specific/password/desktop_login_view.dart b/lib/pages_desktop_specific/password/desktop_login_view.dart index 89447ee57..04fab5bac 100644 --- a/lib/pages_desktop_specific/password/desktop_login_view.dart +++ b/lib/pages_desktop_specific/password/desktop_login_view.dart @@ -75,7 +75,7 @@ class _DesktopLoginViewState extends ConsumerState { secureStore: ref.read(secureStoreProvider), ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Cannot migrate desktop database\n$e $s", level: LogLevel.Error, printFullLength: true, diff --git a/lib/pages_desktop_specific/password/forgotten_passphrase_restore_from_swb.dart b/lib/pages_desktop_specific/password/forgotten_passphrase_restore_from_swb.dart index a20660779..4030e6c50 100644 --- a/lib/pages_desktop_specific/password/forgotten_passphrase_restore_from_swb.dart +++ b/lib/pages_desktop_specific/password/forgotten_passphrase_restore_from_swb.dart @@ -271,7 +271,7 @@ class _ForgottenPassphraseRestoreFromSWBState }); } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); } }, child: MouseRegion( diff --git a/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/advanced_settings.dart b/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/advanced_settings.dart index e96a5288c..60a164b8f 100644 --- a/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/advanced_settings.dart +++ b/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/advanced_settings.dart @@ -363,7 +363,7 @@ class _AdvancedSettings extends ConsumerState { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( - "Debug info", + "Logging", style: STextStyles.desktopTextExtraSmall(context) .copyWith( color: Theme.of(context) @@ -374,7 +374,7 @@ class _AdvancedSettings extends ConsumerState { ), PrimaryButton( buttonHeight: ButtonHeight.xs, - label: "Show logs", + label: "View", width: 101, onPressed: () async { await showDialog( @@ -382,7 +382,7 @@ class _AdvancedSettings extends ConsumerState { useSafeArea: false, barrierDismissible: true, builder: (context) { - return const DebugInfoDialog(); + return const DesktopLoggingDialog(); }, ); }, diff --git a/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/debug_info_dialog.dart b/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/debug_info_dialog.dart index dedfe999d..14048b7d9 100644 --- a/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/debug_info_dialog.dart +++ b/lib/pages_desktop_specific/settings/settings_menu/advanced_settings/debug_info_dialog.dart @@ -1,6 +1,6 @@ -/* +/* * 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. @@ -9,129 +9,101 @@ */ import 'dart:async'; +import 'dart:io'; -import 'package:event_bus/event_bus.dart'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; -import '../../../../models/isar/models/log.dart'; -import '../../../../notifications/show_flush_bar.dart'; -import '../../../../providers/global/debug_service_provider.dart'; +import '../../../../app_config.dart'; +import '../../../../providers/global/prefs_provider.dart'; import '../../../../themes/stack_colors.dart'; import '../../../../utilities/assets.dart'; -import '../../../../utilities/constants.dart'; import '../../../../utilities/logger.dart'; -import '../../../../utilities/show_loading.dart'; import '../../../../utilities/text_styles.dart'; -import '../../../../utilities/util.dart'; import '../../../../widgets/desktop/desktop_dialog.dart'; import '../../../../widgets/desktop/desktop_dialog_close_button.dart'; import '../../../../widgets/desktop/primary_button.dart'; -import '../../../../widgets/desktop/secondary_button.dart'; -import '../../../../widgets/icon_widgets/x_icon.dart'; -import '../../../../widgets/rounded_container.dart'; +import '../../../../widgets/log_level_preference_widget.dart'; +import '../../../../widgets/rounded_white_container.dart'; import '../../../../widgets/stack_dialog.dart'; -import '../../../../widgets/stack_text_field.dart'; -import '../../../../widgets/textfield_icon_button.dart'; -class DebugInfoDialog extends ConsumerStatefulWidget { - const DebugInfoDialog({super.key}); +class DesktopLoggingDialog extends ConsumerStatefulWidget { + const DesktopLoggingDialog({super.key}); @override - ConsumerState createState() => _DebugInfoDialog(); + ConsumerState createState() => _DebugInfoDialog(); } -class _DebugInfoDialog extends ConsumerState { - late final TextEditingController searchDebugController; - late final FocusNode searchDebugFocusNode; - - final scrollController = ScrollController(); +class _DebugInfoDialog extends ConsumerState { + late final TextEditingController fileLocationController; + bool _lock = false; - String _searchTerm = ""; + Future _edit() async { + final currentPath = ref.read(prefsChangeNotifierProvider).logsPath ?? + Logging.instance.logsDirPath; + final newPath = await _pickDir(context, currentPath); - List filtered(List unfiltered, String filter) { - if (filter == "") { - return unfiltered; - } - return unfiltered - .where( - (e) => (e.toString().toLowerCase().contains(filter.toLowerCase())), - ) - .toList(); - } - - BorderRadius? _borderRadius(int index, int listLength) { - if (index == 0 && listLength == 1) { - return BorderRadius.circular( - Constants.size.circularBorderRadius, - ); - } else if (index == 0) { - return BorderRadius.vertical( - bottom: Radius.circular( - Constants.size.circularBorderRadius, - ), - ); - } else if (index == listLength - 1) { - return BorderRadius.vertical( - top: Radius.circular( - Constants.size.circularBorderRadius, - ), + // test if has permission to write + if (newPath != null) { + final file = File( + "$newPath${Platform.pathSeparator}._test", ); + if (!file.existsSync()) { + file.createSync(); + file.deleteSync(); + } } - return null; - } - bool _lock = false; - Future<(String?, bool)?> _saveFile() async { - final path = await FilePicker.platform.getDirectoryPath( - dialogTitle: "Choose Log Save Location", - lockParentWindow: true, - ); + // success + ref.read(prefsChangeNotifierProvider).logsPath = newPath; - if (path == null) { - return null; + if (mounted) { + setState(() { + fileLocationController.text = + ref.read(prefsChangeNotifierProvider).logsPath ?? + Logging.instance.logsDirPath; + }); } + } - bool logsSaved = true; - String? filename; - try { - filename = - await ref.read(debugServiceProvider).exportToFile(path, EventBus()); - } catch (e, s) { - logsSaved = false; - Logging.instance.log("$e $s", level: LogLevel.Error); + Future _pickDir(BuildContext context, String currentPath) async { + final String? chosenPath; + if (Platform.isIOS) { + chosenPath = currentPath; + } else { + final String path = + Platform.isWindows ? currentPath.replaceAll("/", "\\") : currentPath; + chosenPath = await FilePicker.platform.getDirectoryPath( + dialogTitle: "Choose Log Save location", + initialDirectory: path, + lockParentWindow: true, + ); } - return (filename, logsSaved); + return chosenPath; } @override void initState() { - searchDebugController = TextEditingController(); - searchDebugFocusNode = FocusNode(); - super.initState(); + fileLocationController = TextEditingController(); + fileLocationController.text = + ref.read(prefsChangeNotifierProvider).logsPath ?? + Logging.instance.logsDirPath; } @override void dispose() { - searchDebugFocusNode.dispose(); - searchDebugController.dispose(); - - scrollController.dispose(); - + fileLocationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return DesktopDialog( - // Max height of 850 unless the screen is smaller than that. - maxHeight: MediaQuery.of(context).size.height < 850 - ? MediaQuery.of(context).size.height - : 850, - maxWidth: 600, + maxHeight: double.infinity, + maxWidth: 640, child: Column( children: [ Row( @@ -140,7 +112,7 @@ class _DebugInfoDialog extends ConsumerState { Padding( padding: const EdgeInsets.all(32), child: Text( - "Debug info", + "Logging", style: STextStyles.desktopH3(context), textAlign: TextAlign.center, ), @@ -150,287 +122,143 @@ class _DebugInfoDialog extends ConsumerState { ), Padding( padding: const EdgeInsets.symmetric(horizontal: 32), - child: ClipRRect( - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius, - ), - child: TextField( - autocorrect: Util.isDesktop ? false : true, - enableSuggestions: Util.isDesktop ? false : true, - controller: searchDebugController, - focusNode: searchDebugFocusNode, - onChanged: (newString) { - setState(() => _searchTerm = newString); - }, - style: STextStyles.field(context), - decoration: standardInputDecoration( - "Search", - searchDebugFocusNode, - context, - ).copyWith( - prefixIcon: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 10, - vertical: 16, - ), - child: SvgPicture.asset( - Assets.svg.search, - width: 16, - height: 16, - ), - ), - suffixIcon: searchDebugController.text.isNotEmpty - ? Padding( - padding: const EdgeInsets.only(right: 0), - child: UnconstrainedBox( - child: Row( - children: [ - TextFieldIconButton( - child: const XIcon(), - onTap: () async { - setState(() { - searchDebugController.text = ""; - _searchTerm = ""; - }); - }, - ), - ], - ), - ), - ) - : null, + child: Row( + children: [ + Text( + "Log files location", + style: STextStyles.desktopTextFieldLabel(context), + textAlign: TextAlign.left, ), - ), + ], ), ), - Expanded( - // flex: 24, - child: NestedScrollView( - // floatHeaderSlivers: true, - headerSliverBuilder: (context, innerBoxIsScrolled) { - return [ - SliverOverlapAbsorber( - handle: NestedScrollView.sliverOverlapAbsorberHandleFor( - context, - ), - sliver: const SliverToBoxAdapter( - child: Padding( - padding: EdgeInsets.symmetric( - vertical: 16, - horizontal: 32, - ), - child: Column( - children: [], - ), + const SizedBox( + height: 10, + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 32), + child: TextField( + autocorrect: false, + enableSuggestions: false, + controller: fileLocationController, + style: STextStyles.field(context), + decoration: InputDecoration( + hintText: "Save to...", + hintStyle: STextStyles.fieldLabel(context), + suffixIcon: UnconstrainedBox( + child: Row( + children: [ + const SizedBox( + width: 16, ), - ), - ), - ]; - }, - body: Builder( - builder: (context) { - final logs = filtered( - ref.watch( - debugServiceProvider.select((value) => value.recentLogs), - ), - _searchTerm, - ).reversed.toList(growable: false); - return CustomScrollView( - reverse: true, - // shrinkWrap: true, - controller: scrollController, - slivers: [ - SliverOverlapInjector( - handle: NestedScrollView.sliverOverlapAbsorberHandleFor( - context, - ), + SvgPicture.asset( + Assets.svg.folder, + color: Theme.of(context) + .extension()! + .textDark3, + width: 16, + height: 16, ), - SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) { - final log = logs[index]; - - return Container( - key: Key( - "log_${log.id}_${log.timestampInMillisUTC}", - ), - decoration: BoxDecoration( - color: Theme.of(context) - .extension()! - .popupBG, - borderRadius: _borderRadius(index, logs.length), - ), - child: Padding( - padding: const EdgeInsets.all(4), - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 32, - ), - child: RoundedContainer( - padding: const EdgeInsets.all(0), - color: Theme.of(context) - .extension()! - .popupBG, - child: Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - Row( - children: [ - Text( - " [${log.logLevel.name}]", - style: STextStyles.baseXS(context) - .copyWith( - fontSize: 8, - color: (log.logLevel == - LogLevel.Info - ? Theme.of(context) - .extension< - StackColors>()! - .topNavIconGreen - : (log.logLevel == - LogLevel.Warning - ? Theme.of(context) - .extension< - StackColors>()! - .topNavIconYellow - : (log.logLevel == - LogLevel.Error - ? Colors.orange - : Theme.of(context) - .extension< - StackColors>()! - .topNavIconRed))), - ), - ), - Text( - "[${DateTime.fromMillisecondsSinceEpoch(log.timestampInMillisUTC, isUtc: true)}]: ", - style: STextStyles.baseXS(context) - .copyWith( - fontSize: 12, - color: Theme.of(context) - .extension()! - .textDark3, - ), - ), - ], - ), - Row( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - const SizedBox( - width: 20, - ), - Flexible( - child: Column( - crossAxisAlignment: - CrossAxisAlignment.start, - children: [ - SelectableText( - log.message, - style: STextStyles.baseXS( - context, - ).copyWith( - fontSize: 11.5, - ), - ), - ], - ), - ), - ], - ), - ], - ), - ), - ), - ), - ); - }, - childCount: logs.length, - ), + const SizedBox( + width: 12, ), ], - ); - }, + ), + ), + ), + key: const Key( + "logsDirPathLocationControllerKey", ), + readOnly: true, + toolbarOptions: const ToolbarOptions( + copy: true, + cut: false, + paste: false, + selectAll: false, + ), + onChanged: (newValue) {}, ), ), - // const Spacer(), - Padding( - padding: const EdgeInsets.all(32), - child: Row( - children: [ - Expanded( - child: SecondaryButton( - label: "Clear logs", - onPressed: () async { - await ref.read(debugServiceProvider).deleteAllLogs(); - setState(() {}); - - if (context.mounted) { - Navigator.pop(context); - unawaited( - showFloatingFlushBar( - type: FlushBarType.info, - context: context, - message: 'Logs cleared!', - ), - ); - } - }, + const SizedBox( + height: 8, + ), + const Padding( + padding: EdgeInsets.all(32), + child: LogLevelPreferenceWidget(), + ), + if (!Platform.isMacOS) + const SizedBox( + height: 8, + ), + if (!Platform.isMacOS) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 32), + child: Row( + children: [ + Expanded( + child: RoundedWhiteContainer( + borderColor: Theme.of(context) + .extension()! + .textSubtitle6, + child: Text( + "NOTE: ${AppConfig.appName} must be restarted in order" + " for changes to take effect.", + style: STextStyles.desktopTextExtraExtraSmall(context), + ), + ), ), - ), - const SizedBox( - width: 16, - ), - Expanded( - child: PrimaryButton( - label: "Save logs to file", - onPressed: () async { - if (_lock) { - return; - } - _lock = true; - try { - final results = await showLoading<(String?, bool)?>( - whileFuture: _saveFile(), - context: context, - message: "Generating logs file...", - ); - - if (results != null) { - if (results.$2) { - unawaited( - showDialog( - context: context, - builder: (context) => StackOkDialog( - title: "Logs saved to", - message: results.$1, - ), - ), - ); - } else { + ], + ), + ), + if (!Platform.isMacOS) + const SizedBox( + height: 16, + ), + if (!Platform.isMacOS) + Padding( + padding: const EdgeInsets.all(32), + child: Row( + children: [ + const Spacer(), + const SizedBox( + width: 16, + ), + Expanded( + child: PrimaryButton( + label: "Select log save location", + onPressed: () async { + if (_lock) { + return; + } + _lock = true; + try { + await _edit(); + } catch (e, s) { + Logging.instance.e( + "Failed to change logs path", + error: e, + stackTrace: s, + ); + if (context.mounted) { unawaited( showDialog( context: context, builder: (context) => StackOkDialog( - title: "Error Saving Logs", - message: results.$1, + title: "Failed to change logs path", + message: e.toString(), ), ), ); } + } finally { + _lock = false; } - } finally { - _lock = false; - } - }, + }, + ), ), - ), - ], + ], + ), ), - ), ], ), ); diff --git a/lib/pages_desktop_specific/settings/settings_menu/appearance_settings/sub_widgets/desktop_install_theme.dart b/lib/pages_desktop_specific/settings/settings_menu/appearance_settings/sub_widgets/desktop_install_theme.dart index 081540c3b..3ad0f0f1f 100644 --- a/lib/pages_desktop_specific/settings/settings_menu/appearance_settings/sub_widgets/desktop_install_theme.dart +++ b/lib/pages_desktop_specific/settings/settings_menu/appearance_settings/sub_widgets/desktop_install_theme.dart @@ -14,6 +14,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:share_plus/share_plus.dart'; + import '../../../../../themes/stack_colors.dart'; import '../../../../../themes/theme_service.dart'; import '../../../../../utilities/assets.dart'; @@ -56,7 +57,7 @@ class _DesktopInstallThemeState extends ConsumerState { ]); return true; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to install theme: $e\n$s", level: LogLevel.Warning, ); @@ -81,7 +82,7 @@ class _DesktopInstallThemeState extends ConsumerState { } } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); } } diff --git a/lib/pages_desktop_specific/settings/settings_menu/backup_and_restore/create_auto_backup.dart b/lib/pages_desktop_specific/settings/settings_menu/backup_and_restore/create_auto_backup.dart index bf5f3e009..3ed9aafc2 100644 --- a/lib/pages_desktop_specific/settings/settings_menu/backup_and_restore/create_auto_backup.dart +++ b/lib/pages_desktop_specific/settings/settings_menu/backup_and_restore/create_auto_backup.dart @@ -202,7 +202,7 @@ class _CreateAutoBackup extends ConsumerState { } } catch (e, s) { Logging.instance - .log("$e\n$s", level: LogLevel.Error); + .logd("$e\n$s", level: LogLevel.Error); } }, controller: fileLocationController, @@ -700,7 +700,7 @@ class _CreateAutoBackup extends ConsumerState { final String err = getErrorMessageFromSWBException(e); Logging.instance - .log("$err\n$s", level: LogLevel.Error); + .logd("$err\n$s", level: LogLevel.Error); // pop encryption progress dialog Navigator.of(context).pop(); unawaited( @@ -713,7 +713,7 @@ class _CreateAutoBackup extends ConsumerState { return; } catch (e, s) { Logging.instance - .log("$e\n$s", level: LogLevel.Error); + .logd("$e\n$s", level: LogLevel.Error); // pop encryption progress dialog Navigator.of(context).pop(); unawaited( diff --git a/lib/pages_desktop_specific/settings/settings_menu/tor_settings/tor_settings.dart b/lib/pages_desktop_specific/settings/settings_menu/tor_settings/tor_settings.dart index d01a5d678..6b698048a 100644 --- a/lib/pages_desktop_specific/settings/settings_menu/tor_settings/tor_settings.dart +++ b/lib/pages_desktop_specific/settings/settings_menu/tor_settings/tor_settings.dart @@ -71,7 +71,7 @@ class _TorSettingsState extends ConsumerState { // Toggle the useTor preference on success. ref.read(prefsChangeNotifierProvider).useTor = true; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error starting tor: $e\n$s", level: LogLevel.Error, ); @@ -101,7 +101,7 @@ class _TorSettingsState extends ConsumerState { // Toggle the useTor preference on success. ref.read(prefsChangeNotifierProvider).useTor = false; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error stopping tor: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/providers/global/debug_service_provider.dart b/lib/providers/global/debug_service_provider.dart deleted file mode 100644 index 4d666cdcf..000000000 --- a/lib/providers/global/debug_service_provider.dart +++ /dev/null @@ -1,15 +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 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../../services/debug_service.dart'; - -final debugServiceProvider = - ChangeNotifierProvider((ref) => DebugService.instance); diff --git a/lib/route_generator.dart b/lib/route_generator.dart index bcfffa8cd..71a3b890e 100644 --- a/lib/route_generator.dart +++ b/lib/route_generator.dart @@ -91,7 +91,7 @@ import 'pages/send_view/send_view.dart'; import 'pages/send_view/token_send_view.dart'; import 'pages/settings_views/global_settings_view/about_view.dart'; import 'pages/settings_views/global_settings_view/advanced_views/advanced_settings_view.dart'; -import 'pages/settings_views/global_settings_view/advanced_views/debug_view.dart'; +import 'pages/settings_views/global_settings_view/advanced_views/logging_settings_view.dart'; import 'pages/settings_views/global_settings_view/advanced_views/manage_coin_units/edit_coin_units_view.dart'; import 'pages/settings_views/global_settings_view/advanced_views/manage_coin_units/manage_coin_units_view.dart'; import 'pages/settings_views/global_settings_view/advanced_views/manage_explorer_view.dart'; @@ -951,10 +951,10 @@ class RouteGenerator { settings: RouteSettings(name: settings.name), ); - case DebugView.routeName: + case LoggingSettingsView.routeName: return getRoute( shouldUseMaterialRoute: useMaterialPageRoute, - builder: (_) => const DebugView(), + builder: (_) => const LoggingSettingsView(), settings: RouteSettings(name: settings.name), ); diff --git a/lib/services/auto_swb_service.dart b/lib/services/auto_swb_service.dart index 1113b30f1..4a44dfae3 100644 --- a/lib/services/auto_swb_service.dart +++ b/lib/services/auto_swb_service.dart @@ -42,14 +42,14 @@ class AutoSWBService extends ChangeNotifier { /// Attempt a backup. Future doBackup() async { if (_status == AutoSWBStatus.backingUp) { - Logging.instance.log( + Logging.instance.logd( "AutoSWBService attempted to run doBackup() while a backup is in progress!", level: LogLevel.Warning, ); return; } Logging.instance - .log("AutoSWBService.doBackup() started...", level: LogLevel.Info); + .logd("AutoSWBService.doBackup() started...", level: LogLevel.Info); // set running backup status and notify listeners _status = AutoSWBStatus.backingUp; @@ -62,7 +62,7 @@ class AutoSWBService extends ChangeNotifier { final autoBackupDirectoryPath = Prefs.instance.autoBackupLocation; if (autoBackupDirectoryPath == null) { - Logging.instance.log( + Logging.instance.logd( "AutoSWBService attempted to run doBackup() when no auto backup directory was set!", level: LogLevel.Error, ); @@ -105,16 +105,16 @@ class AutoSWBService extends ChangeNotifier { trimBackups(autoBackupDirectoryPath, 3); Logging.instance - .log("AutoSWBService.doBackup() succeeded", level: LogLevel.Info); + .logd("AutoSWBService.doBackup() succeeded", level: LogLevel.Info); } on Exception catch (e, s) { final String err = getErrorMessageFromSWBException(e); - Logging.instance.log("$err\n$s", level: LogLevel.Error); + Logging.instance.logd("$err\n$s", level: LogLevel.Error); // set error backup status and notify listeners _status = AutoSWBStatus.error; notifyListeners(); return; } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); // set error backup status and notify listeners _status = AutoSWBStatus.error; notifyListeners(); diff --git a/lib/services/buy/simplex/simplex_api.dart b/lib/services/buy/simplex/simplex_api.dart index 5bbb82c1c..7242ee295 100644 --- a/lib/services/buy/simplex/simplex_api.dart +++ b/lib/services/buy/simplex/simplex_api.dart @@ -72,7 +72,7 @@ class SimplexAPI { return _parseSupportedCryptos(jsonArray); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableCurrencies exception: $e\n$s", level: LogLevel.Error, ); @@ -107,7 +107,7 @@ class SimplexAPI { return BuyResponse(value: cryptos); } catch (e, s) { Logging.instance - .log("_parseSupported exception: $e\n$s", level: LogLevel.Error); + .logd("_parseSupported exception: $e\n$s", level: LogLevel.Error); return BuyResponse( exception: BuyException( e.toString(), @@ -143,7 +143,7 @@ class SimplexAPI { return _parseSupportedFiats(jsonArray); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableCurrencies exception: $e\n$s", level: LogLevel.Error, ); @@ -180,7 +180,7 @@ class SimplexAPI { return BuyResponse(value: fiats); } catch (e, s) { Logging.instance - .log("_parseSupported exception: $e\n$s", level: LogLevel.Error); + .logd("_parseSupported exception: $e\n$s", level: LogLevel.Error); return BuyResponse( exception: BuyException( e.toString(), @@ -236,7 +236,8 @@ class SimplexAPI { return _parseQuote(jsonArray); } catch (e, s) { - Logging.instance.log("getQuote exception: $e\n$s", level: LogLevel.Error); + Logging.instance + .logd("getQuote exception: $e\n$s", level: LogLevel.Error); return BuyResponse( exception: BuyException( e.toString(), @@ -281,7 +282,7 @@ class SimplexAPI { return BuyResponse(value: _quote); } catch (e, s) { Logging.instance - .log("_parseQuote exception: $e\n$s", level: LogLevel.Error); + .logd("_parseQuote exception: $e\n$s", level: LogLevel.Error); return BuyResponse( exception: BuyException( e.toString(), @@ -350,7 +351,8 @@ class SimplexAPI { return BuyResponse(value: _order); } catch (e, s) { - Logging.instance.log("newOrder exception: $e\n$s", level: LogLevel.Error); + Logging.instance + .logd("newOrder exception: $e\n$s", level: LogLevel.Error); return BuyResponse( exception: BuyException( e.toString(), @@ -378,7 +380,8 @@ class SimplexAPI { return BuyResponse(value: status); } catch (e, s) { - Logging.instance.log("newOrder exception: $e\n$s", level: LogLevel.Error); + Logging.instance + .logd("newOrder exception: $e\n$s", level: LogLevel.Error); return BuyResponse( exception: BuyException( e.toString(), diff --git a/lib/services/coins/tezos/api/tezos_api.dart b/lib/services/coins/tezos/api/tezos_api.dart index e646019ee..776e0e700 100644 --- a/lib/services/coins/tezos/api/tezos_api.dart +++ b/lib/services/coins/tezos/api/tezos_api.dart @@ -25,7 +25,7 @@ abstract final class TezosAPI { final result = jsonDecode(response.body); return result as int; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in TezosAPI while getting counter for $address: $e\n$s", level: LogLevel.Error, ); @@ -53,7 +53,7 @@ abstract final class TezosAPI { return account; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in TezosAPI while getting account for $address: $e\n$s", level: LogLevel.Error, ); @@ -109,7 +109,7 @@ abstract final class TezosAPI { } return txs; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in TezosAPI while getting transactions for $address: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/services/coins/tezos/api/tezos_rpc_api.dart b/lib/services/coins/tezos/api/tezos_rpc_api.dart index 59ca98045..afddfa4c3 100644 --- a/lib/services/coins/tezos/api/tezos_rpc_api.dart +++ b/lib/services/coins/tezos/api/tezos_rpc_api.dart @@ -28,7 +28,7 @@ abstract final class TezosRpcAPI { BigInt.parse(response.body.substring(1, response.body.length - 2)); return balance; } catch (e) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in tezos_rpc_api.dart while getting balance for $address: $e", level: LogLevel.Error, ); @@ -54,7 +54,7 @@ abstract final class TezosRpcAPI { final jsonParsedResponse = jsonDecode(response.body); return int.parse(jsonParsedResponse["level"].toString()); } catch (e) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in tezos_rpc_api.dart while getting chain height for tezos: $e", level: LogLevel.Error, ); diff --git a/lib/services/debug_service.dart b/lib/services/debug_service.dart deleted file mode 100644 index 4d6e51553..000000000 --- a/lib/services/debug_service.dart +++ /dev/null @@ -1,125 +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:io'; - -import 'package:event_bus/event_bus.dart'; -import 'package:flutter/material.dart'; -import 'package:isar/isar.dart'; - -import '../app_config.dart'; -import '../models/isar/models/log.dart'; -import '../utilities/logger.dart'; - -class DebugService extends ChangeNotifier { - DebugService._(); - static final DebugService _instance = DebugService._(); - static DebugService get instance => _instance; - - late final Isar isar; - // late final Stream logsChanged; - - // bool _shouldPause = false; - // - // void togglePauseUiUpdates() { - // _shouldPause = !_shouldPause; - // notifyListeners(); - // } - - // bool get isPaused => _shouldPause; - - Future init(Isar isar) async { - this.isar = isar; - // logsChanged = this.isar.logs.watchLazy(); - // logsChanged.listen((_) { - // if (!_shouldPause) { - // updateRecentLogs(); - // } - // }); - } - - List get recentLogs => isar.logs - .where() - .sortByTimestampInMillisUTCDesc() - .limit(100) - .findAllSync(); - - // Future updateRecentLogs() async { - // int totalCount = await isar.logs.count(); - // int offset = totalCount - numberOfRecentLogsToLoad; - // if (offset < 0) { - // offset = 0; - // } - // - // _recentLogs = (await isar.logs - // .where() - // .anyTimestampInMillisUTC() - // .offset(offset) - // .limit(numberOfRecentLogsToLoad) - // .findAll()); - // notifyListeners(); - // } - - Future deleteAllLogs() async { - try { - await isar.writeTxn(() async => await isar.logs.clear()); - notifyListeners(); - return true; - } catch (_) { - return false; - } - } - - Future deleteLogsOlderThan({ - Duration timeframe = const Duration(days: 30), - }) async { - final cutoffDate = DateTime.now().subtract(timeframe).toUtc(); - await isar.writeTxn(() async { - await isar.logs - .where() - .timestampInMillisUTCLessThan(cutoffDate.millisecondsSinceEpoch) - .deleteAll(); - }); - - Logging.instance.log( - "Logs older than $cutoffDate cleared!", - level: LogLevel.Info, - ); - } - - /// returns the filename of the saved logs file - Future exportToFile(String directory, EventBus eventBus) async { - final now = DateTime.now(); - final filename = - "${AppConfig.prefix}_Wallet_logs_${now.year}_${now.month}_${now.day}_${now.hour}_${now.minute}_${now.second}.txt"; - final filepath = "$directory/$filename"; - final File file = await File(filepath).create(); - - final sink = file.openWrite(); - final logs = await isar.logs.where().anyTimestampInMillisUTC().findAll(); - final count = logs.length; - int counter = 0; - - for (final log in logs) { - sink.writeln(log); - await sink.flush(); - counter++; - final exportPercent = (counter / count).clamp(0.0, 1.0); - eventBus.fire(exportPercent); - } - - await sink.flush(); - await sink.close(); - - eventBus.fire(1.0); - return filename; - } -} diff --git a/lib/services/ethereum/cached_eth_token_balance.dart b/lib/services/ethereum/cached_eth_token_balance.dart index c241f7231..7841a7580 100644 --- a/lib/services/ethereum/cached_eth_token_balance.dart +++ b/lib/services/ethereum/cached_eth_token_balance.dart @@ -54,7 +54,7 @@ class CachedEthTokenBalance { isar: mainDB.isar, ); } else { - Logging.instance.log( + Logging.instance.logd( "CachedEthTokenBalance.fetchAndUpdateCachedBalance failed: ${response.exception}", level: LogLevel.Warning, ); diff --git a/lib/services/ethereum/ethereum_api.dart b/lib/services/ethereum/ethereum_api.dart index 6f5f2313e..fbfbe52fa 100644 --- a/lib/services/ethereum/ethereum_api.dart +++ b/lib/services/ethereum/ethereum_api.dart @@ -104,7 +104,7 @@ abstract class EthereumAPI { e, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getEthTransactions($address): $e\n$s", level: LogLevel.Error, ); @@ -170,7 +170,7 @@ abstract class EthereumAPI { e, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getEthTransactionByHash($txid): $e\n$s", level: LogLevel.Error, ); @@ -233,7 +233,7 @@ abstract class EthereumAPI { e, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getEthTransactionNonces($txns): $e\n$s", level: LogLevel.Error, ); @@ -291,7 +291,7 @@ abstract class EthereumAPI { e, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getEthTokenTransactionsByTxids($txids): $e\n$s", level: LogLevel.Error, ); @@ -352,7 +352,7 @@ abstract class EthereumAPI { e, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getTokenTransactions($address, $tokenContractAddress): $e\n$s", level: LogLevel.Error, ); @@ -478,7 +478,7 @@ abstract class EthereumAPI { e, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getWalletTokenBalance(): $e\n$s", level: LogLevel.Error, ); @@ -529,7 +529,7 @@ abstract class EthereumAPI { e, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAddressNonce(): $e\n$s", level: LogLevel.Error, ); @@ -585,7 +585,7 @@ abstract class EthereumAPI { e, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getGasOracle(): $e\n$s", level: LogLevel.Error, ); @@ -643,14 +643,14 @@ abstract class EthereumAPI { if (json["data"] is List) { if ((json["data"] as List).isEmpty) { if (autoNameOnEmpty) { - Logging.instance.log( + Logging.instance.logd( "getTokenByContractAddress(): Adding token data to server", level: LogLevel.Debug, ); // this will add the missing data to server await _addContractInfoToServer(contractAddress); - Logging.instance.log( + Logging.instance.logd( "getTokenByContractAddress(): Adding to server threw so now" "we try a normal fetch again", level: LogLevel.Debug, @@ -709,7 +709,7 @@ abstract class EthereumAPI { e, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getTokenByContractAddress(): $e\n$s", level: LogLevel.Error, ); @@ -753,7 +753,7 @@ abstract class EthereumAPI { e, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getTokenAbi($name, $contractAddress): $e\n$s", level: LogLevel.Error, ); @@ -798,7 +798,7 @@ abstract class EthereumAPI { e, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getProxyTokenImplementationAddress($contractAddress) : $e\n$s", level: LogLevel.Error, ); diff --git a/lib/services/event_bus/events/global/balance_refreshed_event.dart b/lib/services/event_bus/events/global/balance_refreshed_event.dart index 5b7a5028a..d061a5e3e 100644 --- a/lib/services/event_bus/events/global/balance_refreshed_event.dart +++ b/lib/services/event_bus/events/global/balance_refreshed_event.dart @@ -14,7 +14,7 @@ class BalanceRefreshedEvent { final String walletId; BalanceRefreshedEvent(this.walletId) { - Logging.instance.log( + Logging.instance.logd( "BalanceRefreshedEvent fired on $walletId", level: LogLevel.Info, ); diff --git a/lib/services/event_bus/events/global/blocks_remaining_event.dart b/lib/services/event_bus/events/global/blocks_remaining_event.dart index 008d39440..f94fc0b23 100644 --- a/lib/services/event_bus/events/global/blocks_remaining_event.dart +++ b/lib/services/event_bus/events/global/blocks_remaining_event.dart @@ -15,7 +15,7 @@ class BlocksRemainingEvent { String walletId; BlocksRemainingEvent(this.blocksRemaining, this.walletId) { - Logging.instance.log( + Logging.instance.logd( "RefreshPercentChangedEvent fired on $walletId with blocks remaining = $blocksRemaining", level: LogLevel.Info, ); diff --git a/lib/services/event_bus/events/global/node_connection_status_changed_event.dart b/lib/services/event_bus/events/global/node_connection_status_changed_event.dart index 7d3ca2fca..9f60bc9db 100644 --- a/lib/services/event_bus/events/global/node_connection_status_changed_event.dart +++ b/lib/services/event_bus/events/global/node_connection_status_changed_event.dart @@ -19,7 +19,7 @@ class NodeConnectionStatusChangedEvent { CryptoCurrency coin; NodeConnectionStatusChangedEvent(this.newStatus, this.walletId, this.coin) { - Logging.instance.log( + Logging.instance.logd( "NodeConnectionStatusChangedEvent fired in $walletId with arg newStatus = $newStatus", level: LogLevel.Info, ); diff --git a/lib/services/event_bus/events/global/refresh_percent_changed_event.dart b/lib/services/event_bus/events/global/refresh_percent_changed_event.dart index 7429b828e..fcae085b3 100644 --- a/lib/services/event_bus/events/global/refresh_percent_changed_event.dart +++ b/lib/services/event_bus/events/global/refresh_percent_changed_event.dart @@ -15,7 +15,7 @@ class RefreshPercentChangedEvent { String walletId; RefreshPercentChangedEvent(this.percent, this.walletId) { - Logging.instance.log( + Logging.instance.logd( "RefreshPercentChangedEvent fired on $walletId with percent (range of 0.0-1.0)= $percent", level: LogLevel.Info, ); diff --git a/lib/services/event_bus/events/global/tor_connection_status_changed_event.dart b/lib/services/event_bus/events/global/tor_connection_status_changed_event.dart index 9087d37e2..e42991270 100644 --- a/lib/services/event_bus/events/global/tor_connection_status_changed_event.dart +++ b/lib/services/event_bus/events/global/tor_connection_status_changed_event.dart @@ -16,7 +16,7 @@ class TorConnectionStatusChangedEvent { String message = ""; TorConnectionStatusChangedEvent(this.newStatus, this.message) { - Logging.instance.log( + Logging.instance.logd( "TorSyncStatusChangedEvent fired with arg newStatus = $newStatus ($message)", level: LogLevel.Info, ); diff --git a/lib/services/event_bus/events/global/tor_status_changed_event.dart b/lib/services/event_bus/events/global/tor_status_changed_event.dart index 140e01607..2466f4225 100644 --- a/lib/services/event_bus/events/global/tor_status_changed_event.dart +++ b/lib/services/event_bus/events/global/tor_status_changed_event.dart @@ -20,7 +20,7 @@ class TorPreferenceChangedEvent { required this.status, this.message, }) { - Logging.instance.log( + Logging.instance.logd( "TorStatusChangedEvent changed to \"$status\" with message: $message", level: LogLevel.Warning, ); diff --git a/lib/services/event_bus/events/global/updated_in_background_event.dart b/lib/services/event_bus/events/global/updated_in_background_event.dart index 36a23360f..94ad3a3da 100644 --- a/lib/services/event_bus/events/global/updated_in_background_event.dart +++ b/lib/services/event_bus/events/global/updated_in_background_event.dart @@ -18,7 +18,7 @@ class UpdatedInBackgroundEvent { UpdatedInBackgroundEvent(this.message, this.walletId) { if (kDebugMode) { - Logging.instance.log( + Logging.instance.logd( "UpdatedInBackgroundEvent fired with message: $message", level: LogLevel.Info, ); diff --git a/lib/services/event_bus/events/global/wallet_sync_status_changed_event.dart b/lib/services/event_bus/events/global/wallet_sync_status_changed_event.dart index 0f92fb272..497e6a97d 100644 --- a/lib/services/event_bus/events/global/wallet_sync_status_changed_event.dart +++ b/lib/services/event_bus/events/global/wallet_sync_status_changed_event.dart @@ -19,7 +19,7 @@ class WalletSyncStatusChangedEvent { CryptoCurrency coin; WalletSyncStatusChangedEvent(this.newStatus, this.walletId, this.coin) { - Logging.instance.log( + Logging.instance.logd( "WalletSyncStatusChangedEvent fired in $walletId with arg newStatus = $newStatus", level: LogLevel.Info, ); diff --git a/lib/services/exchange/change_now/change_now_api.dart b/lib/services/exchange/change_now/change_now_api.dart index 2882f9d4d..e0b96bf3b 100644 --- a/lib/services/exchange/change_now/change_now_api.dart +++ b/lib/services/exchange/change_now/change_now_api.dart @@ -79,7 +79,7 @@ class ChangeNowAPI { } } catch (e, s) { Logging.instance - .log("_makeRequest($uri) threw: $e\n$s", level: LogLevel.Error); + .logd("_makeRequest($uri) threw: $e\n$s", level: LogLevel.Error); rethrow; } } @@ -103,7 +103,7 @@ class ChangeNowAPI { return parsed; } catch (e, s) { Logging.instance - .log("_makeRequestV2($uri) threw: $e\n$s", level: LogLevel.Error); + .logd("_makeRequestV2($uri) threw: $e\n$s", level: LogLevel.Error); rethrow; } } @@ -129,13 +129,13 @@ class ChangeNowAPI { return parsed; } catch (_) { - Logging.instance - .log("ChangeNOW api failed to parse: $data", level: LogLevel.Error); + Logging.instance.logd("ChangeNOW api failed to parse: $data", + level: LogLevel.Error); rethrow; } } catch (e, s) { Logging.instance - .log("_makePostRequest($uri) threw: $e\n$s", level: LogLevel.Error); + .logd("_makePostRequest($uri) threw: $e\n$s", level: LogLevel.Error); rethrow; } } @@ -173,7 +173,7 @@ class ChangeNowAPI { ); return result; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableCurrencies exception: $e\n$s", level: LogLevel.Error, ); @@ -185,7 +185,7 @@ class ChangeNowAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableCurrencies exception: $e\n$s", level: LogLevel.Error, ); @@ -263,7 +263,7 @@ class ChangeNowAPI { ); return result; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableCurrencies exception: $e\n$s", level: LogLevel.Error, ); @@ -275,7 +275,7 @@ class ChangeNowAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableCurrencies exception: $e\n$s", level: LogLevel.Error, ); @@ -381,7 +381,7 @@ class ChangeNowAPI { } } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getPairedCurrencies exception: $e\n$s", level: LogLevel.Error, ); @@ -395,7 +395,7 @@ class ChangeNowAPI { return ExchangeResponse(value: currencies); } catch (e, s) { Logging.instance - .log("getPairedCurrencies exception: $e\n$s", level: LogLevel.Error); + .logd("getPairedCurrencies exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -435,7 +435,7 @@ class ChangeNowAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getMinimalExchangeAmount exception: $e\n$s", level: LogLevel.Error, ); @@ -478,7 +478,7 @@ class ChangeNowAPI { ), ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getRange exception: $e\n$s", level: LogLevel.Error, ); @@ -551,7 +551,7 @@ class ChangeNowAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getEstimatedExchangeAmount exception: $e\n$s", level: LogLevel.Error, ); @@ -637,7 +637,7 @@ class ChangeNowAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getEstimatedExchangeAmount exception: $e\n$s", level: LogLevel.Error, ); @@ -763,7 +763,7 @@ class ChangeNowAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getEstimatedExchangeAmountV2 exception: $e\n$s", level: LogLevel.Error, ); @@ -797,7 +797,7 @@ class ChangeNowAPI { await compute(_parseFixedRateMarketsJson, jsonArray as List); return result; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableFixedRateMarkets exception: $e\n$s", level: LogLevel.Error, ); @@ -809,7 +809,7 @@ class ChangeNowAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableFixedRateMarkets exception: $e\n$s", level: LogLevel.Error, ); @@ -898,7 +898,7 @@ class ChangeNowAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "createStandardExchangeTransaction exception: $e\n$s", level: LogLevel.Error, ); @@ -973,7 +973,7 @@ class ChangeNowAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "createFixedRateExchangeTransaction exception: $e\n$s", level: LogLevel.Error, ); @@ -1011,8 +1011,8 @@ class ChangeNowAPI { ); } } catch (e, s) { - Logging.instance - .log("getTransactionStatus exception: $e\n$s", level: LogLevel.Error); + Logging.instance.logd("getTransactionStatus exception: $e\n$s", + level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -1041,7 +1041,7 @@ class ChangeNowAPI { ); return result; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableFloatingRatePairs exception: $e\n$s", level: LogLevel.Error, ); @@ -1053,7 +1053,7 @@ class ChangeNowAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableFloatingRatePairs exception: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/services/exchange/exchange_data_loading_service.dart b/lib/services/exchange/exchange_data_loading_service.dart index 811949d6e..1708a1413 100644 --- a/lib/services/exchange/exchange_data_loading_service.dart +++ b/lib/services/exchange/exchange_data_loading_service.dart @@ -145,7 +145,7 @@ class ExchangeDataLoadingService { if (_isar == null) { await initDB(); } - Logging.instance.log( + Logging.instance.logd( "ExchangeDataLoadingService.loadAll starting...", level: LogLevel.Info, ); @@ -185,14 +185,14 @@ class ExchangeDataLoadingService { // wait for all loading futures to complete await Future.wait(futures); - Logging.instance.log( + Logging.instance.logd( "ExchangeDataLoadingService.loadAll finished in ${DateTime.now().difference(start).inSeconds} seconds", level: LogLevel.Info, ); onLoadingComplete?.call(); await _updateCurrentCacheVersion(cacheVersion); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "ExchangeDataLoadingService.loadAll failed after ${DateTime.now().difference(start).inSeconds} seconds: $e\n$s", level: LogLevel.Error, ); @@ -219,7 +219,7 @@ class ExchangeDataLoadingService { await isar.currencies.putAll(responseCurrencies.value!); }); } else { - Logging.instance.log( + Logging.instance.logd( "Failed to load changeNOW currencies: ${responseCurrencies.exception?.message}", level: LogLevel.Error, ); @@ -353,7 +353,7 @@ class ExchangeDataLoadingService { await isar.currencies.putAll(responseCurrencies.value!); }); } else { - Logging.instance.log( + Logging.instance.logd( "loadMajesticBankCurrencies: $responseCurrencies", level: LogLevel.Warning, ); @@ -378,7 +378,7 @@ class ExchangeDataLoadingService { await isar.currencies.putAll(responseCurrencies.value!); }); } else { - Logging.instance.log( + Logging.instance.logd( "loadTrocadorCurrencies: $responseCurrencies", level: LogLevel.Warning, ); @@ -403,7 +403,7 @@ class ExchangeDataLoadingService { await isar.currencies.putAll(responseCurrencies.value!); }); } else { - Logging.instance.log( + Logging.instance.logd( "loadNanswapCurrencies: $responseCurrencies", level: LogLevel.Warning, ); diff --git a/lib/services/exchange/majestic_bank/majestic_bank_api.dart b/lib/services/exchange/majestic_bank/majestic_bank_api.dart index 0dc46343b..5f64112c2 100644 --- a/lib/services/exchange/majestic_bank/majestic_bank_api.dart +++ b/lib/services/exchange/majestic_bank/majestic_bank_api.dart @@ -11,6 +11,7 @@ import 'dart:convert'; import 'package:decimal/decimal.dart'; + import '../../../exceptions/exchange/exchange_exception.dart'; import '../../../exceptions/exchange/majestic_bank/mb_exception.dart'; import '../../../exceptions/exchange/pair_unavailable_exception.dart'; @@ -20,10 +21,10 @@ import '../../../models/exchange/majestic_bank/mb_order_calculation.dart'; import '../../../models/exchange/majestic_bank/mb_order_status.dart'; import '../../../models/exchange/majestic_bank/mb_rate.dart'; import '../../../networking/http.dart'; -import '../exchange_response.dart'; -import '../../tor_service.dart'; import '../../../utilities/logger.dart'; import '../../../utilities/prefs.dart'; +import '../../tor_service.dart'; +import '../exchange_response.dart'; class MajesticBankAPI { static const String scheme = "https"; @@ -60,7 +61,7 @@ class MajesticBankAPI { return parsed; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "_makeRequest($uri) HTTP:$code threw: $e\n$s", level: LogLevel.Error, ); @@ -91,7 +92,8 @@ class MajesticBankAPI { } return ExchangeResponse(value: rates); } catch (e, s) { - Logging.instance.log("getRates exception: $e\n$s", level: LogLevel.Error); + Logging.instance + .logd("getRates exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -125,7 +127,7 @@ class MajesticBankAPI { return ExchangeResponse(value: limit); } catch (e, s) { Logging.instance - .log("getLimits exception: $e\n$s", level: LogLevel.Error); + .logd("getLimits exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -158,7 +160,7 @@ class MajesticBankAPI { return ExchangeResponse(value: limits); } catch (e, s) { Logging.instance - .log("getLimits exception: $e\n$s", level: LogLevel.Error); + .logd("getLimits exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -226,7 +228,7 @@ class MajesticBankAPI { return ExchangeResponse(value: result); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "calculateOrder $fromCurrency-$receiveCurrency exception: $e\n$s", level: LogLevel.Error, ); @@ -275,7 +277,7 @@ class MajesticBankAPI { return ExchangeResponse(value: order); } catch (e, s) { Logging.instance - .log("createOrder exception: $e\n$s", level: LogLevel.Error); + .logd("createOrder exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -329,8 +331,8 @@ class MajesticBankAPI { return ExchangeResponse(value: order); } catch (e, s) { - Logging.instance - .log("createFixedRateOrder exception: $e\n$s", level: LogLevel.Error); + Logging.instance.logd("createFixedRateOrder exception: $e\n$s", + level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -377,7 +379,7 @@ class MajesticBankAPI { return ExchangeResponse(value: status); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "trackOrder exception when trying to parse $json: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/services/exchange/nanswap/nanswap_api.dart b/lib/services/exchange/nanswap/nanswap_api.dart index 41f06f19a..a5435e15f 100644 --- a/lib/services/exchange/nanswap/nanswap_api.dart +++ b/lib/services/exchange/nanswap/nanswap_api.dart @@ -47,7 +47,7 @@ class NanswapAPI { return parsed; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "NanswapAPI._makeRequest($uri) HTTP:$code threw: $e\n$s", level: LogLevel.Error, ); @@ -81,7 +81,7 @@ class NanswapAPI { return parsed; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "NanswapAPI._makePostRequest($uri) HTTP:$code threw: $e\n$s", level: LogLevel.Error, ); @@ -135,7 +135,7 @@ class NanswapAPI { return ExchangeResponse(value: result); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Nanswap.getSupportedCurrencies() exception: $e\n$s", level: LogLevel.Error, ); @@ -199,14 +199,14 @@ class NanswapAPI { ), ); } catch (_) { - Logging.instance.log( + Logging.instance.logd( "Nanswap.getEstimate() response was: $json", level: LogLevel.Error, ); rethrow; } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Nanswap.getEstimate() exception: $e\n$s", level: LogLevel.Error, ); @@ -271,7 +271,7 @@ class NanswapAPI { ), ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Nanswap.getEstimateReverse() exception: $e\n$s", level: LogLevel.Error, ); @@ -322,7 +322,7 @@ class NanswapAPI { ), ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Nanswap.getOrderLimits() exception: $e\n$s", level: LogLevel.Error, ); @@ -419,7 +419,7 @@ class NanswapAPI { rethrow; } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Nanswap.createOrder() exception: $e\n$s", level: LogLevel.Error, ); @@ -502,7 +502,7 @@ class NanswapAPI { rethrow; } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Nanswap.getOrder($id) exception: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/services/exchange/nanswap/nanswap_exchange.dart b/lib/services/exchange/nanswap/nanswap_exchange.dart index a2de87c33..de89b886e 100644 --- a/lib/services/exchange/nanswap/nanswap_exchange.dart +++ b/lib/services/exchange/nanswap/nanswap_exchange.dart @@ -80,7 +80,6 @@ class NanswapExchange extends Exchange { } final t = response.value!; - print(t); return ExchangeResponse( value: Trade( diff --git a/lib/services/exchange/simpleswap/simpleswap_api.dart b/lib/services/exchange/simpleswap/simpleswap_api.dart index 0653ff7c6..4573319e5 100644 --- a/lib/services/exchange/simpleswap/simpleswap_api.dart +++ b/lib/services/exchange/simpleswap/simpleswap_api.dart @@ -59,7 +59,7 @@ class SimpleSwapAPI { return parsed; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "_makeRequest($uri) HTTP:$code threw: $e\n$s", level: LogLevel.Error, ); @@ -89,7 +89,7 @@ class SimpleSwapAPI { throw Exception("response: ${response.body}"); } catch (e, s) { Logging.instance - .log("_makeRequest($uri) threw: $e\n$s", level: LogLevel.Error); + .logd("_makeRequest($uri) threw: $e\n$s", level: LogLevel.Error); rethrow; } } @@ -149,7 +149,7 @@ class SimpleSwapAPI { ); return ExchangeResponse(value: trade, exception: null); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableCurrencies exception: $e\n$s", level: LogLevel.Error, ); @@ -177,7 +177,7 @@ class SimpleSwapAPI { return await compute(_parseAvailableCurrenciesJson, jsonArray as List); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableCurrencies exception: $e\n$s", level: LogLevel.Error, ); @@ -212,7 +212,7 @@ class SimpleSwapAPI { return ExchangeResponse(value: currencies); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "_parseAvailableCurrenciesJson exception: $e\n$s", level: LogLevel.Error, ); @@ -247,7 +247,7 @@ class SimpleSwapAPI { ); } catch (e, s) { Logging.instance - .log("getCurrency exception: $e\n$s", level: LogLevel.Error); + .logd("getCurrency exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -280,7 +280,7 @@ class SimpleSwapAPI { return result; } catch (e, s) { Logging.instance - .log("getAllPairs exception: $e\n$s", level: LogLevel.Error); + .logd("getAllPairs exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -321,7 +321,7 @@ class SimpleSwapAPI { return ExchangeResponse(value: pairs); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "_parseAvailableCurrenciesJson exception: $e\n$s", level: LogLevel.Error, ); @@ -359,7 +359,7 @@ class SimpleSwapAPI { return ExchangeResponse(value: jsonObject as String); } catch (e, s) { Logging.instance - .log("getEstimated exception: $e\n$s", level: LogLevel.Error); + .logd("getEstimated exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -416,7 +416,7 @@ class SimpleSwapAPI { return ExchangeResponse(value: trade); } catch (e, s) { Logging.instance - .log("getExchange exception: $e\n$s", level: LogLevel.Error); + .logd("getExchange exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -454,7 +454,8 @@ class SimpleSwapAPI { ), ); } catch (e, s) { - Logging.instance.log("getRange exception: $e\n$s", level: LogLevel.Error); + Logging.instance + .logd("getRange exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -488,7 +489,7 @@ class SimpleSwapAPI { ); return result; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableFixedRateMarkets exception: $e\n$s", level: LogLevel.Error, ); @@ -500,7 +501,7 @@ class SimpleSwapAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getAvailableFixedRateMarkets exception: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/services/exchange/trocador/trocador_api.dart b/lib/services/exchange/trocador/trocador_api.dart index fa791d7d4..09eaeefe8 100644 --- a/lib/services/exchange/trocador/trocador_api.dart +++ b/lib/services/exchange/trocador/trocador_api.dart @@ -70,7 +70,7 @@ abstract class TrocadorAPI { return json; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "_makeRequest($uri) HTTP:$code threw: $e\n$s", level: LogLevel.Error, ); @@ -106,7 +106,8 @@ abstract class TrocadorAPI { throw Exception("unexpected json: $json"); } } catch (e, s) { - Logging.instance.log("getCoins exception: $e\n$s", level: LogLevel.Error); + Logging.instance + .logd("getCoins exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -136,7 +137,8 @@ abstract class TrocadorAPI { return ExchangeResponse(value: TrocadorTrade.fromMap(map)); } catch (e, s) { - Logging.instance.log("getTrade exception: $e\n$s", level: LogLevel.Error); + Logging.instance + .logd("getTrade exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -211,7 +213,7 @@ abstract class TrocadorAPI { return ExchangeResponse(value: TrocadorRate.fromMap(map)); } catch (e, s) { Logging.instance - .log("getNewRate exception: $e\n$s", level: LogLevel.Error); + .logd("getNewRate exception: $e\n$s", level: LogLevel.Error); return ExchangeResponse( exception: ExchangeException( e.toString(), @@ -326,7 +328,7 @@ abstract class TrocadorAPI { "This trade couldn't be completed. Please select another provider."; } - Logging.instance.log( + Logging.instance.logd( "_getNewTrade failed to parse response: $json\n$e\n$s", level: LogLevel.Error, ); @@ -338,7 +340,7 @@ abstract class TrocadorAPI { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "_getNewTrade exception: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/services/frost.dart b/lib/services/frost.dart index a3e2e030f..d0dc08d99 100644 --- a/lib/services/frost.dart +++ b/lib/services/frost.dart @@ -35,7 +35,7 @@ abstract class Frost { return participants; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getParticipants failed: $e\n$s", level: LogLevel.Fatal, ); @@ -48,7 +48,7 @@ abstract class Frost { decodeMultisigConfig(multisigConfig: encodedConfig); return true; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "validateEncodedMultisigConfig failed: $e\n$s", level: LogLevel.Fatal, ); @@ -66,7 +66,7 @@ abstract class Frost { return threshold; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getThreshold failed: $e\n$s", level: LogLevel.Fatal, ); @@ -144,7 +144,7 @@ abstract class Frost { inputs: outputs, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "extractDataFromSignConfig failed: $e\n$s", level: LogLevel.Fatal, ); @@ -168,7 +168,7 @@ abstract class Frost { return config; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "createMultisigConfig failed: $e\n$s", level: LogLevel.Fatal, ); @@ -204,7 +204,7 @@ abstract class Frost { secretShareMachineWrapperPtr: machinePtr, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "startKeyGeneration failed: $e\n$s", level: LogLevel.Fatal, ); @@ -234,7 +234,7 @@ abstract class Frost { return (share: share, secretSharesResPtr: secretSharesResPtr); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "generateSecretShares failed: $e\n$s", level: LogLevel.Fatal, ); @@ -275,7 +275,7 @@ abstract class Frost { serializedKeys: serializedKeys, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "completeKeyGeneration failed: $e\n$s", level: LogLevel.Fatal, ); @@ -322,7 +322,7 @@ abstract class Frost { return signConfig; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "createSignConfig failed: $e\n$s", level: LogLevel.Fatal, ); @@ -352,7 +352,7 @@ abstract class Frost { machinePtr: attemptSignRes.ref.machine, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "attemptSignConfig failed: $e\n$s", level: LogLevel.Fatal, ); @@ -378,7 +378,7 @@ abstract class Frost { machinePtr: continueSignRes.ref.machine, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "continueSigning failed: $e\n$s", level: LogLevel.Fatal, ); @@ -398,7 +398,7 @@ abstract class Frost { return rawTransaction; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "completeSigning failed: $e\n$s", level: LogLevel.Fatal, ); @@ -419,7 +419,7 @@ abstract class Frost { ); return configPtr; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "decodedSignConfig failed: $e\n$s", level: LogLevel.Fatal, ); @@ -443,7 +443,7 @@ abstract class Frost { return config; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "createResharerConfig failed: $e\n$s", level: LogLevel.Fatal, ); @@ -469,7 +469,7 @@ abstract class Frost { machine: result.machine, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "beginResharer failed: $e\n$s", level: LogLevel.Fatal, ); @@ -498,7 +498,7 @@ abstract class Frost { prior: result.machine, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "beginReshared failed: $e\n$s", level: LogLevel.Fatal, ); @@ -518,7 +518,7 @@ abstract class Frost { ); return result; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "finishResharer failed: $e\n$s", level: LogLevel.Fatal, ); @@ -542,7 +542,7 @@ abstract class Frost { ); return result; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "finishReshared failed: $e\n$s", level: LogLevel.Fatal, ); @@ -558,7 +558,7 @@ abstract class Frost { return config; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "decodedResharerConfig failed: $e\n$s", level: LogLevel.Fatal, ); @@ -631,7 +631,7 @@ abstract class Frost { newParticipants: newParticipants, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "extractResharerConfigData failed: $e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/services/fusion_tor_service.dart b/lib/services/fusion_tor_service.dart index 0d5b29f59..d7bf5181b 100644 --- a/lib/services/fusion_tor_service.dart +++ b/lib/services/fusion_tor_service.dart @@ -1,8 +1,9 @@ import 'dart:io'; -import '../utilities/logger.dart'; import 'package:tor_ffi_plugin/tor_ffi_plugin.dart'; +import '../utilities/logger.dart'; + class FusionTorService { Tor? _tor; String? _torDataDirPath; @@ -61,7 +62,7 @@ class FusionTorService { try { await _tor!.start(torDataDirPath: _torDataDirPath!); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "FusionTorService.start failed: $e\n$s", level: LogLevel.Warning, ); diff --git a/lib/services/monkey_service.dart b/lib/services/monkey_service.dart index f921135c1..1f326cf5a 100644 --- a/lib/services/monkey_service.dart +++ b/lib/services/monkey_service.dart @@ -1,10 +1,11 @@ import 'dart:typed_data'; import 'package:flutter_riverpod/flutter_riverpod.dart'; + import '../networking/http.dart'; -import 'tor_service.dart'; import '../utilities/logger.dart'; import '../utilities/prefs.dart'; +import 'tor_service.dart'; final pMonKeyService = Provider((ref) => MonKeyService()); @@ -38,7 +39,7 @@ class MonKeyService { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed fetchMonKey($address): $e\n$s", level: LogLevel.Error, ); diff --git a/lib/services/node_service.dart b/lib/services/node_service.dart index 847602249..c32664839 100644 --- a/lib/services/node_service.dart +++ b/lib/services/node_service.dart @@ -293,7 +293,7 @@ class NodeService extends ChangeNotifier { final json = jsonDecode(response.body) as Map; final result = jsonDecode(json['result'] as String); final map = jsonDecode(result as String); - Logging.instance.log(map, level: LogLevel.Info); + Logging.instance.logd(map, level: LogLevel.Info); for (final coin in AppConfig.coins) { final nodeList = List>.from( @@ -331,7 +331,7 @@ class NodeService extends ChangeNotifier { } } catch (e, s) { Logging.instance - .log("updateCommunityNodes() failed: $e\n$s", level: LogLevel.Error); + .logd("updateCommunityNodes() failed: $e\n$s", level: LogLevel.Error); } } } diff --git a/lib/services/notifications_service.dart b/lib/services/notifications_service.dart index 065285257..181678f9e 100644 --- a/lib/services/notifications_service.dart +++ b/lib/services/notifications_service.dart @@ -106,7 +106,7 @@ class NotificationsService extends ChangeNotifier { _timer = Timer.periodic(notificationRefreshInterval, (_) { Logging.instance - .log("Periodic notifications update check", level: LogLevel.Info); + .logd("Periodic notifications update check", level: LogLevel.Info); if (prefs.externalCalls) { _checkTrades(); } @@ -222,7 +222,7 @@ class NotificationsService extends ChangeNotifier { } on NoSuchTransactionException catch (e, s) { await _deleteWatchedTxNotification(notification); } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Error); + Logging.instance.logd("$e $s", level: LogLevel.Error); } } } diff --git a/lib/services/price.dart b/lib/services/price.dart index 5a97e43cb..f8a5139f5 100644 --- a/lib/services/price.dart +++ b/lib/services/price.dart @@ -20,6 +20,7 @@ import '../db/hive/db.dart'; import '../networking/http.dart'; import '../utilities/logger.dart'; import '../utilities/prefs.dart'; +import '../utilities/util.dart'; import '../wallets/crypto_currency/crypto_currency.dart'; import 'tor_service.dart'; @@ -128,9 +129,9 @@ class PriceAPI { } final externalCalls = Prefs.instance.externalCalls; - if ((!Logger.isTestEnv && !externalCalls) || + if ((!Util.isTestEnv && !externalCalls) || !(await Prefs.instance.isExternalCallsSet())) { - Logging.instance.log( + Logging.instance.logd( "User does not want to use external calls", level: LogLevel.Info, ); @@ -171,7 +172,7 @@ class PriceAPI { return _cachedPrices; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getPricesAnd24hChange($baseCurrency): $e\n$s", level: LogLevel.Error, ); @@ -184,9 +185,9 @@ class PriceAPI { final externalCalls = Prefs.instance.externalCalls; final HTTP client = HTTP(); - if ((!Logger.isTestEnv && !externalCalls) || + if ((!Util.isTestEnv && !externalCalls) || !(await Prefs.instance.isExternalCallsSet())) { - Logging.instance.log( + Logging.instance.logd( "User does not want to use external calls", level: LogLevel.Info, ); @@ -207,7 +208,7 @@ class PriceAPI { final json = jsonDecode(response.body) as List; return List.from(json); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "availableBaseCurrencies() using $uriString: $e\n$s", level: LogLevel.Error, ); @@ -226,9 +227,9 @@ class PriceAPI { contractAddresses.isEmpty) return tokenPrices; final externalCalls = Prefs.instance.externalCalls; - if ((!Logger.isTestEnv && !externalCalls) || + if ((!Util.isTestEnv && !externalCalls) || !(await Prefs.instance.isExternalCallsSet())) { - Logging.instance.log( + Logging.instance.logd( "User does not want to use external calls", level: LogLevel.Info, ); @@ -272,7 +273,7 @@ class PriceAPI { return tokenPrices; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "getPricesAnd24hChangeForEthTokens($baseCurrency,$contractAddresses): $e\n$s", level: LogLevel.Error, ); diff --git a/lib/services/tor_service.dart b/lib/services/tor_service.dart index 6904f8789..49ab83a0b 100644 --- a/lib/services/tor_service.dart +++ b/lib/services/tor_service.dart @@ -85,7 +85,7 @@ class TorService { // Complete the future. return; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "TorService.start failed: $e\n$s", level: LogLevel.Warning, ); diff --git a/lib/services/wallets.dart b/lib/services/wallets.dart index 6defcf012..701f77d9b 100644 --- a/lib/services/wallets.dart +++ b/lib/services/wallets.dart @@ -72,7 +72,7 @@ class Wallets { SecureStorageInterface secureStorage, ) async { final walletId = info.walletId; - Logging.instance.log( + Logging.instance.logd( "deleteWallet called with walletId=$walletId", level: LogLevel.Warning, ); @@ -97,7 +97,7 @@ class Wallets { appRoot: await StackFileSystem.applicationRootDirectory(), ); Logging.instance - .log("monero wallet: $walletId deleted", level: LogLevel.Info); + .logd("monero wallet: $walletId deleted", level: LogLevel.Info); } else if (info.coin is Monero) { await lib_monero_compat.deleteWalletFiles( name: walletId, @@ -105,13 +105,13 @@ class Wallets { appRoot: await StackFileSystem.applicationRootDirectory(), ); Logging.instance - .log("monero wallet: $walletId deleted", level: LogLevel.Info); + .logd("monero wallet: $walletId deleted", level: LogLevel.Info); } else if (info.coin is Epiccash) { final deleteResult = await deleteEpicWallet( walletId: walletId, secureStore: secureStorage, ); - Logging.instance.log( + Logging.instance.logd( "epic wallet: $walletId deleted with result: $deleteResult", level: LogLevel.Info, ); @@ -210,7 +210,7 @@ class Wallets { for (final walletInfo in walletInfoList) { try { final isVerified = await walletInfo.isMnemonicVerified(mainDB.isar); - Logging.instance.log( + Logging.instance.logd( "LOADING WALLET: ${walletInfo.name}:${walletInfo.walletId} " "IS VERIFIED: $isVerified", level: LogLevel.Info, @@ -252,7 +252,7 @@ class Wallets { // await walletsService.deleteWallet(walletInfo.name, false); } } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Fatal); + Logging.instance.logd("$e $s", level: LogLevel.Fatal); continue; } } @@ -317,7 +317,7 @@ class Wallets { for (final walletInfo in walletInfoList) { try { final isVerified = await walletInfo.isMnemonicVerified(mainDB.isar); - Logging.instance.log( + Logging.instance.logd( "LOADING WALLET: ${walletInfo.name}:${walletInfo.walletId} " "IS VERIFIED: $isVerified", level: LogLevel.Info, @@ -355,7 +355,7 @@ class Wallets { deleteFutures.add(_deleteWallet(walletInfo.walletId)); } } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Fatal); + Logging.instance.logd("$e $s", level: LogLevel.Fatal); continue; } } @@ -447,7 +447,7 @@ class Wallets { for (final walletInfo in walletInfoList) { try { final isVerified = await walletInfo.isMnemonicVerified(mainDB.isar); - Logging.instance.log( + Logging.instance.logd( "LOADING WALLET: ${walletInfo.name}:${walletInfo.walletId} " "IS VERIFIED: $isVerified", level: LogLevel.Info, @@ -485,7 +485,7 @@ class Wallets { deleteFutures.add(_deleteWallet(walletInfo.walletId)); } } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Fatal); + Logging.instance.logd("$e $s", level: LogLevel.Fatal); continue; } } @@ -509,7 +509,7 @@ class Wallets { Future _refreshFutures(List idsToRefresh) async { final start = DateTime.now(); - Logging.instance.log( + Logging.instance.logd( "Initial refresh start: ${start.toUtc()}", level: LogLevel.Warning, ); @@ -526,7 +526,7 @@ class Wallets { } await Future.wait(futures); } - Logging.instance.log( + Logging.instance.logd( "Initial refresh duration: ${DateTime.now().difference(start)}", level: LogLevel.Warning, ); @@ -580,7 +580,7 @@ class Wallets { for (final wallet in wallets) { final isVerified = await wallet.info.isMnemonicVerified(mainDB.isar); - Logging.instance.log( + Logging.instance.logd( "LOADING WALLET: ${wallet.info.name}:${wallet.walletId} IS VERIFIED: $isVerified", level: LogLevel.Info, ); diff --git a/lib/services/wallets_service.dart b/lib/services/wallets_service.dart index 744b327d1..7d0e90c33 100644 --- a/lib/services/wallets_service.dart +++ b/lib/services/wallets_service.dart @@ -11,6 +11,7 @@ import 'dart:convert'; import 'package:flutter/material.dart'; + import '../app_config.dart'; import '../db/hive/db.dart'; import '../utilities/logger.dart'; @@ -74,7 +75,7 @@ class WalletsService extends ChangeNotifier { final names = DB.instance .get(boxName: DB.boxNameAllWalletsData, key: 'names') as Map?; if (names == null) { - Logging.instance.log( + Logging.instance.logd( "Fetched wallet 'names' returned null. Setting initializing 'names'", level: LogLevel.Info, ); @@ -85,7 +86,7 @@ class WalletsService extends ChangeNotifier { ); return {}; } - Logging.instance.log("Fetched wallet names: $names", level: LogLevel.Info); + Logging.instance.logd("Fetched wallet names: $names", level: LogLevel.Info); final mapped = Map.from(names); mapped.removeWhere((name, dyn) { final jsonObject = Map.from(dyn as Map); @@ -93,7 +94,7 @@ class WalletsService extends ChangeNotifier { AppConfig.getCryptoCurrencyFor(jsonObject["coin"] as String); return false; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error, ${jsonObject["coin"]} does not exist", level: LogLevel.Error, ); diff --git a/lib/themes/theme_service.dart b/lib/themes/theme_service.dart index 19050029c..930280535 100644 --- a/lib/themes/theme_service.dart +++ b/lib/themes/theme_service.dart @@ -77,7 +77,7 @@ class ThemeService { if (file.isFile) { // TODO more sanitation? if (file.name.contains("..")) { - Logging.instance.log( + Logging.instance.logd( "Bad theme asset file path: ${file.name}", level: LogLevel.Error, ); @@ -110,7 +110,7 @@ class ThemeService { await dir.delete(recursive: true); } } else { - Logging.instance.log( + Logging.instance.logd( "Failed to delete theme $themeId", level: LogLevel.Warning, ); @@ -142,7 +142,7 @@ class ThemeService { } Future _updateDefaultTheme(String name) async { - Logging.instance.log( + Logging.instance.logd( "Updating default $name theme...", level: LogLevel.Info, ); @@ -150,7 +150,7 @@ class ThemeService { await ThemeService.instance.install( themeArchiveData: zip.buffer.asUint8List(), ); - Logging.instance.log( + Logging.instance.logd( "Updating default $name theme... finished", level: LogLevel.Info, ); @@ -174,7 +174,7 @@ class ThemeService { await Directory("${themesDir.path}/$themeId/assets").exists(); if (!jsonFileExists || !assetsDirExists) { - Logging.instance.log( + Logging.instance.logd( "Theme $themeId found in DB but is missing files", level: LogLevel.Warning, ); @@ -204,7 +204,7 @@ class ThemeService { return result; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to fetch themes list: $e\n$s", level: LogLevel.Warning, ); @@ -236,7 +236,7 @@ class ThemeService { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to fetch themes list: $e\n$s", level: LogLevel.Warning, ); @@ -279,7 +279,7 @@ class StackThemeMetaData { previewImageUrl: map["previewImageUrl"] as String, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to create instance of StackThemeMetaData using $map: \n$e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/utilities/address_utils.dart b/lib/utilities/address_utils.dart index efac56d64..d63dca66f 100644 --- a/lib/utilities/address_utils.dart +++ b/lib/utilities/address_utils.dart @@ -72,8 +72,12 @@ class AddressUtils { result["tx_description"] = Uri.decodeComponent(u.fragment); } } - } catch (e) { - print("Exception caught in parseUri($uri): $e"); + } catch (e, s) { + Logging.instance.d( + "Exception caught in parseUri($uri): $e", + error: e, + stackTrace: s, + ); } return result; } @@ -151,7 +155,7 @@ class AddressUtils { additionalParams: filteredParams, ); } catch (e, s) { - logging?.log("$e\n$s", level: LogLevel.Error); + logging?.logd("$e\n$s", level: LogLevel.Error); return null; } } @@ -199,8 +203,12 @@ class AddressUtils { Map result = {}; try { result = Map.from(jsonDecode(data) as Map); - } catch (e) { - print("Exception caught in parseQRSeedData($data): $e"); + } catch (e, s) { + Logging.instance.d( + "Exception caught in parseQRSeedData($data)", + error: e, + stackTrace: s, + ); } return result; } diff --git a/lib/utilities/biometrics.dart b/lib/utilities/biometrics.dart index cf9d8c27d..6dbb05982 100644 --- a/lib/utilities/biometrics.dart +++ b/lib/utilities/biometrics.dart @@ -27,14 +27,14 @@ class Biometrics { required String title, }) async { if (!(Platform.isIOS || Platform.isAndroid)) { - Logging.instance.log( + Logging.instance.logd( "Tried to use Biometrics.authenticate() on a platform that is not Android or iOS! ...returning false.", level: LogLevel.Error, ); return false; } if (integrationTestFlag) { - Logging.instance.log( + Logging.instance.logd( "Tried to use Biometrics.authenticate() during integration testing. Returning false.", level: LogLevel.Warning, ); @@ -53,7 +53,7 @@ class Biometrics { List availableSystems = await localAuth.getAvailableBiometrics(); - Logging.instance.log( + Logging.instance.logd( "Bio availableSystems: $availableSystems", level: LogLevel.Info, ); @@ -79,7 +79,7 @@ class Biometrics { return true; } } catch (e) { - Logging.instance.log( + Logging.instance.logd( "local_auth exception caught in Biometrics.authenticate(), e: $e", level: LogLevel.Error, ); diff --git a/lib/utilities/connection_check/electrum_connection_check.dart b/lib/utilities/connection_check/electrum_connection_check.dart index ae8ba3f94..e90d7896c 100644 --- a/lib/utilities/connection_check/electrum_connection_check.dart +++ b/lib/utilities/connection_check/electrum_connection_check.dart @@ -27,7 +27,7 @@ Future checkElectrumServer({ // And the killswitch isn't set... if (!_prefs.torKillSwitch) { // Then we'll just proceed and connect to ElectrumX through clearnet at the bottom of this function. - Logging.instance.log( + Logging.instance.logd( "Tor preference set but Tor is not enabled, killswitch not set, connecting to Electrum adapter through clearnet", level: LogLevel.Warning, ); @@ -62,7 +62,7 @@ Future checkElectrumServer({ return true; } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Debug); + Logging.instance.logd("$e\n$s", level: LogLevel.Debug); return false; } } diff --git a/lib/utilities/constants.dart b/lib/utilities/constants.dart index 163b7d04e..1c3b908a1 100644 --- a/lib/utilities/constants.dart +++ b/lib/utilities/constants.dart @@ -40,7 +40,7 @@ abstract class Constants { // Enable Logger.print statements static const bool disableLogger = false; - static const int currentDataVersion = 13; + static const int currentDataVersion = 14; static const int rescanV1 = 1; diff --git a/lib/utilities/desktop_password_service.dart b/lib/utilities/desktop_password_service.dart index 3852a8695..7197cced8 100644 --- a/lib/utilities/desktop_password_service.dart +++ b/lib/utilities/desktop_password_service.dart @@ -68,7 +68,7 @@ class DPS { await _put(key: _kKeyBlobKey, value: await _handler!.getKeyBlob()); await _updateStoredKeyBlobVersion(kLatestBlobVersion); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "${_getMessageFromException(e)}\n$s", level: LogLevel.Error, ); @@ -104,7 +104,7 @@ class DPS { await _updateStoredKeyBlobVersion(kLatestBlobVersion); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "${_getMessageFromException(e)}\n$s", level: LogLevel.Error, ); @@ -125,7 +125,7 @@ class DPS { // existing passphrase matches key blob return true; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "${_getMessageFromException(e)}\n$s", level: LogLevel.Warning, ); @@ -161,7 +161,7 @@ class DPS { // successfully updated passphrase return true; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "${_getMessageFromException(e)}\n$s", level: LogLevel.Warning, ); @@ -189,7 +189,7 @@ class DPS { box = await DB.instance.hive.openBox(kBoxNameDesktopData); await box.put(key, value); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "DPS failed put($key): $e\n$s", level: LogLevel.Fatal, ); @@ -205,7 +205,7 @@ class DPS { box = await DB.instance.hive.openBox(kBoxNameDesktopData); value = box.get(key); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "DPS failed get($key): $e\n$s", level: LogLevel.Fatal, ); diff --git a/lib/utilities/enums/log_level_enum.dart b/lib/utilities/enums/log_level_enum.dart index 5fb7f9e52..c2c1de557 100644 --- a/lib/utilities/enums/log_level_enum.dart +++ b/lib/utilities/enums/log_level_enum.dart @@ -10,10 +10,28 @@ // Used in Isar db and stored there as int indexes so adding/removing values // in this definition should be done extremely carefully in production +import 'package:logger/logger.dart'; + +@Deprecated("Use Level instead, combined with the new logging features") enum LogLevel { Info, Warning, Error, Fatal, Debug; + + Level getLoggerLevel() { + switch (this) { + case LogLevel.Info: + return Level.info; + case LogLevel.Warning: + return Level.warning; + case LogLevel.Error: + return Level.error; + case LogLevel.Fatal: + return Level.fatal; + case LogLevel.Debug: + return Level.debug; + } + } } diff --git a/lib/utilities/extensions/impl/contract_abi.dart b/lib/utilities/extensions/impl/contract_abi.dart index b067c552e..401e8af04 100644 --- a/lib/utilities/extensions/impl/contract_abi.dart +++ b/lib/utilities/extensions/impl/contract_abi.dart @@ -68,7 +68,7 @@ extension ContractAbiExtensions on ContractAbi { return ContractAbi(name, functions, events); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to parse ABI for $name: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/utilities/git_status.dart b/lib/utilities/git_status.dart index 093bc39af..0f873df3f 100644 --- a/lib/utilities/git_status.dart +++ b/lib/utilities/git_status.dart @@ -138,7 +138,7 @@ abstract class GitStatus { String project, String commit, ) async { - Logging.instance.log("doesCommitExist", level: LogLevel.Info); + Logging.instance.logd("doesCommitExist", level: LogLevel.Info); final Client client = Client(); try { final uri = Uri.parse( @@ -151,7 +151,7 @@ abstract class GitStatus { ); final response = jsonDecode(commitQuery.body.toString()); - Logging.instance.log( + Logging.instance.logd( "doesCommitExist $project $commit $response", level: LogLevel.Info, ); @@ -159,13 +159,13 @@ abstract class GitStatus { try { isThereCommit = response['sha'] == commit; Logging.instance - .log("isThereCommit $isThereCommit", level: LogLevel.Info); + .logd("isThereCommit $isThereCommit", level: LogLevel.Info); return isThereCommit; } catch (e, s) { return false; } } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Error); + Logging.instance.logd("$e $s", level: LogLevel.Error); return false; } } @@ -176,7 +176,7 @@ abstract class GitStatus { String branch, String commit, ) async { - Logging.instance.log("doesCommitExist", level: LogLevel.Info); + Logging.instance.logd("doesCommitExist", level: LogLevel.Info); final Client client = Client(); try { final uri = Uri.parse( @@ -189,20 +189,20 @@ abstract class GitStatus { ); final response = jsonDecode(commitQuery.body.toString()); - Logging.instance.log( + Logging.instance.logd( "isHeadCommit $project $commit $branch $response", level: LogLevel.Info, ); bool isHead; try { isHead = response['sha'] == commit; - Logging.instance.log("isHead $isHead", level: LogLevel.Info); + Logging.instance.logd("isHead $isHead", level: LogLevel.Info); return isHead; } catch (e, s) { return false; } } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Error); + Logging.instance.logd("$e $s", level: LogLevel.Error); return false; } } diff --git a/lib/utilities/logger.dart b/lib/utilities/logger.dart index 83949ec5b..7243de77a 100644 --- a/lib/utilities/logger.dart +++ b/lib/utilities/logger.dart @@ -8,161 +8,264 @@ * */ +import 'dart:convert'; import 'dart:core' as core; import 'dart:core'; -import 'dart:io'; +import 'dart:isolate'; +import 'dart:ui'; -import 'package:flutter/foundation.dart'; -import 'package:isar/isar.dart'; +import 'package:flutter_libsparkmobile/flutter_libsparkmobile.dart' as spark; +import 'package:logger/logger.dart'; -import '../models/isar/models/log.dart'; -import 'constants.dart'; import 'enums/log_level_enum.dart'; +import 'util.dart'; export 'enums/log_level_enum.dart'; +const _kLoggerPortName = "logger_port"; + +// convenience conversion for spark +extension LoggingLevelExt on spark.LoggingLevel { + Level getLoggerLevel() { + switch (this) { + case spark.LoggingLevel.info: + return Level.info; + case spark.LoggingLevel.warning: + return Level.warning; + case spark.LoggingLevel.error: + return Level.error; + case spark.LoggingLevel.fatal: + return Level.fatal; + case spark.LoggingLevel.debug: + return Level.debug; + case spark.LoggingLevel.trace: + return Level.trace; + } + } +} + class Logging { - static const isArmLinux = bool.fromEnvironment("IS_ARM"); - static final isTestEnv = Platform.environment["FLUTTER_TEST"] == "true"; Logging._(); static final Logging _instance = Logging._(); static Logging get instance => _instance; - static const core.int defaultPrintLength = 1020; + late final String logsDirPath; - late final Isar? isar; - late final _AsyncLogWriterQueue _queue; + SendPort get _sendPort { + final port = IsolateNameServer.lookupPortByName(_kLoggerPortName); + if (port == null) { + throw Exception( + "Did you forget to call Logging.initialize()?", + ); + } + return port; + } - Future init(Isar isar) async { - _queue = _AsyncLogWriterQueue(); - this.isar = isar; + Future initialize(String logsPath, {required Level level}) async { + if (Isolate.current.debugName != "main") { + throw Exception( + "Logging.initialize() must be called on the main isolate.", + ); + } + if (IsolateNameServer.lookupPortByName(_kLoggerPortName) != null) { + throw Exception( + "Logging was already initialized", + ); + } + + logsDirPath = logsPath; + + final receivePort = ReceivePort(); + await Isolate.spawn( + (sendPort) { + final ReceivePort receivePort = ReceivePort(); + sendPort.send(receivePort.sendPort); + + PrettyPrinter prettyPrinter(bool toFile) => PrettyPrinter( + printEmojis: false, + methodCount: 0, + dateTimeFormat: + toFile ? DateTimeFormat.none : DateTimeFormat.dateAndTime, + colors: !toFile, + noBoxingByDefault: toFile, + ); + + final consoleLogger = Logger( + printer: PrefixPrinter(prettyPrinter(false)), + filter: ProductionFilter(), + level: level, + ); + + final fileLogger = Logger( + printer: PrefixPrinter(prettyPrinter(true)), + filter: ProductionFilter(), + level: level, + output: AdvancedFileOutput( + path: logsDirPath, + overrideExisting: false, + latestFileName: "latest.txt", + writeImmediately: [ + Level.error, + Level.fatal, + Level.warning, + Level.trace, // mainly for spark debugging. TODO: Remove later + ], + ), + ); + + receivePort.listen((message) { + final event = (message as (LogEvent, bool)).$1; + consoleLogger.log( + event.level, + event.message, + stackTrace: event.stackTrace, + error: event.error, + time: event.time.toUtc(), + ); + if (message.$2) { + fileLogger.log( + event.level, + "${event.time.toUtc().toIso8601String()} ${event.message}", + stackTrace: event.stackTrace, + error: event.error, + time: event.time, + ); + } + }); + }, + receivePort.sendPort, + ); + final loggerPort = await receivePort.first as SendPort; + IsolateNameServer.registerPortWithName(loggerPort, _kLoggerPortName); } - void log( + String _stringifyMessage(dynamic message) => + !(message is Map || message is Iterable) + ? message.toString() + : JsonEncoder.withIndent(' ', (o) => o.toString()).convert(message); + + @core.Deprecated("Use Logging.instance.log instead") + void logd( core.Object? object, { required LogLevel level, core.bool printToConsole = true, core.bool printFullLength = false, + }) => + log( + level.getLoggerLevel(), + object, + ); + + void log( + Level level, + dynamic message, { + DateTime? time, + Object? error, + StackTrace? stackTrace, + bool toFile = true, // false will print to console only }) { + if (Util.isTestEnv || Util.isArmLinux) { + toFile = false; + } try { - if (isTestEnv || isArmLinux) { - Logger.print(object, normalLength: !printFullLength); - return; - } - String message = object.toString(); - - // random value to check max size of message before storing in db - if (message.length > 20000) { - message = "${message.substring(0, 20000)}..."; - } - - final now = core.DateTime.now().toUtc(); - final log = Log() - ..message = message - ..logLevel = level - ..timestampInMillisUTC = now.millisecondsSinceEpoch; - if (level == LogLevel.Error || level == LogLevel.Fatal) { - printFullLength = true; - } - - _queue.add( - () async => isar!.writeTxn( - () async => await isar!.logs.put(log), + _sendPort.send( + ( + LogEvent( + level, + _stringifyMessage(message), + time: time, + error: error, + stackTrace: stackTrace, + ), + toFile ), ); - - if (printToConsole) { - final core.String logStr = "Log: ${log.toString()}"; - final core.int logLength = logStr.length; - - if (!printFullLength || logLength <= defaultPrintLength) { - debugPrint(logStr); - } else { - core.int start = 0; - core.int endIndex = defaultPrintLength; - core.int tmpLogLength = logLength; - while (endIndex < logLength) { - debugPrint(logStr.substring(start, endIndex)); - endIndex += defaultPrintLength; - start += defaultPrintLength; - tmpLogLength -= defaultPrintLength; - } - if (tmpLogLength > 0) { - debugPrint(logStr.substring(start, logLength)); - } - } - } } catch (e, s) { - print("problem trying to log"); - print("$e $s"); - Logger.print(object); + t("Isolates suck", error: e, stackTrace: s); } } -} -abstract class Logger { - static final isTestEnv = Platform.environment["FLUTTER_TEST"] == "true"; + void t( + dynamic message, { + DateTime? time, + Object? error, + StackTrace? stackTrace, + }) => + log( + Level.trace, + message, + time: time, + error: error, + stackTrace: stackTrace, + ); - static void print( - core.Object? object, { - core.bool withTimeStamp = true, - core.bool normalLength = true, - }) async { - if (Constants.disableLogger && !isTestEnv) { - return; - } - final utcTime = withTimeStamp ? "${core.DateTime.now().toUtc()}: " : ""; - final core.int defaultPrintLength = 1020 - utcTime.length; - if (normalLength) { - debugPrint("$utcTime$object"); - } else if (object == null || - object.toString().length <= defaultPrintLength) { - debugPrint("$utcTime$object"); - } else { - final core.String log = object.toString(); - core.int start = 0; - core.int endIndex = defaultPrintLength; - final core.int logLength = log.length; - core.int tmpLogLength = log.length; - while (endIndex < logLength) { - debugPrint(utcTime + log.substring(start, endIndex)); - endIndex += defaultPrintLength; - start += defaultPrintLength; - tmpLogLength -= defaultPrintLength; - } - if (tmpLogLength > 0) { - debugPrint(utcTime + log.substring(start, logLength)); - } - } - } -} + void d( + dynamic message, { + DateTime? time, + Object? error, + StackTrace? stackTrace, + }) => + log( + Level.debug, + message, + time: time, + error: error, + stackTrace: stackTrace, + ); -/// basic async queue for writing logs in the [Logging] to isar -class _AsyncLogWriterQueue { - final List Function()> _queue = []; - bool _runningLock = false; + void i( + dynamic message, { + DateTime? time, + Object? error, + StackTrace? stackTrace, + }) => + log( + Level.info, + message, + time: time, + error: error, + stackTrace: stackTrace, + ); - void add(Future Function() futureFunction) { - _queue.add(futureFunction); - _run(); - } + void w( + dynamic message, { + DateTime? time, + Object? error, + StackTrace? stackTrace, + }) => + log( + Level.warning, + message, + time: time, + error: error, + stackTrace: stackTrace, + ); - void _run() async { - if (_runningLock) { - return; - } - _runningLock = true; - try { - while (_queue.isNotEmpty) { - final futureFunction = _queue.removeAt(0); - try { - await futureFunction.call(); - } catch (e, s) { - debugPrint("$e\n$s"); - } - } - } finally { - _runningLock = false; - } - } + void e( + dynamic message, { + DateTime? time, + Object? error, + StackTrace? stackTrace, + }) => + log( + Level.error, + message, + time: time, + error: error, + stackTrace: stackTrace, + ); + + void f( + dynamic message, { + DateTime? time, + Object? error, + StackTrace? stackTrace, + }) => + log( + Level.fatal, + message, + time: time, + error: error, + stackTrace: stackTrace, + ); } diff --git a/lib/utilities/prefs.dart b/lib/utilities/prefs.dart index 0bc2dcc43..395e5ecd6 100644 --- a/lib/utilities/prefs.dart +++ b/lib/utilities/prefs.dart @@ -11,6 +11,7 @@ import 'dart:async'; import 'package:flutter/cupertino.dart'; +import 'package:logger/logger.dart'; import 'package:uuid/uuid.dart'; import '../app_config.dart'; @@ -73,6 +74,8 @@ class Prefs extends ChangeNotifier { _autoPin = await _getAutoPin(); _enableExchange = await _getEnableExchange(); _advancedFiroFeatures = await _getAdvancedFiroFeatures(); + _logsPath = await _getLogsPath(); + _logLevel = await _getLogLevel(); _initialized = true; } @@ -1182,4 +1185,55 @@ class Prefs extends ChangeNotifier { ) as bool? ?? false; } + + // Logs path. Null defaults to default as defined in stack_file_system.dart + String? _logsPath; + String? get logsPath => _logsPath; + set logsPath(String? logsPath) { + if (_logsPath != logsPath) { + DB.instance.put( + boxName: DB.boxNamePrefs, + key: "logsPath", + value: logsPath, + ); + _logsPath = logsPath; + notifyListeners(); + } + } + + Future _getLogsPath() async { + return await DB.instance.get( + boxName: DB.boxNamePrefs, + key: "logsPath", + ) as String?; + } + + // log level pref + Level _logLevel = Level.warning; + Level get logLevel => _logLevel; + set logLevel(Level logLevel) { + if (_logLevel != logLevel) { + DB.instance.put( + boxName: DB.boxNamePrefs, + key: "logLevel", + value: logLevel.value, + ); + _logLevel = logLevel; + notifyListeners(); + } + } + + Future _getLogLevel() async { + final value = await DB.instance.get( + boxName: DB.boxNamePrefs, + key: "logLevel", + ) as int?; + + try { + return Level.values.firstWhere((e) => e.value == value); + } catch (_) { + // default to warning + return Level.warning; + } + } } diff --git a/lib/utilities/show_loading.dart b/lib/utilities/show_loading.dart index 371d67d1d..7f97ca851 100644 --- a/lib/utilities/show_loading.dart +++ b/lib/utilities/show_loading.dart @@ -71,7 +71,7 @@ Future showLoading({ result = await whileFuture; } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "showLoading caught: $e\n$s", level: LogLevel.Warning, ); diff --git a/lib/utilities/stack_file_system.dart b/lib/utilities/stack_file_system.dart index 53e382ff0..67b992bbc 100644 --- a/lib/utilities/stack_file_system.dart +++ b/lib/utilities/stack_file_system.dart @@ -11,9 +11,10 @@ import 'dart:io'; import 'package:path_provider/path_provider.dart'; +import 'package:permission_handler/permission_handler.dart'; import '../app_config.dart'; -import 'logger.dart'; +import 'prefs.dart'; import 'util.dart'; abstract class StackFileSystem { @@ -36,7 +37,7 @@ abstract class StackFileSystem { Directory appDirectory; // todo: can merge and do same as regular linux home dir? - if (Logging.isArmLinux) { + if (Util.isArmLinux) { appDirectory = await getApplicationDocumentsDirectory(); appDirectory = Directory("${appDirectory.path}/.${AppConfig.appDefaultDataDirName}"); @@ -158,4 +159,36 @@ abstract class StackFileSystem { } static Directory? themesDir; + + static Future applicationLogsDirectory(Prefs prefs) async { + // if prefs logs path is set, use that + if (prefs.logsPath != null) { + final dir = Directory(prefs.logsPath!); + if (await dir.exists()) { + return dir; + } + } + + final appDocsDir = await getApplicationDocumentsDirectory(); + const logsDirName = "${AppConfig.prefix}_Logs"; + final Directory logsDir; + + if (Platform.isIOS) { + logsDir = Directory("${appDocsDir.path}/logs"); + } else if (Platform.isMacOS || Platform.isLinux || Platform.isWindows) { + // TODO check this is correct for macos + logsDir = Directory("${appDocsDir.path}/$logsDirName"); + } else if (Platform.isAndroid) { + await Permission.storage.request(); + logsDir = Directory("/storage/emulated/0/Documents/$logsDirName"); + } else { + throw Exception("Unsupported Platform"); + } + + if (!logsDir.existsSync()) { + await logsDir.create(recursive: true); + } + + return logsDir; + } } diff --git a/lib/utilities/test_epic_box_connection.dart b/lib/utilities/test_epic_box_connection.dart index 7fff18369..8e98e4ccf 100644 --- a/lib/utilities/test_epic_box_connection.dart +++ b/lib/utilities/test_epic_box_connection.dart @@ -41,7 +41,7 @@ Future _testEpicBoxNodeConnection(Uri uri) async { return false; } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Warning); + Logging.instance.logd("$e\n$s", level: LogLevel.Warning); return false; } } @@ -87,7 +87,7 @@ Future testEpicNodeConnection(NodeFormData data) async { return null; } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Warning); + Logging.instance.logd("$e\n$s", level: LogLevel.Warning); return null; } } diff --git a/lib/utilities/test_monero_node_connection.dart b/lib/utilities/test_monero_node_connection.dart index 8901d4d2e..0abfff5ae 100644 --- a/lib/utilities/test_monero_node_connection.dart +++ b/lib/utilities/test_monero_node_connection.dart @@ -11,10 +11,10 @@ import 'dart:convert'; import 'dart:io'; +import 'package:digest_auth/digest_auth.dart'; import 'package:flutter/material.dart'; import 'package:http/io_client.dart'; import 'package:monero_rpc/monero_rpc.dart'; -import 'package:digest_auth/digest_auth.dart'; import 'package:socks5_proxy/socks.dart'; import 'package:tor_ffi_plugin/socks_socket.dart'; @@ -103,7 +103,7 @@ Future testMoneroNodeConnection( return MoneroNodeConnectionResponse(null, null, null, success); } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Warning); + Logging.instance.logd("$e\n$s", level: LogLevel.Warning); return MoneroNodeConnectionResponse(null, null, null, false); } finally { await socket?.close(); @@ -150,7 +150,7 @@ Future testMoneroNodeConnection( if (badCertResponse != null) { return badCertResponse!; } else { - Logging.instance.log("$e\n$s", level: LogLevel.Warning); + Logging.instance.logd("$e\n$s", level: LogLevel.Warning); return MoneroNodeConnectionResponse(null, null, null, false); } } finally { diff --git a/lib/utilities/test_node_connection.dart b/lib/utilities/test_node_connection.dart index 9169cb636..f3e1a9618 100644 --- a/lib/utilities/test_node_connection.dart +++ b/lib/utilities/test_node_connection.dart @@ -100,7 +100,7 @@ Future testNodeConnection({ if (ref.read(prefsChangeNotifierProvider).useTor) { if (formData.netOption! == TorPlainNetworkOption.clear) { - Logging.instance.log( + Logging.instance.logd( "This node is configured for non-TOR only but TOR is enabled", level: LogLevel.Warning, ); @@ -108,7 +108,7 @@ Future testNodeConnection({ } } else { if (formData.netOption! == TorPlainNetworkOption.tor) { - Logging.instance.log( + Logging.instance.logd( "This node is configured for TOR only but TOR is disabled", level: LogLevel.Warning, ); @@ -128,7 +128,7 @@ Future testNodeConnection({ onSuccess?.call(data); } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Warning); + Logging.instance.logd("$e\n$s", level: LogLevel.Warning); } break; @@ -175,7 +175,7 @@ Future testNodeConnection({ } } } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Warning); + Logging.instance.logd("$e\n$s", level: LogLevel.Warning); } break; @@ -251,7 +251,7 @@ Future testNodeConnection({ ); final health = await rpcClient.getHealth(); - Logging.instance.log( + Logging.instance.logd( "Solana testNodeConnection \"health=$health\"", level: LogLevel.Info, ); @@ -283,7 +283,7 @@ Future testNodeConnection({ BlockfrostRequestBackendHealthStatus(), ); - Logging.instance.log( + Logging.instance.logd( "Cardano testNodeConnection \"health=$health\"", level: LogLevel.Info, ); diff --git a/lib/utilities/util.dart b/lib/utilities/util.dart index d573d9b90..5480e0804 100644 --- a/lib/utilities/util.dart +++ b/lib/utilities/util.dart @@ -18,6 +18,9 @@ import 'package:intl/number_symbols.dart'; import 'package:intl/number_symbols_data.dart'; abstract class Util { + static const isArmLinux = bool.fromEnvironment("IS_ARM"); + static final isTestEnv = Platform.environment["FLUTTER_TEST"] == "true"; + static Directory? libraryPath; static double? screenWidth; diff --git a/lib/utilities/wallet_tools.dart b/lib/utilities/wallet_tools.dart index cbc3c616c..8d869ea63 100644 --- a/lib/utilities/wallet_tools.dart +++ b/lib/utilities/wallet_tools.dart @@ -2,13 +2,17 @@ import 'package:isar/isar.dart'; import '../db/isar/main_db.dart'; import '../models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import '../models/isar/models/firo_specific/lelantus_coin.dart'; import '../wallets/crypto_currency/crypto_currency.dart'; +import '../wallets/isar/models/spark_coin.dart'; +import '../wallets/wallet/impl/firo_wallet.dart'; import 'amount/amount.dart'; import 'amount/amount_formatter.dart'; import 'amount/amount_unit.dart'; +import 'logger.dart'; abstract class WalletDevTools { - static String checkFiroTransactionTally(String walletId) { + static String checkFiroTransactionTally(FiroWallet wallet) { final amtFmt = AmountFormatter( unit: AmountUnit.normal, locale: "en_US", @@ -18,7 +22,7 @@ abstract class WalletDevTools { final all = MainDB.instance.isar.transactionV2s .where() - .walletIdEqualTo(walletId) + .walletIdEqualTo(wallet.walletId) .findAllSync(); final totalCount = all.length; @@ -43,12 +47,27 @@ abstract class WalletDevTools { fractionDigits: 8, ); - print("======== $walletId ============="); - print("totalTxCount: $totalCount"); - print( + final lelantusCoinsCount = MainDB.instance.isar.lelantusCoins + .where() + .walletIdEqualTo(wallet.walletId) + .countSync(); + final sparkCoinsCount = MainDB.instance.isar.sparkCoins + .where() + .walletIdEqualToAnyLTagHash(wallet.walletId) + .countSync(); + + final buffer = StringBuffer(); + buffer.writeln("============= ${wallet.info.name} ============="); + buffer.writeln("wallet id: ${wallet.walletId}"); + buffer.writeln("totalTxCount: $totalCount"); + buffer.writeln( "balanceAccordingToTxns: ${amtFmt.format(balanceAccordingToTxHistory)}", ); - print("=================================================="); + buffer.writeln("lelantusCoinsCount: $lelantusCoinsCount"); + buffer.writeln("sparkCoinsCount: $sparkCoinsCount"); + buffer.writeln("=================================================="); + + Logging.instance.d(buffer); return amtFmt.format(balanceAccordingToTxHistory); } diff --git a/lib/wallets/api/lelantus_ffi_wrapper.dart b/lib/wallets/api/lelantus_ffi_wrapper.dart index 44e446507..5bb9dab11 100644 --- a/lib/wallets/api/lelantus_ffi_wrapper.dart +++ b/lib/wallets/api/lelantus_ffi_wrapper.dart @@ -48,7 +48,7 @@ abstract final class LelantusFfiWrapper { try { return await compute(_restore, args); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from _restore(): $e\n$s", level: LogLevel.Info, ); diff --git a/lib/wallets/api/tezos/tezos_api.dart b/lib/wallets/api/tezos/tezos_api.dart index abe126ac3..8e81f6451 100644 --- a/lib/wallets/api/tezos/tezos_api.dart +++ b/lib/wallets/api/tezos/tezos_api.dart @@ -25,7 +25,7 @@ abstract final class TezosAPI { final result = jsonDecode(response.body); return result as int; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in TezosAPI while getting counter for $address: $e\n$s", level: LogLevel.Error, ); @@ -51,11 +51,9 @@ abstract final class TezosAPI { final account = TezosAccount.fromMap(Map.from(result)); - print("Get account =================== $account"); - return account; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in TezosAPI while getting account for $address: $e\n$s", level: LogLevel.Error, ); @@ -111,7 +109,7 @@ abstract final class TezosAPI { } return txs; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in TezosAPI while getting transactions for $address: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/wallets/api/tezos/tezos_rpc_api.dart b/lib/wallets/api/tezos/tezos_rpc_api.dart index 1497a46c0..a5da3b01e 100644 --- a/lib/wallets/api/tezos/tezos_rpc_api.dart +++ b/lib/wallets/api/tezos/tezos_rpc_api.dart @@ -28,7 +28,7 @@ abstract final class TezosRpcAPI { BigInt.parse(response.body.substring(1, response.body.length - 2)); return balance; } catch (e) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in tezos_rpc_api.dart while getting balance for $address: $e", level: LogLevel.Error, ); @@ -54,7 +54,7 @@ abstract final class TezosRpcAPI { final jsonParsedResponse = jsonDecode(response.body); return int.parse(jsonParsedResponse["level"].toString()); } catch (e) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in tezos_rpc_api.dart while getting chain height for tezos: $e", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/impl/bitcoin_frost_wallet.dart b/lib/wallets/wallet/impl/bitcoin_frost_wallet.dart index c1701d8b7..5400ba457 100644 --- a/lib/wallets/wallet/impl/bitcoin_frost_wallet.dart +++ b/lib/wallets/wallet/impl/bitcoin_frost_wallet.dart @@ -56,7 +56,7 @@ class BitcoinFrostWallet extends Wallet required List participants, required int threshold, }) async { - Logging.instance.log( + Logging.instance.logd( "Generating new FROST wallet.", level: LogLevel.Info, ); @@ -108,7 +108,7 @@ class BitcoinFrostWallet extends Wallet await mainDB.putAddresses([address]); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from initializeNewFrost(): $e\n$s", level: LogLevel.Fatal, ); @@ -626,7 +626,7 @@ class BitcoinFrostWallet extends Wallet // TODO: [prio=none] Check for special Bitcoin outputs like ordinals. } else { - Logging.instance.log( + Logging.instance.logd( "Unexpected tx found (ignoring it): $txData", level: LogLevel.Error, ); @@ -686,7 +686,7 @@ class BitcoinFrostWallet extends Wallet "index < kFrostSecureStartingIndex hit someSaneMaximum"); } } else { - Logging.instance.log( + Logging.instance.logd( "$runtimeType.checkSaveInitialReceivingAddress() failed due" " to missing serialized keys", level: LogLevel.Fatal, @@ -698,12 +698,13 @@ class BitcoinFrostWallet extends Wallet @override Future confirmSend({required TxData txData}) async { try { - Logging.instance.log("confirmSend txData: $txData", level: LogLevel.Info); + Logging.instance + .logd("confirmSend txData: $txData", level: LogLevel.Info); final hex = txData.raw!; final txHash = await electrumXClient.broadcastTransaction(rawTx: hex); - Logging.instance.log("Sent txHash: $txHash", level: LogLevel.Info); + Logging.instance.logd("Sent txHash: $txHash", level: LogLevel.Info); // mark utxos as used final usedUTXOs = txData.utxos!.map((e) => e.copyWith(used: true)); @@ -717,7 +718,7 @@ class BitcoinFrostWallet extends Wallet return txData; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from confirmSend(): $e\n$s", level: LogLevel.Error, ); @@ -803,11 +804,11 @@ class BitcoinFrostWallet extends Wallet ).raw.toInt(), ); - Logging.instance.log("fetched fees: $feeObject", level: LogLevel.Info); + Logging.instance.logd("fetched fees: $feeObject", level: LogLevel.Info); return feeObject; } catch (e) { - Logging.instance - .log("Exception rethrown from _getFees(): $e", level: LogLevel.Error); + Logging.instance.logd("Exception rethrown from _getFees(): $e", + level: LogLevel.Error); rethrow; } } @@ -830,7 +831,7 @@ class BitcoinFrostWallet extends Wallet } if (serializedKeys == null || multisigConfig == null) { final err = "${info.coinName} wallet ${info.walletId} had null keys/cfg"; - Logging.instance.log(err, level: LogLevel.Fatal); + Logging.instance.logd(err, level: LogLevel.Fatal); throw Exception(err); // TODO [prio=low]: handle null keys or config. This should not happen. } @@ -957,7 +958,7 @@ class BitcoinFrostWallet extends Wallet unawaited(refresh()); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "recoverFromSerializedKeys failed: $e\n$s", level: LogLevel.Fatal, ); @@ -1164,7 +1165,7 @@ class BitcoinFrostWallet extends Wallet return await mainDB.updateUTXOs(walletId, outputArray); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Output fetch unsuccessful: $e\n$s", level: LogLevel.Error, ); @@ -1381,7 +1382,7 @@ class BitcoinFrostWallet extends Wallet if (e.toString().contains("initialized")) { // Ignore. This should happen every first time the wallet is opened. } else { - Logging.instance.log( + Logging.instance.logd( "Error closing electrumXClient: $e", level: LogLevel.Error, ); @@ -1478,7 +1479,7 @@ class BitcoinFrostWallet extends Wallet await checkChangeAddressForTransactions(); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from _checkChangeAddressForTransactions" "($cryptoCurrency): $e\n$s", level: LogLevel.Error, @@ -1493,7 +1494,7 @@ class BitcoinFrostWallet extends Wallet try { throw Exception(); } catch (_, s) { - Logging.instance.log( + Logging.instance.logd( "checkReceivingAddressForTransactions called but reuse address flag set: $s", level: LogLevel.Error, ); @@ -1525,7 +1526,7 @@ class BitcoinFrostWallet extends Wallet } } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from _checkReceivingAddressForTransactions" "($cryptoCurrency): $e\n$s", level: LogLevel.Error, @@ -1748,7 +1749,7 @@ class BitcoinFrostWallet extends Wallet int gapCounter = 0; int index = secure ? kFrostSecureStartingIndex : 0; for (; gapCounter < 20; index++) { - Logging.instance.log( + Logging.instance.logd( "Frost index: $index, \t GapCounter chain=$chain: $gapCounter", level: LogLevel.Info, ); @@ -1843,7 +1844,7 @@ class BitcoinFrostWallet extends Wallet return allTxHashes; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType._fetchHistory: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/impl/bitcoincash_wallet.dart b/lib/wallets/wallet/impl/bitcoincash_wallet.dart index 3c8fb58bc..a8bcc599d 100644 --- a/lib/wallets/wallet/impl/bitcoincash_wallet.dart +++ b/lib/wallets/wallet/impl/bitcoincash_wallet.dart @@ -198,7 +198,7 @@ class BitcoincashWallet valueStringSats = prevOut.valueStringSats; addresses.addAll(prevOut.addresses); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error getting prevOutJson: $e\nStack trace: $s", level: LogLevel.Warning, ); @@ -293,7 +293,7 @@ class BitcoincashWallet // only found outputs owned by this wallet type = TransactionType.incoming; } else { - Logging.instance.log( + Logging.instance.logd( "Unexpected tx found (ignoring it): $txData", level: LogLevel.Error, ); @@ -345,7 +345,7 @@ class BitcoincashWallet } } catch (e, s) { // Probably doesn't contain a cash token so just log failure - Logging.instance.log( + Logging.instance.logd( "Script pub key \"$scriptPubKeyHex\" cash token" " parsing check failed: $e\n$s", level: LogLevel.Warning, diff --git a/lib/wallets/wallet/impl/cardano_wallet.dart b/lib/wallets/wallet/impl/cardano_wallet.dart index 2b9a8b9bb..3a555c2d3 100644 --- a/lib/wallets/wallet/impl/cardano_wallet.dart +++ b/lib/wallets/wallet/impl/cardano_wallet.dart @@ -76,7 +76,7 @@ class CardanoWallet extends Bip39Wallet { await mainDB.updateOrPutAddresses([address]); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType checkSaveInitialReceivingAddress() failed: $e\n$s", level: LogLevel.Error, ); @@ -94,7 +94,7 @@ class CardanoWallet extends Bip39Wallet { return Future.value(health); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error ping checking in cardano_wallet.dart: $e\n$s", level: LogLevel.Error, ); @@ -146,7 +146,7 @@ class CardanoWallet extends Bip39Wallet { slow: fee, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error getting fees in cardano_wallet.dart: $e\n$s", level: LogLevel.Error, ); @@ -264,7 +264,7 @@ class CardanoWallet extends Bip39Wallet { ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType Cardano prepareSend failed: $e\n$s", level: LogLevel.Error, ); @@ -355,7 +355,7 @@ class CardanoWallet extends Bip39Wallet { txid: sentTx, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType Cardano confirmSend failed: $e\n$s", level: LogLevel.Error, ); @@ -425,7 +425,7 @@ class CardanoWallet extends Bip39Wallet { await info.updateBalance(newBalance: balance, isar: mainDB.isar); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error getting balance in cardano_wallet.dart: $e\n$s", level: LogLevel.Error, ); @@ -446,7 +446,7 @@ class CardanoWallet extends Bip39Wallet { isar: mainDB.isar, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error updating transactions in cardano_wallet.dart: $e\n$s", level: LogLevel.Error, ); @@ -581,7 +581,7 @@ class CardanoWallet extends Bip39Wallet { } on NodeTorMismatchConfigException { rethrow; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error updating transactions in cardano_wallet.dart: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/impl/dash_wallet.dart b/lib/wallets/wallet/impl/dash_wallet.dart index bf1e91b9a..559581256 100644 --- a/lib/wallets/wallet/impl/dash_wallet.dart +++ b/lib/wallets/wallet/impl/dash_wallet.dart @@ -234,7 +234,7 @@ class DashWallet extends Bip39HDWallet // Only found outputs owned by this wallet. type = TransactionType.incoming; } else { - Logging.instance.log( + Logging.instance.logd( "Unexpected tx found (ignoring it): $txData", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/impl/dogecoin_wallet.dart b/lib/wallets/wallet/impl/dogecoin_wallet.dart index 8d2d2f029..52946f170 100644 --- a/lib/wallets/wallet/impl/dogecoin_wallet.dart +++ b/lib/wallets/wallet/impl/dogecoin_wallet.dart @@ -237,7 +237,7 @@ class DogecoinWallet // Only found outputs owned by this wallet. type = TransactionType.incoming; } else { - Logging.instance.log( + Logging.instance.logd( "Unexpected tx found (ignoring it): $txData", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/impl/ecash_wallet.dart b/lib/wallets/wallet/impl/ecash_wallet.dart index 968ea72cc..27ec2e8bd 100644 --- a/lib/wallets/wallet/impl/ecash_wallet.dart +++ b/lib/wallets/wallet/impl/ecash_wallet.dart @@ -276,7 +276,7 @@ class EcashWallet extends Bip39HDWallet // only found outputs owned by this wallet type = TransactionType.incoming; } else { - Logging.instance.log( + Logging.instance.logd( "Unexpected tx found (ignoring it): $txData", level: LogLevel.Error, ); @@ -332,7 +332,7 @@ class EcashWallet extends Bip39HDWallet } } catch (e, s) { // Probably doesn't contain a cash token so just log failure - Logging.instance.log( + Logging.instance.logd( "Script pub key \"$scriptPubKeyHex\" cash token" " parsing check failed: $e\n$s", level: LogLevel.Warning, diff --git a/lib/wallets/wallet/impl/epiccash_wallet.dart b/lib/wallets/wallet/impl/epiccash_wallet.dart index 7533925c8..11b4973bb 100644 --- a/lib/wallets/wallet/impl/epiccash_wallet.dart +++ b/lib/wallets/wallet/impl/epiccash_wallet.dart @@ -93,13 +93,13 @@ class EpiccashWallet extends Bip39Wallet { wallet: wallet, transactionId: txSlateId, ); - Logging.instance.log( + Logging.instance.logd( "cancel $txSlateId result: $result", level: LogLevel.Info, ); return result; } catch (e, s) { - Logging.instance.log("$e, $s", level: LogLevel.Error); + Logging.instance.logd("$e, $s", level: LogLevel.Error); return e.toString(); } } @@ -196,14 +196,15 @@ class EpiccashWallet extends Bip39Wallet { } return realFee; } catch (e, s) { - Logging.instance.log("Error getting fees $e - $s", level: LogLevel.Error); + Logging.instance + .logd("Error getting fees $e - $s", level: LogLevel.Error); rethrow; } } Future _startSync() async { _hackedCheckTorNodePrefs(); - Logging.instance.log("request start sync", level: LogLevel.Info); + Logging.instance.logd("request start sync", level: LogLevel.Info); final wallet = await secureStorageInterface.read(key: '${walletId}_wallet'); const int refreshFromNode = 1; if (!syncMutex.isLocked) { @@ -216,7 +217,7 @@ class EpiccashWallet extends Bip39Wallet { ); }); } else { - Logging.instance.log("request start sync denied", level: LogLevel.Info); + Logging.instance.logd("request start sync denied", level: LogLevel.Info); } } @@ -257,7 +258,7 @@ class EpiccashWallet extends Bip39Wallet { return response is String && response.contains("Challenge"); } catch (_) { - Logging.instance.log( + Logging.instance.logd( "_testEpicBoxConnection failed on \"$host:$port\"", level: LogLevel.Info, ); @@ -289,7 +290,7 @@ class EpiccashWallet extends Bip39Wallet { return true; } catch (e, s) { Logging.instance - .log("ERROR STORING ADDRESS $e $s", level: LogLevel.Error); + .logd("ERROR STORING ADDRESS $e $s", level: LogLevel.Error); return false; } } @@ -301,7 +302,7 @@ class EpiccashWallet extends Bip39Wallet { // of the last one that has not been processed, or the index after the one most recently processed; return receivingIndex; } catch (e, s) { - Logging.instance.log("$e $s", level: LogLevel.Error); + Logging.instance.logd("$e $s", level: LogLevel.Error); return 0; } } @@ -340,7 +341,7 @@ class EpiccashWallet extends Bip39Wallet { epicboxConfig: epicboxConfig.toString(), ); - Logging.instance.log( + Logging.instance.logd( "WALLET_ADDRESS_IS $walletAddress", level: LogLevel.Info, ); @@ -378,7 +379,7 @@ class EpiccashWallet extends Bip39Wallet { // loop while scanning in chain in chunks (of blocks?) while (lastScannedBlock < chainHeight) { - Logging.instance.log( + Logging.instance.logd( "chainHeight: $chainHeight, lastScannedBlock: $lastScannedBlock", level: LogLevel.Info, ); @@ -405,14 +406,14 @@ class EpiccashWallet extends Bip39Wallet { lastScannedBlock = nextScannedBlock; } - Logging.instance.log( + Logging.instance.logd( "_startScans successfully at the tip", level: LogLevel.Info, ); //Once scanner completes restart listener await _listenToEpicbox(); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "_startScans failed: $e\n$s", level: LogLevel.Error, ); @@ -421,7 +422,8 @@ class EpiccashWallet extends Bip39Wallet { } Future _listenToEpicbox() async { - Logging.instance.log("STARTING WALLET LISTENER ....", level: LogLevel.Info); + Logging.instance + .logd("STARTING WALLET LISTENER ....", level: LogLevel.Info); final wallet = await secureStorageInterface.read(key: '${walletId}_wallet'); final EpicBoxConfigModel epicboxConfig = await getEpicBoxConfig(); epiccash.LibEpiccash.startEpicboxListener( @@ -548,7 +550,7 @@ class EpiccashWallet extends Bip39Wallet { ); } else { try { - Logging.instance.log( + Logging.instance.logd( "initializeExisting() ${cryptoCurrency.prettyName} wallet", level: LogLevel.Info, ); @@ -569,7 +571,7 @@ class EpiccashWallet extends Bip39Wallet { await updateNode(); } catch (e, s) { // do nothing, still allow user into wallet - Logging.instance.log( + Logging.instance.logd( "$runtimeType init() failed: $e\n$s", level: LogLevel.Error, ); @@ -635,7 +637,7 @@ class EpiccashWallet extends Bip39Wallet { txid: transaction.slateId, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Epic cash confirmSend: $e\n$s", level: LogLevel.Error, ); @@ -680,7 +682,7 @@ class EpiccashWallet extends Bip39Wallet { ); } catch (e, s) { Logging.instance - .log("Epic cash prepareSend: $e\n$s", level: LogLevel.Error); + .logd("Epic cash prepareSend: $e\n$s", level: LogLevel.Error); rethrow; } } @@ -762,7 +764,7 @@ class EpiccashWallet extends Bip39Wallet { unawaited(refresh(doScan: false)); }); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from electrumx_mixin recover(): $e\n$s", level: LogLevel.Info, ); @@ -880,7 +882,7 @@ class EpiccashWallet extends Bip39Wallet { cryptoCurrency, ), ); - Logging.instance.log( + Logging.instance.logd( "Caught exception in refreshWalletData(): $error\n$strace", level: LogLevel.Error, ); @@ -918,7 +920,7 @@ class EpiccashWallet extends Bip39Wallet { isar: mainDB.isar, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Epic cash wallet failed to update balance: $e\n$s", level: LogLevel.Warning, ); @@ -1058,7 +1060,7 @@ class EpiccashWallet extends Bip39Wallet { await mainDB.isar.transactionV2s.putAll(txns); }); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "${cryptoCurrency.runtimeType} ${cryptoCurrency.network} net wallet" " \"${info.name}\"_${info.walletId} updateTransactions() failed: $e\n$s", level: LogLevel.Warning, @@ -1105,7 +1107,7 @@ class EpiccashWallet extends Bip39Wallet { ) != null; } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Info); + Logging.instance.logd("$e\n$s", level: LogLevel.Info); return false; } } @@ -1162,7 +1164,8 @@ class EpiccashWallet extends Bip39Wallet { timer?.cancel(); timer = null; await super.exit(); - Logging.instance.log("EpicCash_wallet exit finished", level: LogLevel.Info); + Logging.instance + .logd("EpicCash_wallet exit finished", level: LogLevel.Info); } void _hackedCheckTorNodePrefs() { @@ -1216,7 +1219,7 @@ Future deleteEpicWallet({ config: config!, ); } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Error); + Logging.instance.logd("$e\n$s", level: LogLevel.Error); return "deleteEpicWallet($walletId) failed..."; } } diff --git a/lib/wallets/wallet/impl/ethereum_wallet.dart b/lib/wallets/wallet/impl/ethereum_wallet.dart index beb377229..6551f8eda 100644 --- a/lib/wallets/wallet/impl/ethereum_wallet.dart +++ b/lib/wallets/wallet/impl/ethereum_wallet.dart @@ -240,7 +240,7 @@ class EthereumWallet extends Bip39Wallet with PrivateKeyInterface { isar: mainDB.isar, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType wallet failed to update balance: $e\n$s", level: LogLevel.Warning, ); @@ -258,7 +258,7 @@ class EthereumWallet extends Bip39Wallet with PrivateKeyInterface { isar: mainDB.isar, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType Exception caught in chainHeight: $e\n$s", level: LogLevel.Warning, ); @@ -297,7 +297,7 @@ class EthereumWallet extends Bip39Wallet with PrivateKeyInterface { ); if (response.value == null) { - Logging.instance.log( + Logging.instance.logd( "Failed to refresh transactions for ${cryptoCurrency.prettyName} ${info.name} " "$walletId: ${response.exception}", level: LogLevel.Warning, @@ -407,7 +407,7 @@ class EthereumWallet extends Bip39Wallet with PrivateKeyInterface { } await mainDB.updateOrPutTransactionV2s(txns); } else { - Logging.instance.log( + Logging.instance.logd( "Failed to refresh transactions with nonces for ${cryptoCurrency.prettyName} " "${info.name} $walletId: ${txsResponse.exception}", level: LogLevel.Warning, diff --git a/lib/wallets/wallet/impl/firo_wallet.dart b/lib/wallets/wallet/impl/firo_wallet.dart index d149a7a9e..055127c50 100644 --- a/lib/wallets/wallet/impl/firo_wallet.dart +++ b/lib/wallets/wallet/impl/firo_wallet.dart @@ -60,7 +60,7 @@ class FiroWallet extends Bip39HDWallet if (txData.tempTx != null) { await mainDB.updateOrPutTransactionV2s([txData.tempTx!]); _unconfirmedTxids.add(txData.tempTx!.txid); - Logging.instance.log( + Logging.instance.logd( "Added firo unconfirmed: ${txData.tempTx!.txid}", level: LogLevel.Info, ); @@ -221,7 +221,7 @@ class FiroWallet extends Bip39HDWallet ); if (isMySpark && sparkCoinsInvolvedReceived.isEmpty && !isMySpentSpark) { - Logging.instance.log( + Logging.instance.logd( "sparkCoinsInvolvedReceived is empty and should not be! (ignoring tx parsing)", level: LogLevel.Error, ); @@ -229,7 +229,7 @@ class FiroWallet extends Bip39HDWallet } if (isMySpentSpark && sparkCoinsInvolvedSpent.isEmpty && !isMySpark) { - Logging.instance.log( + Logging.instance.logd( "sparkCoinsInvolvedSpent is empty and should not be! (ignoring tx parsing)", level: LogLevel.Error, ); @@ -248,13 +248,13 @@ class FiroWallet extends Bip39HDWallet } else if (asm.startsWith("OP_LELANTUSMINT")) { isMint = true; } else { - Logging.instance.log( + Logging.instance.logd( "Unknown mint op code found for lelantusmint tx: ${txData["txid"]}", level: LogLevel.Error, ); } } else { - Logging.instance.log( + Logging.instance.logd( "ASM for lelantusmint tx: ${txData["txid"]} is null!", level: LogLevel.Error, ); @@ -268,13 +268,13 @@ class FiroWallet extends Bip39HDWallet asm.startsWith("OP_SPARKSMINT")) { isSparkMint = true; } else { - Logging.instance.log( + Logging.instance.logd( "Unknown mint op code found for sparkmint tx: ${txData["txid"]}", level: LogLevel.Error, ); } } else { - Logging.instance.log( + Logging.instance.logd( "ASM for sparkmint tx: ${txData["txid"]} is null!", level: LogLevel.Error, ); @@ -570,7 +570,7 @@ class FiroWallet extends Bip39HDWallet // only found outputs owned by this wallet type = TransactionType.incoming; } else { - Logging.instance.log( + Logging.instance.logd( "Unexpected tx found (ignoring it): $txData", level: LogLevel.Error, ); @@ -747,7 +747,7 @@ class FiroWallet extends Bip39HDWallet ); // receiving addresses - Logging.instance.log( + Logging.instance.logd( "checking receiving addresses...", level: LogLevel.Info, ); @@ -772,7 +772,7 @@ class FiroWallet extends Bip39HDWallet } // change addresses - Logging.instance.log( + Logging.instance.logd( "checking change addresses...", level: LogLevel.Info, ); @@ -899,13 +899,13 @@ class FiroWallet extends Bip39HDWallet }); unawaited(refresh()); - Logging.instance.log( + Logging.instance.logd( "Firo recover for " "${info.name}: ${DateTime.now().difference(start)}", level: LogLevel.Info, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from electrumx_mixin recover(): $e\n$s", level: LogLevel.Info, ); diff --git a/lib/wallets/wallet/impl/litecoin_wallet.dart b/lib/wallets/wallet/impl/litecoin_wallet.dart index d301d0608..073fe1149 100644 --- a/lib/wallets/wallet/impl/litecoin_wallet.dart +++ b/lib/wallets/wallet/impl/litecoin_wallet.dart @@ -287,7 +287,7 @@ class LitecoinWallet // } } } else { - Logging.instance.log( + Logging.instance.logd( "Unexpected tx found (ignoring it): $txData", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/impl/namecoin_wallet.dart b/lib/wallets/wallet/impl/namecoin_wallet.dart index a401d6395..cc92b32e3 100644 --- a/lib/wallets/wallet/impl/namecoin_wallet.dart +++ b/lib/wallets/wallet/impl/namecoin_wallet.dart @@ -264,7 +264,7 @@ class NamecoinWallet // Only found outputs owned by this wallet. type = TransactionType.incoming; } else { - Logging.instance.log( + Logging.instance.logd( "Unexpected tx found (ignoring it): $txData", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/impl/particl_wallet.dart b/lib/wallets/wallet/impl/particl_wallet.dart index 567700e6f..a03068738 100644 --- a/lib/wallets/wallet/impl/particl_wallet.dart +++ b/lib/wallets/wallet/impl/particl_wallet.dart @@ -313,7 +313,7 @@ class ParticlWallet // Only found outputs owned by this wallet. type = TransactionType.incoming; } else { - Logging.instance.log( + Logging.instance.logd( "Unexpected tx found (ignoring it): $txData", level: LogLevel.Error, ); @@ -348,7 +348,7 @@ class ParticlWallet required TxData txData, required List utxoSigningData, }) async { - Logging.instance.log( + Logging.instance.logd( "Starting Particl buildTransaction ----------", level: LogLevel.Info, ); @@ -523,7 +523,7 @@ class ParticlWallet ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Caught exception while signing transaction: $e\n$s", level: LogLevel.Error, ); @@ -540,7 +540,7 @@ class ParticlWallet String hexString = builtTx.toHex(isParticl: true).toString(); if (hexString.length % 2 != 0) { // Ensure the string has an even length. - Logging.instance.log( + Logging.instance.logd( "Hex string has odd length, which is unexpected.", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/impl/peercoin_wallet.dart b/lib/wallets/wallet/impl/peercoin_wallet.dart index e1d993584..ef0ae1c71 100644 --- a/lib/wallets/wallet/impl/peercoin_wallet.dart +++ b/lib/wallets/wallet/impl/peercoin_wallet.dart @@ -272,7 +272,7 @@ class PeercoinWallet // Only found outputs owned by this wallet. type = TransactionType.incoming; } else { - Logging.instance.log( + Logging.instance.logd( "Unexpected tx found (ignoring it): $txData", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/impl/solana_wallet.dart b/lib/wallets/wallet/impl/solana_wallet.dart index 8c7f7e43b..fdf369da9 100644 --- a/lib/wallets/wallet/impl/solana_wallet.dart +++ b/lib/wallets/wallet/impl/solana_wallet.dart @@ -99,7 +99,7 @@ class SolanaWallet extends Bip39Wallet { await mainDB.updateOrPutAddresses([address]); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType checkSaveInitialReceivingAddress() failed: $e\n$s", level: LogLevel.Error, ); @@ -157,7 +157,7 @@ class SolanaWallet extends Bip39Wallet { ), ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType Solana prepareSend failed: $e\n$s", level: LogLevel.Error, ); @@ -197,7 +197,7 @@ class SolanaWallet extends Bip39Wallet { txid: txid, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType Solana confirmSend failed: $e\n$s", level: LogLevel.Error, ); @@ -259,7 +259,7 @@ class SolanaWallet extends Bip39Wallet { health = await _rpcClient?.getHealth(); return health != null; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType Solana pingCheck failed \"health response=$health\": $e\n$s", level: LogLevel.Error, ); @@ -334,7 +334,7 @@ class SolanaWallet extends Bip39Wallet { await info.updateBalance(newBalance: newBalance, isar: mainDB.isar); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error getting balance in solana_wallet.dart: $e\n$s", level: LogLevel.Error, ); @@ -354,7 +354,7 @@ class SolanaWallet extends Bip39Wallet { isar: mainDB.isar, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in solana_wallet.dart while getting" " chain height for solana: $e\n$s", level: LogLevel.Error, @@ -458,7 +458,7 @@ class SolanaWallet extends Bip39Wallet { } on NodeTorMismatchConfigException { rethrow; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in solana_wallet.dart while getting" " transactions for solana: $e\n$s", level: LogLevel.Error, diff --git a/lib/wallets/wallet/impl/stellar_wallet.dart b/lib/wallets/wallet/impl/stellar_wallet.dart index 8932a30fb..7d4b5880c 100644 --- a/lib/wallets/wallet/impl/stellar_wallet.dart +++ b/lib/wallets/wallet/impl/stellar_wallet.dart @@ -172,7 +172,7 @@ class StellarWallet extends Bip39Wallet { exists = true; } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error getting account ${e.toString()} - ${s.toString()}", level: LogLevel.Error, ); @@ -230,7 +230,7 @@ class StellarWallet extends Bip39Wallet { } } catch (e, s) { // do nothing, still allow user into wallet - Logging.instance.log( + Logging.instance.logd( "$runtimeType checkSaveInitialReceivingAddress() failed: $e\n$s", level: LogLevel.Error, ); @@ -266,7 +266,7 @@ class StellarWallet extends Bip39Wallet { ), ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType prepareSend() failed: $e\n$s", level: LogLevel.Error, ); @@ -327,7 +327,7 @@ class StellarWallet extends Bip39Wallet { txid: response.hash!, ); } catch (e, s) { - Logging.instance.log("Error sending TX $e - $s", level: LogLevel.Error); + Logging.instance.logd("Error sending TX $e - $s", level: LogLevel.Error); rethrow; } } @@ -394,7 +394,7 @@ class StellarWallet extends Bip39Wallet { // probably just doesn't have any history yet or whatever stellar needs return; } else { - Logging.instance.log( + Logging.instance.logd( "$runtimeType ${info.name} $walletId " "failed to fetch account to updateBalance", level: LogLevel.Warning, @@ -428,7 +428,7 @@ class StellarWallet extends Bip39Wallet { } } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType ${info.name} $walletId " "updateBalance() failed: $e\n$s", level: LogLevel.Warning, @@ -448,7 +448,7 @@ class StellarWallet extends Bip39Wallet { .then((value) => value.records!.first.sequence); await info.updateCachedChainHeight(newHeight: height, isar: mainDB.isar); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType updateChainHeight() failed: $e\n$s", level: LogLevel.Error, ); @@ -485,7 +485,7 @@ class StellarWallet extends Bip39Wallet { // probably just doesn't have any history yet or whatever stellar needs return; } else { - Logging.instance.log( + Logging.instance.logd( "Stellar ${info.name} $walletId failed to fetch transactions", level: LogLevel.Warning, ); @@ -676,7 +676,7 @@ class StellarWallet extends Bip39Wallet { await mainDB.updateOrPutTransactionV2s(transactionList); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from updateTransactions(): $e\n$s", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/impl/sub_wallets/eth_token_wallet.dart b/lib/wallets/wallet/impl/sub_wallets/eth_token_wallet.dart index 99d831f4b..624b66347 100644 --- a/lib/wallets/wallet/impl/sub_wallets/eth_token_wallet.dart +++ b/lib/wallets/wallet/impl/sub_wallets/eth_token_wallet.dart @@ -153,7 +153,7 @@ class EthTokenWallet extends Wallet { usingContractAddress: contractAddress.hex, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType _updateTokenABI(): $e\n$s", level: LogLevel.Warning, ); @@ -200,7 +200,7 @@ class EthTokenWallet extends Wallet { _sendFunction = _deployedContract.function('transfer'); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType wallet failed init(): $e\n$s", level: LogLevel.Warning, ); @@ -311,7 +311,7 @@ class EthTokenWallet extends Wallet { try { throw Exception(); } catch (_, s) { - Logging.instance.log( + Logging.instance.logd( "Eth token wallet recover called. This should not happen. Stacktrace: $s", level: LogLevel.Warning, ); @@ -347,13 +347,13 @@ class EthTokenWallet extends Wallet { isar: mainDB.isar, ); } else { - Logging.instance.log( + Logging.instance.logd( "CachedEthTokenBalance.fetchAndUpdateCachedBalance failed: ${response.exception}", level: LogLevel.Warning, ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType wallet failed to update balance: $e\n$s", level: LogLevel.Warning, ); @@ -380,7 +380,7 @@ class EthTokenWallet extends Wallet { if (response.exception != null && response.exception!.message .contains("response is empty but status code is 200")) { - Logging.instance.log( + Logging.instance.logd( "No ${tokenContract.name} transfers found for $addressString", level: LogLevel.Info, ); @@ -419,7 +419,7 @@ class EthTokenWallet extends Wallet { // Server indexing failed for some reason. Instead of hard crashing or // showing no transactions we just skip it here. Not ideal but better // than nothing showing up - Logging.instance.log( + Logging.instance.logd( "Server error: Transaction ${tokenDto.transactionHash} not found.", level: LogLevel.Error, ); @@ -523,7 +523,7 @@ class EthTokenWallet extends Wallet { } await mainDB.updateOrPutTransactionV2s(txns); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType wallet failed to update transactions: $e\n$s", level: LogLevel.Warning, ); diff --git a/lib/wallets/wallet/impl/tezos_wallet.dart b/lib/wallets/wallet/impl/tezos_wallet.dart index ab1448319..d0c837302 100644 --- a/lib/wallets/wallet/impl/tezos_wallet.dart +++ b/lib/wallets/wallet/impl/tezos_wallet.dart @@ -60,7 +60,7 @@ class TezosWallet extends Bip39Wallet { return Tezos.standardDerivationPath; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error in _scanPossiblePaths() in tezos_wallet.dart: $e\n$s", level: LogLevel.Error, ); @@ -144,7 +144,7 @@ class TezosWallet extends Bip39Wallet { return opList; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error in _buildSendTransaction() in tezos_wallet.dart: $e\n$s", level: LogLevel.Error, ); @@ -164,7 +164,7 @@ class TezosWallet extends Bip39Wallet { } } catch (e, s) { // do nothing, still allow user into wallet - Logging.instance.log( + Logging.instance.logd( "$runtimeType checkSaveInitialReceivingAddress() failed: $e\n$s", level: LogLevel.Error, ); @@ -271,7 +271,7 @@ class TezosWallet extends Bip39Wallet { tezosOperationsList: opList, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error in prepareSend() in tezos_wallet.dart: $e\n$s", level: LogLevel.Error, ); @@ -338,14 +338,14 @@ class TezosWallet extends Bip39Wallet { } catch (e, s) { if (_estCount > 3) { _estCount = 0; - Logging.instance.log( + Logging.instance.logd( " Error in _estimate in tezos_wallet.dart: $e\n$s", level: LogLevel.Error, ); rethrow; } else { _estCount++; - Logging.instance.log( + Logging.instance.logd( "_estimate() retry _estCount=$_estCount", level: LogLevel.Warning, ); @@ -386,7 +386,7 @@ class TezosWallet extends Bip39Wallet { return fee; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( " Error in estimateFeeFor() in tezos_wallet.dart: $e\n$s", level: LogLevel.Error, ); @@ -499,7 +499,7 @@ class TezosWallet extends Bip39Wallet { await info.updateBalance(newBalance: newBalance, isar: mainDB.isar); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error getting balance in tezos_wallet.dart: $e\n$s", level: LogLevel.Error, ); @@ -523,7 +523,7 @@ class TezosWallet extends Bip39Wallet { isar: mainDB.isar, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Error occurred in tezos_wallet.dart while getting" " chain height for tezos: $e\n$s", level: LogLevel.Error, diff --git a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart index 8ab9efcc8..2e965cb6d 100644 --- a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart +++ b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart @@ -179,7 +179,7 @@ abstract class LibMoneroWallet onNewBlock: onNewBlock, onBalancesChanged: onBalancesChanged, onError: (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Warning); + Logging.instance.logd("$e\n$s", level: LogLevel.Warning); }, ), ); @@ -307,7 +307,7 @@ abstract class LibMoneroWallet privateSpendKey: base.getPrivateSpendKey(), ); } catch (e, s) { - Logging.instance.log("getKeys failed: $e\n$s", level: LogLevel.Fatal); + Logging.instance.logd("getKeys failed: $e\n$s", level: LogLevel.Fatal); return CWKeyData( walletId: walletId, publicViewKey: "ERROR", @@ -374,7 +374,7 @@ abstract class LibMoneroWallet value: "", ); } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Fatal); + Logging.instance.logd("$e\n$s", level: LogLevel.Fatal); } await updateNode(); } @@ -462,7 +462,7 @@ abstract class LibMoneroWallet isar: mainDB.isar, ); } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Fatal); + Logging.instance.logd("$e\n$s", level: LogLevel.Fatal); rethrow; } await updateNode(); @@ -476,7 +476,7 @@ abstract class LibMoneroWallet libMoneroWallet?.startListeners(); libMoneroWallet?.startAutoSaving(); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from recoverFromMnemonic(): $e\n$s", level: LogLevel.Error, ); @@ -548,7 +548,7 @@ abstract class LibMoneroWallet _setSyncStatus(lib_monero_compat.ConnectedSyncStatus()); } catch (e, s) { _setSyncStatus(lib_monero_compat.FailedSyncStatus()); - Logging.instance.log( + Logging.instance.logd( "Exception caught in $runtimeType.updateNode(): $e\n$s", level: LogLevel.Error, ); @@ -802,7 +802,7 @@ abstract class LibMoneroWallet await updateBalance(); await updateTransactions(); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "onBalancesChanged(): $e\n$s", level: LogLevel.Warning, ); @@ -813,7 +813,7 @@ abstract class LibMoneroWallet try { await updateTransactions(); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "onNewBlock(): $e\n$s", level: LogLevel.Warning, ); @@ -1165,7 +1165,7 @@ abstract class LibMoneroWallet isar: mainDB.isar, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception in generateNewAddress(): $e\n$s", level: LogLevel.Error, ); @@ -1178,7 +1178,7 @@ abstract class LibMoneroWallet try { throw Exception(); } catch (_, s) { - Logging.instance.log( + Logging.instance.logd( "checkReceivingAddressForTransactions called but reuse address flag set: $s", level: LogLevel.Error, ); @@ -1230,13 +1230,13 @@ abstract class LibMoneroWallet } } } on SocketException catch (se, s) { - Logging.instance.log( + Logging.instance.logd( "SocketException caught in _checkReceivingAddressForTransactions(): $se\n$s", level: LogLevel.Error, ); return; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from _checkReceivingAddressForTransactions(): $e\n$s", level: LogLevel.Error, ); @@ -1386,7 +1386,7 @@ abstract class LibMoneroWallet throw ArgumentError("Invalid fee rate argument provided!"); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from prepare send(): $e\n$s", level: LogLevel.Info, ); @@ -1407,20 +1407,20 @@ abstract class LibMoneroWallet txData.pendingTransaction!, ); - Logging.instance.log( + Logging.instance.logd( "transaction ${txData.pendingTransaction!.txid} has been sent", level: LogLevel.Info, ); return txData.copyWith(txid: txData.pendingTransaction!.txid); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "${info.name} ${compatType.name.toLowerCase()} confirmSend: $e\n$s", level: LogLevel.Error, ); rethrow; } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from confirmSend(): $e\n$s", level: LogLevel.Info, ); @@ -1499,7 +1499,7 @@ abstract class LibMoneroWallet libMoneroWallet?.startListeners(); libMoneroWallet?.startAutoSaving(); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from recoverViewOnly(): $e\n$s", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/supporting/epiccash_wallet_info_extension.dart b/lib/wallets/wallet/supporting/epiccash_wallet_info_extension.dart index d913df779..4e634ba17 100644 --- a/lib/wallets/wallet/supporting/epiccash_wallet_info_extension.dart +++ b/lib/wallets/wallet/supporting/epiccash_wallet_info_extension.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'package:isar/isar.dart'; + import '../../../utilities/logger.dart'; import '../../isar/models/wallet_info.dart'; @@ -17,7 +18,7 @@ extension EpiccashWalletInfoExtension on WalletInfo { ), ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "ExtraEpiccashWalletInfo.fromMap failed: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/wallet.dart b/lib/wallets/wallet/wallet.dart index 4445ba7a9..accbfea55 100644 --- a/lib/wallets/wallet/wallet.dart +++ b/lib/wallets/wallet/wallet.dart @@ -126,7 +126,7 @@ abstract class Wallet { await updateChainHeight(); } catch (e, s) { // do nothing on failure (besides logging) - Logging.instance.log("$e\n$s", level: LogLevel.Warning); + Logging.instance.logd("$e\n$s", level: LogLevel.Warning); } // return regardless of whether it was updated or not as we want a @@ -552,7 +552,7 @@ abstract class Wallet { cryptoCurrency, ), ); - Logging.instance.log( + Logging.instance.logd( "Caught exception in refreshWalletData(): $error\n$strace", level: LogLevel.Error, ); @@ -699,7 +699,7 @@ abstract class Wallet { ); } - Logging.instance.log( + Logging.instance.logd( "Refresh for " "${info.name}: ${DateTime.now().difference(start)}", level: LogLevel.Info, diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/bcash_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/bcash_interface.dart index 0fd65ba0d..4205d32bd 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/bcash_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/bcash_interface.dart @@ -21,7 +21,7 @@ mixin BCashInterface required List utxoSigningData, }) async { Logging.instance - .log("Starting buildTransaction ----------", level: LogLevel.Info); + .logd("Starting buildTransaction ----------", level: LogLevel.Info); // TODO: use coinlib @@ -114,7 +114,7 @@ mixin BCashInterface ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Caught exception while signing transaction: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/cash_fusion_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/cash_fusion_interface.dart index c22064d03..6bdce0b5e 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/cash_fusion_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/cash_fusion_interface.dart @@ -379,7 +379,7 @@ mixin CashFusionInterface return root.derivePath(derivationPath).privateKey.data; } catch (e, s) { - Logging.instance.log("$e\n$s", level: LogLevel.Fatal); + Logging.instance.logd("$e\n$s", level: LogLevel.Fatal); throw Exception("Derivation path for pubkey=$pubKey could not be found"); } } @@ -741,7 +741,7 @@ mixin CashFusionInterface if (addr == null) { // A utxo object should always have a non null address. // If non found then just ignore the UTXO (aka don't fuse it) - Logging.instance.log( + Logging.instance.logd( "Ignoring utxo=$utxo for address=\"$addressString\" while selecting UTXOs for Fusion", level: LogLevel.Info, ); @@ -781,7 +781,7 @@ mixin CashFusionInterface // Also reset the failed count here. _failedFuseCount = 0; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Error, ); @@ -816,7 +816,7 @@ mixin CashFusionInterface } } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart index b59041ef8..66522fe7b 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart @@ -114,7 +114,7 @@ mixin ElectrumXInterface List? utxos, }) async { Logging.instance - .log("Starting coinSelection ----------", level: LogLevel.Info); + .logd("Starting coinSelection ----------", level: LogLevel.Info); // TODO: multiple recipients one day assert(txData.recipients!.length == 1); @@ -171,22 +171,22 @@ mixin ElectrumXInterface ); } - Logging.instance.log( + Logging.instance.logd( "spendableOutputs.length: ${spendableOutputs.length}", level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( "availableOutputs.length: ${availableOutputs.length}", level: LogLevel.Info, ); Logging.instance - .log("spendableOutputs: $spendableOutputs", level: LogLevel.Info); - Logging.instance.log( + .logd("spendableOutputs: $spendableOutputs", level: LogLevel.Info); + Logging.instance.logd( "spendableSatoshiValue: $spendableSatoshiValue", level: LogLevel.Info, ); - Logging.instance - .log("satoshiAmountToSend: $satoshiAmountToSend", level: LogLevel.Info); + Logging.instance.logd("satoshiAmountToSend: $satoshiAmountToSend", + level: LogLevel.Info); BigInt satoshisBeingUsed = BigInt.zero; int inputsBeingConsumed = 0; @@ -217,11 +217,11 @@ mixin ElectrumXInterface } Logging.instance - .log("satoshisBeingUsed: $satoshisBeingUsed", level: LogLevel.Info); - Logging.instance - .log("inputsBeingConsumed: $inputsBeingConsumed", level: LogLevel.Info); + .logd("satoshisBeingUsed: $satoshisBeingUsed", level: LogLevel.Info); + Logging.instance.logd("inputsBeingConsumed: $inputsBeingConsumed", + level: LogLevel.Info); Logging.instance - .log('utxoObjectsToUse: $utxoObjectsToUse', level: LogLevel.Info); + .logd('utxoObjectsToUse: $utxoObjectsToUse', level: LogLevel.Info); // numberOfOutputs' length must always be equal to that of recipientsArray and recipientsAmtArray final List recipientsArray = [recipientAddress]; @@ -261,7 +261,7 @@ mixin ElectrumXInterface )) .vSize!; } catch (e) { - Logging.instance.log("vSizeForOneOutput: $e", level: LogLevel.Error); + Logging.instance.logd("vSizeForOneOutput: $e", level: LogLevel.Error); rethrow; } @@ -287,7 +287,7 @@ mixin ElectrumXInterface )) .vSize!; } catch (e) { - Logging.instance.log("vSizeForTwoOutPuts: $e", level: LogLevel.Error); + Logging.instance.logd("vSizeForTwoOutPuts: $e", level: LogLevel.Error); rethrow; } @@ -310,11 +310,11 @@ mixin ElectrumXInterface ), ); - Logging.instance.log( + Logging.instance.logd( "feeForTwoOutputs: $feeForTwoOutputs", level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( "feeForOneOutput: $feeForOneOutput", level: LogLevel.Info, ); @@ -322,19 +322,19 @@ mixin ElectrumXInterface final difference = satoshisBeingUsed - satoshiAmountToSend; Future singleOutputTxn() async { - Logging.instance.log( + Logging.instance.logd( 'Input size: $satoshisBeingUsed', level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( 'Recipient output size: $satoshiAmountToSend', level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( 'Fee being paid: $difference sats', level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( 'Estimated fee: $feeForOneOutput', level: LogLevel.Info, ); @@ -358,10 +358,10 @@ mixin ElectrumXInterface // no change output required if (difference == feeForOneOutput) { - Logging.instance.log('1 output in tx', level: LogLevel.Info); + Logging.instance.logd('1 output in tx', level: LogLevel.Info); return await singleOutputTxn(); } else if (difference < feeForOneOutput) { - Logging.instance.log( + Logging.instance.logd( 'Cannot pay tx fee - checking for more outputs and trying again', level: LogLevel.Warning, ); @@ -394,24 +394,24 @@ mixin ElectrumXInterface recipientsArray.add(newChangeAddress); recipientsAmtArray.add(changeOutputSize); - Logging.instance.log('2 outputs in tx', level: LogLevel.Info); - Logging.instance.log( + Logging.instance.logd('2 outputs in tx', level: LogLevel.Info); + Logging.instance.logd( 'Input size: $satoshisBeingUsed', level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( 'Recipient output size: $satoshiAmountToSend', level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( 'Change Output Size: $changeOutputSize', level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( 'Difference (fee being paid): $feeBeingPaid sats', level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( 'Estimated fee: $feeForTwoOutputs', level: LogLevel.Info, ); @@ -433,23 +433,23 @@ mixin ElectrumXInterface recipientsAmtArray.removeLast(); recipientsAmtArray.add(changeOutputSize); - Logging.instance.log( + Logging.instance.logd( 'Adjusted Input size: $satoshisBeingUsed', level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( 'Adjusted Recipient output size: $satoshiAmountToSend', level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( 'Adjusted Change Output Size: $changeOutputSize', level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( 'Adjusted Difference (fee being paid): $feeBeingPaid sats', level: LogLevel.Info, ); - Logging.instance.log( + Logging.instance.logd( 'Adjusted Estimated fee: $feeForTwoOutputs', level: LogLevel.Info, ); @@ -475,7 +475,7 @@ mixin ElectrumXInterface } else { // Something went wrong here. It either overshot or undershot the estimated fee amount or the changeOutputSize // is smaller than or equal to cryptoCurrency.dustLimit. Revert to single output transaction. - Logging.instance.log( + Logging.instance.logd( 'Reverting to 1 output in tx', level: LogLevel.Info, ); @@ -498,7 +498,7 @@ mixin ElectrumXInterface required int feeRatePerKB, }) async { Logging.instance - .log("Attempting to send all $cryptoCurrency", level: LogLevel.Info); + .logd("Attempting to send all $cryptoCurrency", level: LogLevel.Info); if (txData.recipients!.length != 1) { throw Exception( "Send all to more than one recipient not yet supported", @@ -629,7 +629,7 @@ mixin ElectrumXInterface return signingData; } catch (e, s) { Logging.instance - .log("fetchBuildTxData() threw: $e,\n$s", level: LogLevel.Error); + .logd("fetchBuildTxData() threw: $e,\n$s", level: LogLevel.Error); rethrow; } } @@ -640,7 +640,7 @@ mixin ElectrumXInterface required List utxoSigningData, }) async { Logging.instance - .log("Starting buildTransaction ----------", level: LogLevel.Info); + .logd("Starting buildTransaction ----------", level: LogLevel.Info); // temp tx data to show in gui while waiting for real data from server final List tempInputs = []; @@ -810,7 +810,7 @@ mixin ElectrumXInterface ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Caught exception while signing transaction: $e\n$s", level: LogLevel.Error, ); @@ -858,7 +858,7 @@ mixin ElectrumXInterface await electrumXClient.checkElectrumAdapter(); return await fetchChainHeight(retries: retries); } - Logging.instance.log( + Logging.instance.logd( "Exception rethrown in fetchChainHeight\nError: $e\nStack trace: $s", level: LogLevel.Error, ); @@ -891,7 +891,7 @@ mixin ElectrumXInterface } return result; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown in _getBatchTxCount(address: $addresses: $e\n$s", level: LogLevel.Error, ); @@ -937,7 +937,7 @@ mixin ElectrumXInterface // Ignore. This should happen every first time the wallet is opened. } else { Logging.instance - .log("Error closing electrumXClient: $e", level: LogLevel.Error); + .logd("Error closing electrumXClient: $e", level: LogLevel.Error); } } electrumXClient = ElectrumXClient.from( @@ -966,7 +966,7 @@ mixin ElectrumXInterface for (int index = 0; gapCounter < cryptoCurrency.maxUnusedAddressGap; index += txCountBatchSize) { - Logging.instance.log( + Logging.instance.logd( "index: $index, \t GapCounter $chain ${type.name}: $gapCounter", level: LogLevel.Info, ); @@ -1053,7 +1053,7 @@ mixin ElectrumXInterface int index = 0; for (; gapCounter < cryptoCurrency.maxUnusedAddressGap; index++) { - Logging.instance.log( + Logging.instance.logd( "index: $index, \t GapCounter chain=$chain ${type.name}: $gapCounter", level: LogLevel.Info, ); @@ -1177,7 +1177,7 @@ mixin ElectrumXInterface return allTxHashes; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType._fetchHistory: $e\n$s", level: LogLevel.Error, ); @@ -1298,11 +1298,11 @@ mixin ElectrumXInterface ).raw.toInt(), ); - Logging.instance.log("fetched fees: $feeObject", level: LogLevel.Info); + Logging.instance.logd("fetched fees: $feeObject", level: LogLevel.Info); _cachedFees = feeObject; return _cachedFees!; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from _getFees(): $e\nStack trace: $s", level: LogLevel.Error, ); @@ -1375,7 +1375,7 @@ mixin ElectrumXInterface try { throw Exception(); } catch (_, s) { - Logging.instance.log( + Logging.instance.logd( "checkReceivingAddressForTransactions called but reuse address flag set: $s", level: LogLevel.Error, ); @@ -1411,7 +1411,7 @@ mixin ElectrumXInterface } } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from _checkReceivingAddressForTransactions" "($cryptoCurrency): $e\n$s", level: LogLevel.Error, @@ -1430,7 +1430,7 @@ mixin ElectrumXInterface try { throw Exception(); } catch (_, s) { - Logging.instance.log( + Logging.instance.logd( "checkChangeAddressForTransactions called but reuse address flag set: $s", level: LogLevel.Error, ); @@ -1463,7 +1463,7 @@ mixin ElectrumXInterface await checkChangeAddressForTransactions(); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from _checkChangeAddressForTransactions" "($cryptoCurrency): $e\n$s", level: LogLevel.Error, @@ -1503,7 +1503,7 @@ mixin ElectrumXInterface } // receiving addresses - Logging.instance.log( + Logging.instance.logd( "checking receiving addresses...", level: LogLevel.Info, ); @@ -1528,7 +1528,7 @@ mixin ElectrumXInterface } // change addresses - Logging.instance.log( + Logging.instance.logd( "checking change addresses...", level: LogLevel.Info, ); @@ -1634,7 +1634,7 @@ mixin ElectrumXInterface paymentCodeStrings: codesToCheck, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to check ${PaynymIsApi.baseURL} followers/following for history during " "bitcoin wallet ($walletId ${info.name}) " "_recoverWalletFromBIP32SeedPhrase: $e/n$s", @@ -1646,7 +1646,7 @@ mixin ElectrumXInterface unawaited(refresh()); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from electrumx_mixin recover(): $e\n$s", level: LogLevel.Info, ); @@ -1714,7 +1714,7 @@ mixin ElectrumXInterface return await mainDB.updateUTXOs(walletId, outputArray); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Output fetch unsuccessful: $e\n$s", level: LogLevel.Error, ); @@ -1725,12 +1725,13 @@ mixin ElectrumXInterface @override Future confirmSend({required TxData txData}) async { try { - Logging.instance.log("confirmSend txData: $txData", level: LogLevel.Info); + Logging.instance + .logd("confirmSend txData: $txData", level: LogLevel.Info); final txHash = await electrumXClient.broadcastTransaction( rawTx: txData.raw!, ); - Logging.instance.log("Sent txHash: $txHash", level: LogLevel.Info); + Logging.instance.logd("Sent txHash: $txHash", level: LogLevel.Info); txData = txData.copyWith( usedUTXOs: @@ -1745,7 +1746,7 @@ mixin ElectrumXInterface return await updateSentCachedTxData(txData: txData); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from confirmSend(): $e\n$s", level: LogLevel.Error, ); @@ -1798,7 +1799,7 @@ mixin ElectrumXInterface ); Logging.instance - .log("PREPARE SEND RESULT: $result", level: LogLevel.Info); + .logd("PREPARE SEND RESULT: $result", level: LogLevel.Info); if (result.fee!.raw.toInt() < result.vSize!) { throw Exception( @@ -1846,7 +1847,7 @@ mixin ElectrumXInterface isSendAllCoinControlUtxos: isSendAllCoinControlUtxos, ); - Logging.instance.log("prepare send: $result", level: LogLevel.Info); + Logging.instance.logd("prepare send: $result", level: LogLevel.Info); if (result.fee!.raw.toInt() < result.vSize!) { throw Exception( "Error in fee calculation: Transaction fee (${result.fee!.raw.toInt()}) cannot " @@ -1858,7 +1859,7 @@ mixin ElectrumXInterface throw ArgumentError("Invalid fee rate argument provided!"); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from prepareSend(): $e\n$s", level: LogLevel.Error, ); @@ -1875,7 +1876,7 @@ mixin ElectrumXInterface await super.init(); } catch (e, s) { // do nothing, still allow user into wallet - Logging.instance.log( + Logging.instance.logd( "$runtimeType init() did not complete: $e\n$s", level: LogLevel.Warning, ); @@ -1888,7 +1889,7 @@ mixin ElectrumXInterface .getServerFeatures() .timeout(const Duration(seconds: 5)); - Logging.instance.log("features: $features", level: LogLevel.Info); + Logging.instance.logd("features: $features", level: LogLevel.Info); _serverVersion = _parseServerVersion(features["server_version"] as String); @@ -1897,7 +1898,7 @@ mixin ElectrumXInterface throw Exception("Genesis hash does not match!"); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType _initializeServerVersionAndCheckGenesisHash() did not complete: $e\n$s", level: LogLevel.Warning, ); @@ -1967,7 +1968,7 @@ mixin ElectrumXInterface } } catch (_) {} - Logging.instance.log( + Logging.instance.logd( "${info.name} _parseServerVersion($version) => $result", level: LogLevel.Info, ); @@ -2023,7 +2024,7 @@ mixin ElectrumXInterface if (root != null) { // receiving addresses - Logging.instance.log( + Logging.instance.logd( "checking receiving addresses...", level: LogLevel.Info, ); @@ -2057,7 +2058,7 @@ mixin ElectrumXInterface } // change addresses - Logging.instance.log( + Logging.instance.logd( "checking change addresses...", level: LogLevel.Info, ); @@ -2184,7 +2185,7 @@ mixin ElectrumXInterface unawaited(refresh()); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from electrumx_mixin recoverViewOnly(): $e\n$s", level: LogLevel.Info, ); diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/lelantus_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/lelantus_interface.dart index 3d57f3c36..a51a98a22 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/lelantus_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/lelantus_interface.dart @@ -83,7 +83,7 @@ mixin LelantusInterface privateKey, ); } catch (_) { - Logging.instance.log("error bad key", level: LogLevel.Error); + Logging.instance.logd("error bad key", level: LogLevel.Error); return lelantus.DartLelantusEntry(1, 0, 0, 0, 0, ''); } }).toList(); @@ -153,9 +153,10 @@ mixin LelantusInterface chaincode: root.chaincode, ); - Logging.instance.log("prepared fee: ${result.fee}", level: LogLevel.Info); Logging.instance - .log("prepared vSize: ${result.vSize}", level: LogLevel.Info); + .logd("prepared fee: ${result.fee}", level: LogLevel.Info); + Logging.instance + .logd("prepared vSize: ${result.vSize}", level: LogLevel.Info); // fee should never be less than vSize sanity check if (result.fee!.raw.toInt() < result.vSize!) { @@ -165,7 +166,7 @@ mixin LelantusInterface } return result; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown in firo prepareSend(): $e\n$s", level: LogLevel.Error, ); @@ -231,7 +232,7 @@ mixin LelantusInterface await mainDB.isar.lelantusCoins.put(jmint); }); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); @@ -284,7 +285,7 @@ mixin LelantusInterface await mainDB.addNewTransactionData(txnsData, walletId); } else { // This is a mint - Logging.instance.log("this is a mint", level: LogLevel.Info); + Logging.instance.logd("this is a mint", level: LogLevel.Info); final List updatedCoins = []; @@ -309,7 +310,7 @@ mixin LelantusInterface await mainDB.isar.lelantusCoins.putAll(updatedCoins); }); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); @@ -432,7 +433,7 @@ mixin LelantusInterface txs[address] = txn; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception caught in getJMintTransactions(): $e\n$s", level: LogLevel.Info, ); @@ -441,7 +442,7 @@ mixin LelantusInterface } return txs; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown in getJMintTransactions(): $e\n$s", level: LogLevel.Info, ); @@ -470,7 +471,7 @@ mixin LelantusInterface } return sets; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from refreshAnonymitySets: $e\n$s", level: LogLevel.Error, ); @@ -536,7 +537,7 @@ mixin LelantusInterface final tx = await mainDB.getTransaction(walletId, coin.txid); if (tx == null) { - Logging.instance.log( + Logging.instance.logd( "Transaction with txid=${coin.txid} not found in local db!", level: LogLevel.Error, ); @@ -555,7 +556,7 @@ mixin LelantusInterface await mainDB.isar.lelantusCoins.putAll(updatedCoins); }); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); @@ -638,7 +639,7 @@ mixin LelantusInterface } if (inputTxns.isEmpty) { //some error. - Logging.instance.log( + Logging.instance.logd( "cryptic \"//some error\" occurred in staticProcessRestore on lelantus coin: $coin", level: LogLevel.Error, ); @@ -698,7 +699,7 @@ mixin LelantusInterface await mainDB.isar.lelantusCoins.putAll(result.lelantusCoins); }); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$e\n$s", level: LogLevel.Fatal, ); @@ -716,7 +717,7 @@ mixin LelantusInterface final spendTxs = await getJMintTransactions( result.spendTxIds, ); - Logging.instance.log(spendTxs, level: LogLevel.Info); + Logging.instance.logd(spendTxs, level: LogLevel.Info); for (final element in spendTxs.entries) { final address = element.value.address.value ?? @@ -841,7 +842,7 @@ mixin LelantusInterface } for (final mintsElement in txData.mintsMapLelantus!) { - Logging.instance.log("using $mintsElement", level: LogLevel.Info); + Logging.instance.logd("using $mintsElement", level: LogLevel.Info); final Uint8List mintu8 = Format.stringToUint8List(mintsElement['script'] as String); txb.addOutput(mintu8, mintsElement['value'] as int); @@ -1063,7 +1064,7 @@ mixin LelantusInterface try { anonymitySets = await fetchAnonymitySets(); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Firo needs better internet to create mints: $e\n$s", level: LogLevel.Fatal, ); @@ -1087,7 +1088,7 @@ mixin LelantusInterface } if (isUsedMintTag) { - Logging.instance.log( + Logging.instance.logd( "Found used index when minting", level: LogLevel.Warning, ); @@ -1135,7 +1136,7 @@ mixin LelantusInterface unawaited(refresh()); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception caught in anonymizeAllLelantus(): $e\n$s", level: LogLevel.Warning, ); @@ -1171,13 +1172,13 @@ mixin LelantusInterface .findFirstSync(); if (txn == null) { - Logging.instance.log( + Logging.instance.logd( "Transaction not found in DB for lelantus coin: $lelantusCoin", level: LogLevel.Fatal, ); } else { if (txn.isLelantus != true) { - Logging.instance.log( + Logging.instance.logd( "Bad database state found in ${info.name} $walletId for _refreshBalance lelantus", level: LogLevel.Fatal, ); diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/nano_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/nano_interface.dart index e08bc3b45..4bf55253d 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/nano_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/nano_interface.dart @@ -345,7 +345,7 @@ mixin NanoInterface on Bip39Wallet { } } catch (e, s) { // do nothing, still allow user into wallet - Logging.instance.log( + Logging.instance.logd( "$runtimeType checkSaveInitialReceivingAddress() failed: $e\n$s", level: LogLevel.Error, ); @@ -489,7 +489,7 @@ mixin NanoInterface on Bip39Wallet { ); } catch (e, s) { Logging.instance - .log("Error sending transaction $e - $s", level: LogLevel.Error); + .logd("Error sending transaction $e - $s", level: LogLevel.Error); rethrow; } } @@ -669,7 +669,7 @@ mixin NanoInterface on Bip39Wallet { await info.updateBalance(newBalance: balance, isar: mainDB.isar); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to update ${cryptoCurrency.runtimeType} balance: $e\n$s", level: LogLevel.Warning, ); @@ -705,7 +705,7 @@ mixin NanoInterface on Bip39Wallet { await info.updateCachedChainHeight(newHeight: height, isar: mainDB.isar); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to update ${cryptoCurrency.runtimeType} chain height: $e\n$s", level: LogLevel.Warning, ); diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/ordinals_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/ordinals_interface.dart index 4ca21ef1a..09896d2d6 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/ordinals_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/ordinals_interface.dart @@ -19,7 +19,7 @@ mixin OrdinalsInterface return (await _litescribeAPI.getInscriptionsByAddress(address)) .isNotEmpty; } catch (_) { - Logging.instance.log("Litescribe api failure!", level: LogLevel.Error); + Logging.instance.logd("Litescribe api failure!", level: LogLevel.Error); return false; } @@ -54,7 +54,7 @@ mixin OrdinalsInterface await mainDB.isar.ordinals.putAll(ords); }); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType failed refreshInscriptions(): $e\n$s", level: LogLevel.Warning, ); diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart index b20638362..1ad8aa986 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart @@ -889,7 +889,7 @@ mixin PaynymInterface return Tuple2(clTx.toHex(), clTx.vSize()); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "_createNotificationTx(): $e\n$s", level: LogLevel.Error, ); @@ -902,15 +902,15 @@ mixin PaynymInterface }) async { try { Logging.instance - .log("confirmNotificationTx txData: $txData", level: LogLevel.Info); + .logd("confirmNotificationTx txData: $txData", level: LogLevel.Info); final txHash = await electrumXClient.broadcastTransaction(rawTx: txData.raw!); - Logging.instance.log("Sent txHash: $txHash", level: LogLevel.Info); + Logging.instance.logd("Sent txHash: $txHash", level: LogLevel.Info); try { await updateTransactions(); } catch (e) { - Logging.instance.log( + Logging.instance.logd( "refresh() failed in confirmNotificationTx (${info.name}::$walletId): $e", level: LogLevel.Error, ); @@ -921,7 +921,7 @@ mixin PaynymInterface txHash: txHash, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from confirmSend(): $e\n$s", level: LogLevel.Error, ); @@ -1047,7 +1047,7 @@ mixin PaynymInterface return (witnessComponents[1] as String).toUint8ListFromHex; } } catch (e, s) { - Logging.instance.log("_pubKeyFromInput: $e\n$s", level: LogLevel.Info); + Logging.instance.logd("_pubKeyFromInput: $e\n$s", level: LogLevel.Info); } } return null; @@ -1097,7 +1097,7 @@ mixin PaynymInterface return unBlindedPaymentCode; } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "unBlindedPaymentCodeFromTransaction() failed: $e\n$s\nFor tx: $transaction", level: LogLevel.Warning, ); @@ -1149,7 +1149,7 @@ mixin PaynymInterface return unBlindedPaymentCode; } catch (e) { - Logging.instance.log( + Logging.instance.logd( "unBlindedPaymentCodeFromTransactionBad() failed: $e\nFor tx: $transaction", level: LogLevel.Warning, ); @@ -1826,7 +1826,7 @@ mixin PaynymInterface // TODO: [prio=none] Check for special Bitcoin outputs like ordinals. } else { - Logging.instance.log( + Logging.instance.logd( "Unexpected tx found (ignoring it): $txData", level: LogLevel.Error, ); diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/rbf_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/rbf_interface.dart index 80bff1a7a..939987bdd 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/rbf_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/rbf_interface.dart @@ -148,7 +148,7 @@ mixin RbfInterface ), ], ); - Logging.instance.log( + Logging.instance.logd( "RBF on assumed send all", level: LogLevel.Debug, ); @@ -184,7 +184,7 @@ mixin RbfInterface isChange: removed.isChange, ), ); - Logging.instance.log( + Logging.instance.logd( "RBF with same utxo set with increased fee and reduced change", level: LogLevel.Debug, ); @@ -198,7 +198,7 @@ mixin RbfInterface // oh well... // do nothing here as we already removed the change output above - Logging.instance.log( + Logging.instance.logd( "RBF with same utxo set with increased fee and no change", level: LogLevel.Debug, ); @@ -255,7 +255,7 @@ mixin RbfInterface // TODO: remove assert assert(newUtxoSet.length == txData.utxos!.length + extraUtxos.length); - Logging.instance.log( + Logging.instance.logd( "RBF with ${extraUtxos.length} extra utxo(s)" " added to pay for the new fee", level: LogLevel.Debug, diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/spark_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/spark_interface.dart index 8de5bbbab..fc34ed50e 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/spark_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/spark_interface.dart @@ -1,11 +1,15 @@ import 'dart:convert'; +import 'dart:isolate'; import 'dart:math'; import 'package:bitcoindart/bitcoindart.dart' as btc; import 'package:decimal/decimal.dart'; import 'package:flutter/foundation.dart'; +import 'package:flutter_libsparkmobile/flutter_libsparkmobile.dart' as spark + show Log; import 'package:flutter_libsparkmobile/flutter_libsparkmobile.dart'; import 'package:isar/isar.dart'; +import 'package:logger/logger.dart'; import '../../../db/sqlite/firo_cache.dart'; import '../../../models/balance.dart'; @@ -20,6 +24,7 @@ import '../../../utilities/amount/amount.dart'; import '../../../utilities/enums/derive_path_type_enum.dart'; import '../../../utilities/extensions/extensions.dart'; import '../../../utilities/logger.dart'; +import '../../../utilities/prefs.dart'; import '../../crypto_currency/interfaces/electrumx_currency_interface.dart'; import '../../isar/models/spark_coin.dart'; import '../../isar/models/wallet_info.dart'; @@ -50,6 +55,75 @@ String _hashTag(String tag) { return hash; } +void initSparkLogging(Level level) { + final levels = Level.values.where((e) => e >= level).map((e) => e.name); + spark.Log.levels + .addAll(LoggingLevel.values.where((e) => levels.contains(e.name))); + spark.Log.onLog = ( + level, + value, { + error, + stackTrace, + required time, + }) { + Logging.instance.log( + level.getLoggerLevel(), + value, + error: error, + stackTrace: stackTrace, + time: time, + ); + }; +} + +abstract class _SparkIsolate { + static Isolate? _isolate; + static SendPort? _sendPort; + static final ReceivePort _receivePort = ReceivePort(); + + static Future initialize() async { + final level = Prefs.instance.logLevel; + + _isolate = await Isolate.spawn( + (SendPort sendPort) { + initSparkLogging(level); // ensure logging is set up in isolate + + final receivePort = ReceivePort(); + + sendPort.send(receivePort.sendPort); + + receivePort.listen((message) async { + if (message is List && message.length == 3) { + final function = message[0] as Function; + final argument = message[1]; + final replyPort = message[2] as SendPort; + + final result = await function(argument); + replyPort.send(result); + } + }); + }, + _receivePort.sendPort, + ); + _sendPort = await _receivePort.first as SendPort; + } + + static Future run(ComputeCallback task, M argument) async { + if (_isolate == null || _sendPort == null) await initialize(); + + final ReceivePort responsePort = ReceivePort(); + _sendPort?.send([task, argument, responsePort.sendPort]); + return await responsePort.first as R; + } +} + +Future computeWithLibSparkLogging( + ComputeCallback callback, + M message, +) async { + return _SparkIsolate.run(callback, message); +} + mixin SparkInterface on Bip39HDWallet, ElectrumXInterface { String? _sparkChangeAddressCached; @@ -70,7 +144,7 @@ mixin SparkInterface Future hashTag(String tag) async { try { - return await compute(_hashTag, tag); + return await computeWithLibSparkLogging(_hashTag, tag); } catch (_) { throw ArgumentError("Invalid tag string format", "tag"); } @@ -105,7 +179,7 @@ mixin SparkInterface } } catch (e, s) { // do nothing, still allow user into wallet - Logging.instance.log( + Logging.instance.logd( "$runtimeType init() failed: $e\n$s", level: LogLevel.Error, ); @@ -553,7 +627,7 @@ mixin SparkInterface ); extractedTx.setPayload(Uint8List(0)); - final spend = await compute( + final spend = await computeWithLibSparkLogging( _createSparkSend, ( privateKeyHex: privateKey.toHex, @@ -685,12 +759,13 @@ mixin SparkInterface required TxData txData, }) async { try { - Logging.instance.log("confirmSend txData: $txData", level: LogLevel.Info); + Logging.instance + .logd("confirmSend txData: $txData", level: LogLevel.Info); final txHash = await electrumXClient.broadcastTransaction( rawTx: txData.raw!, ); - Logging.instance.log("Sent txHash: $txHash", level: LogLevel.Info); + Logging.instance.logd("Sent txHash: $txHash", level: LogLevel.Info); txData = txData.copyWith( // TODO revisit setting these both @@ -709,7 +784,7 @@ mixin SparkInterface return await updateSentCachedTxData(txData: txData); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception rethrown from confirmSend(): $e\n$s", level: LogLevel.Error, ); @@ -764,7 +839,7 @@ mixin SparkInterface // if there is new data we try and identify the coins if (rawCoins.isNotEmpty) { // run identify off main isolate - final myCoins = await compute( + final myCoins = await computeWithLibSparkLogging( _identifyCoins, ( anonymitySetCoins: rawCoins, @@ -783,13 +858,13 @@ mixin SparkInterface return result; } catch (e) { - Logging.instance.log( + Logging.instance.logd( "_refreshSparkCoinsMempoolCheck() failed: $e", level: LogLevel.Error, ); return []; } finally { - Logging.instance.log( + Logging.instance.logd( "$walletId ${info.name} _refreshSparkCoinsMempoolCheck() run " "duration: ${DateTime.now().difference(start)}", level: LogLevel.Debug, @@ -950,7 +1025,7 @@ mixin SparkInterface // try to identify any coins in the unchecked set data final List newlyIdCoins = []; for (final groupId in rawCoinsBySetId.keys) { - final myCoins = await compute( + final myCoins = await computeWithLibSparkLogging( _identifyCoins, ( anonymitySetCoins: rawCoinsBySetId[groupId]!, @@ -1093,13 +1168,13 @@ mixin SparkInterface isar: mainDB.isar, ); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType $walletId ${info.name}: $e\n$s", level: LogLevel.Error, ); rethrow; } finally { - Logging.instance.log( + Logging.instance.logd( "${info.name} refreshSparkData() duration:" " ${DateTime.now().difference(start)}", level: LogLevel.Debug, @@ -1138,7 +1213,7 @@ mixin SparkInterface try { await refreshSparkData(null); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "$runtimeType $walletId ${info.name}: $e\n$s", level: LogLevel.Error, ); @@ -1672,7 +1747,7 @@ mixin SparkInterface ); } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Caught exception while signing spark mint transaction: $e\n$s", level: LogLevel.Error, ); @@ -1825,7 +1900,7 @@ mixin SparkInterface await confirmSparkMintTransactions(txData: TxData(sparkMints: mints)); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception caught in anonymizeAllSpark(): $e\n$s", level: LogLevel.Warning, ); @@ -1932,7 +2007,7 @@ mixin SparkInterface return txData.copyWith(sparkMints: mints); } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Exception caught in prepareSparkMintTransaction(): $e\n$s", level: LogLevel.Warning, ); @@ -2145,7 +2220,7 @@ Future _asyncSparkFeesWrapper({ required List serializedCoins, required int privateRecipientsCount, }) async { - return await compute( + return await computeWithLibSparkLogging( _estSparkFeeComputeFunc, ( privateKeyHex: privateKeyHex, diff --git a/lib/widgets/custom_buttons/paynym_follow_toggle_button.dart b/lib/widgets/custom_buttons/paynym_follow_toggle_button.dart index daa87415c..a2c4db100 100644 --- a/lib/widgets/custom_buttons/paynym_follow_toggle_button.dart +++ b/lib/widgets/custom_buttons/paynym_follow_toggle_button.dart @@ -22,6 +22,7 @@ import '../../providers/global/wallets_provider.dart'; import '../../providers/wallet/my_paynym_account_state_provider.dart'; import '../../themes/stack_colors.dart'; import '../../utilities/assets.dart'; +import '../../utilities/logger.dart'; import '../../utilities/util.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart'; import '../desktop/primary_button.dart'; @@ -109,23 +110,25 @@ class _PaynymFollowToggleButtonState ); await Future.delayed(const Duration(milliseconds: 200)); - print("RRR result: $result"); + Logging.instance.d("PayNym follow result: $result"); } - print("Follow result: $result on try $i"); + Logging.instance.d("Follow result: $result on try $i"); if (result.value!.following == followedAccount.value!.nymID) { if (!loadingPopped && mounted) { Navigator.of(context, rootNavigator: isDesktop).pop(); } - unawaited( - showFloatingFlushBar( - type: FlushBarType.success, - message: "You are following ${followedAccount.value!.nymName}", - context: context, - ), - ); + if (mounted) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.success, + message: "You are following ${followedAccount.value!.nymName}", + context: context, + ), + ); + } final myAccount = ref.read(myPaynymAccountStateProvider.state).state!; @@ -150,13 +153,15 @@ class _PaynymFollowToggleButtonState Navigator.of(context, rootNavigator: isDesktop).pop(); } - unawaited( - showFloatingFlushBar( - type: FlushBarType.warning, - message: "Failed to follow ${followedAccount.value!.nymName}", - context: context, - ), - ); + if (mounted) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.warning, + message: "Failed to follow ${followedAccount.value!.nymName}", + context: context, + ), + ); + } return false; } @@ -212,23 +217,25 @@ class _PaynymFollowToggleButtonState followedAccount.value!.nonSegwitPaymentCode.code, ); await Future.delayed(const Duration(milliseconds: 200)); - print("unfollow RRR result: $result"); + Logging.instance.d("PayNym unfollow result: $result"); } - print("Unfollow result: $result on try $i"); + Logging.instance.d("Unfollow result: $result on try $i"); if (result.value!.unfollowing == followedAccount.value!.nymID) { if (!loadingPopped && mounted) { Navigator.of(context, rootNavigator: isDesktop).pop(); } - unawaited( - showFloatingFlushBar( - type: FlushBarType.success, - message: "You have unfollowed ${followedAccount.value!.nymName}", - context: context, - ), - ); + if (mounted) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.success, + message: "You have unfollowed ${followedAccount.value!.nymName}", + context: context, + ), + ); + } final myAccount = ref.read(myPaynymAccountStateProvider.state).state!; @@ -247,13 +254,15 @@ class _PaynymFollowToggleButtonState Navigator.of(context, rootNavigator: isDesktop).pop(); } - unawaited( - showFloatingFlushBar( - type: FlushBarType.warning, - message: "Failed to unfollow ${followedAccount.value!.nymName}", - context: context, - ), - ); + if (mounted) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.warning, + message: "Failed to unfollow ${followedAccount.value!.nymName}", + context: context, + ), + ); + } return false; } diff --git a/lib/widgets/date_picker/date_picker.dart b/lib/widgets/date_picker/date_picker.dart index cd843e542..328e2c096 100644 --- a/lib/widgets/date_picker/date_picker.dart +++ b/lib/widgets/date_picker/date_picker.dart @@ -2,6 +2,7 @@ import 'dart:math'; import 'package:calendar_date_picker2/calendar_date_picker2.dart'; import 'package:flutter/material.dart'; + import '../../themes/stack_colors.dart'; import '../../utilities/constants.dart'; import '../../utilities/util.dart'; @@ -22,8 +23,6 @@ Future showSWDatePicker(BuildContext context) async { _size.height >= 550 ? 450 : _size.height - 32, ); } - print("====================================="); - print(size); final now = DateTime.now(); diff --git a/lib/widgets/desktop/qr_code_scanner_dialog.dart b/lib/widgets/desktop/qr_code_scanner_dialog.dart index b9a583f46..24d24c93d 100644 --- a/lib/widgets/desktop/qr_code_scanner_dialog.dart +++ b/lib/widgets/desktop/qr_code_scanner_dialog.dart @@ -61,7 +61,7 @@ class _QrCodeScannerDialogState extends State { try { if (Platform.isLinux && _cameraLinuxPlugin != null) { await _cameraLinuxPlugin.initializeCamera(); - Logging.instance.log("Linux Camera initialized", level: LogLevel.Info); + Logging.instance.logd("Linux Camera initialized", level: LogLevel.Info); } else if (Platform.isWindows && _cameraWindowsPlugin != null) { final List cameras = await _cameraWindowsPlugin.availableCameras(); @@ -81,7 +81,7 @@ class _QrCodeScannerDialogState extends State { await _cameraWindowsPlugin.initializeCamera(_cameraId); // await _cameraWindowsPlugin!.onCameraInitialized(_cameraId).first; // TODO [prio=low]: Make this work. ^^^ - Logging.instance.log( + Logging.instance.logd( "Windows Camera initialized with ID: $_cameraId", level: LogLevel.Info, ); @@ -95,7 +95,7 @@ class _QrCodeScannerDialogState extends State { await CameraMacOS.instance .initialize(cameraMacOSMode: CameraMacOSMode.photo); - Logging.instance.log( + Logging.instance.logd( "macOS Camera initialized with ID: $_macOSDeviceId", level: LogLevel.Info, ); @@ -104,7 +104,7 @@ class _QrCodeScannerDialogState extends State { return true; } catch (e, s) { Logging.instance - .log("Failed to initialize camera: $e\n$s", level: LogLevel.Error); + .logd("Failed to initialize camera: $e\n$s", level: LogLevel.Error); return false; } } @@ -115,11 +115,11 @@ class _QrCodeScannerDialogState extends State { try { if (Platform.isLinux && _cameraLinuxPlugin != null) { _cameraLinuxPlugin.stopCamera(); - Logging.instance.log("Linux Camera stopped", level: LogLevel.Info); + Logging.instance.logd("Linux Camera stopped", level: LogLevel.Info); } else if (Platform.isWindows && _cameraWindowsPlugin != null) { // if (_cameraId >= 0) { await _cameraWindowsPlugin.dispose(_cameraId); - Logging.instance.log( + Logging.instance.logd( "Windows Camera stopped with ID: $_cameraId", level: LogLevel.Info, ); @@ -130,7 +130,7 @@ class _QrCodeScannerDialogState extends State { } else if (Platform.isMacOS) { // if (_macOSDeviceId != null) { await CameraMacOS.instance.stopImageStream(); - Logging.instance.log( + Logging.instance.logd( "macOS Camera stopped with ID: $_macOSDeviceId", level: LogLevel.Info, ); @@ -141,7 +141,7 @@ class _QrCodeScannerDialogState extends State { } } catch (e, s) { Logging.instance - .log("Failed to stop camera: $e\n$s", level: LogLevel.Error); + .logd("Failed to stop camera: $e\n$s", level: LogLevel.Error); } } @@ -162,14 +162,14 @@ class _QrCodeScannerDialogState extends State { final macOSimg = await CameraMacOS.instance.takePicture(); if (macOSimg == null) { Logging.instance - .log("Failed to capture image", level: LogLevel.Error); + .logd("Failed to capture image", level: LogLevel.Error); await Future.delayed(Duration(milliseconds: _imageDelayInMs)); continue; } final img.Image? image = img.decodeImage(macOSimg.bytes!); if (image == null) { Logging.instance - .log("Failed to capture image", level: LogLevel.Error); + .logd("Failed to capture image", level: LogLevel.Error); await Future.delayed(Duration(milliseconds: _imageDelayInMs)); continue; } @@ -187,7 +187,8 @@ class _QrCodeScannerDialogState extends State { // > WARNING Since this will check the image data against all known // > decoders, it is much slower than using an explicit decoder if (image == null) { - Logging.instance.log("Failed to decode image", level: LogLevel.Error); + Logging.instance + .logd("Failed to decode image", level: LogLevel.Error); await Future.delayed(Duration(milliseconds: _imageDelayInMs)); continue; } @@ -360,7 +361,7 @@ class _QrCodeScannerDialogState extends State { } } } catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to decode image: $e\n$s", level: LogLevel.Error, ); diff --git a/lib/widgets/log_level_preference_widget.dart b/lib/widgets/log_level_preference_widget.dart new file mode 100644 index 000000000..7a889564d --- /dev/null +++ b/lib/widgets/log_level_preference_widget.dart @@ -0,0 +1,142 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:logger/logger.dart'; + +import '../providers/global/prefs_provider.dart'; +import '../themes/stack_colors.dart'; +import '../utilities/extensions/extensions.dart'; +import '../utilities/text_styles.dart'; +import '../utilities/util.dart'; +import 'rounded_container.dart'; + +class LogLevelPreferenceWidget extends ConsumerStatefulWidget { + const LogLevelPreferenceWidget({super.key}); + + @override + ConsumerState createState() => + _LogLevelPreferenceWidgetState(); +} + +class _LogLevelPreferenceWidgetState + extends ConsumerState { + double _sliderValue = 0; + static const List _levels = [ + Level.off, + Level.fatal, + Level.error, + Level.warning, + Level.info, + Level.debug, + Level.trace, + ]; + + @override + void initState() { + super.initState(); + _sliderValue = _levels + .indexOf(ref.read(prefsChangeNotifierProvider).logLevel) + .toDouble(); + } + + @override + Widget build(BuildContext context) { + final current = + ref.watch(prefsChangeNotifierProvider.select((s) => s.logLevel)); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "Current level: ${current.name.capitalize()}", + style: Util.isDesktop + ? STextStyles.desktopTextFieldLabel(context) + : STextStyles.fieldLabel(context), + textAlign: TextAlign.left, + ), + Slider( + min: 0, + max: _levels.length - 1, + divisions: _levels.length - 1, + value: _sliderValue, + onChanged: (value) { + // setState(() { + _sliderValue = value; + // }); + ref.read(prefsChangeNotifierProvider).logLevel = + _levels[_sliderValue.toInt()]; + }, + ), + if (current == Level.debug || current == Level.trace) + Padding( + padding: const EdgeInsets.only(top: 10), + child: RoundedContainer( + color: + Theme.of(context).extension()!.warningBackground, + child: RichText( + text: TextSpan( + text: "Privacy Warning: ", + style: STextStyles.label700(context).copyWith( + color: Theme.of(context) + .extension()! + .warningForeground, + fontSize: Util.isDesktop ? 14 : 12, + ), + children: [ + TextSpan( + text: "Selecting ", + style: STextStyles.label(context).copyWith( + color: Theme.of(context) + .extension()! + .warningForeground, + fontSize: Util.isDesktop ? 14 : 12, + ), + ), + TextSpan( + text: "Trace", + style: STextStyles.label700(context).copyWith( + color: Theme.of(context) + .extension()! + .warningForeground, + fontSize: Util.isDesktop ? 14 : 12, + ), + ), + TextSpan( + text: " or ", + style: STextStyles.label(context).copyWith( + color: Theme.of(context) + .extension()! + .warningForeground, + fontSize: Util.isDesktop ? 14 : 12, + ), + ), + TextSpan( + text: "Debug", + style: STextStyles.label700(context).copyWith( + color: Theme.of(context) + .extension()! + .warningForeground, + fontSize: Util.isDesktop ? 14 : 12, + ), + ), + TextSpan( + text: " may log sensitive metadata, such as transaction" + " details, addresses, or network activity. While no" + " private keys, mnemonics, or credentials will ever " + "be logged, enabling these levels could expose " + "information that might compromise privacy if " + "accessed by unauthorized parties.", + style: STextStyles.label(context).copyWith( + color: Theme.of(context) + .extension()! + .warningForeground, + fontSize: Util.isDesktop ? 14 : 12, + ), + ), + ], + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/widgets/textfields/frost_step_field.dart b/lib/widgets/textfields/frost_step_field.dart index f7563080f..125100bf7 100644 --- a/lib/widgets/textfields/frost_step_field.dart +++ b/lib/widgets/textfields/frost_step_field.dart @@ -97,7 +97,7 @@ class _FrostStepFieldState extends State { ); if (qrResult == null) { - Logging.instance.log( + Logging.instance.logd( "Qr scanning cancelled", level: LogLevel.Info, ); @@ -109,7 +109,7 @@ class _FrostStepFieldState extends State { } } } on PlatformException catch (e, s) { - Logging.instance.log( + Logging.instance.logd( "Failed to get camera permissions while trying to scan qr code: $e\n$s", level: LogLevel.Warning, ); diff --git a/lib/widgets/wallet_card.dart b/lib/widgets/wallet_card.dart index 814d4b321..c01b46614 100644 --- a/lib/widgets/wallet_card.dart +++ b/lib/widgets/wallet_card.dart @@ -159,7 +159,7 @@ class SimpleWalletCard extends ConsumerWidget { if (!success!) { // TODO: show error dialog here? - Logging.instance.log( + Logging.instance.logd( "Failed to load token wallet for $contract", level: LogLevel.Error, ); diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index 66db749d9..245400e1a 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -11,6 +11,7 @@ import cs_monero_flutter_libs_macos import desktop_drop import device_info_plus import devicelocale +import file_picker import flutter_libepiccash import flutter_local_notifications import flutter_secure_storage_macos @@ -33,6 +34,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { DesktopDropPlugin.register(with: registry.registrar(forPlugin: "DesktopDropPlugin")) DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) DevicelocalePlugin.register(with: registry.registrar(forPlugin: "DevicelocalePlugin")) + FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin")) FlutterLibepiccashPlugin.register(with: registry.registrar(forPlugin: "FlutterLibepiccashPlugin")) FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin")) FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin")) diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements index 3d2512f1e..4dad60b7a 100644 --- a/macos/Runner/DebugProfile.entitlements +++ b/macos/Runner/DebugProfile.entitlements @@ -6,13 +6,15 @@ com.apple.security.cs.allow-jit - com.apple.security.network.server + com.apple.security.device.audio-input + + com.apple.security.device.camera + + com.apple.security.files.user-selected.read-write com.apple.security.network.client - - com.apple.security.device.audio-input - com.apple.security.device.camera + com.apple.security.network.server diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements index 4094a6367..7c2b75281 100644 --- a/macos/Runner/Release.entitlements +++ b/macos/Runner/Release.entitlements @@ -4,13 +4,15 @@ com.apple.security.app-sandbox - com.apple.security.network.client + com.apple.security.device.audio-input - com.apple.security.network.server + com.apple.security.device.camera - com.apple.security.device.audio-input + com.apple.security.files.user-selected.read-write - com.apple.security.device.camera + com.apple.security.network.client + + com.apple.security.network.server diff --git a/pubspec.lock b/pubspec.lock index bb163c0e0..590466016 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -758,11 +758,11 @@ packages: dependency: "direct main" description: path: "." - ref: "9abc0930081c9859884e073bd25ab88b2114d9e7" - resolved-ref: "9abc0930081c9859884e073bd25ab88b2114d9e7" + ref: b2849e63e1d418ad8d943c886cd3f4ed20d0ff23 + resolved-ref: b2849e63e1d418ad8d943c886cd3f4ed20d0ff23 url: "https://github.com/cypherstack/flutter_file_picker.git" source: git - version: "8.0.3" + version: "8.3.1" fixnum: dependency: transitive description: @@ -824,11 +824,11 @@ packages: dependency: "direct main" description: path: "." - ref: "9318bdd8e76e4dc8a49e3d64e8851c85e017eff3" - resolved-ref: "9318bdd8e76e4dc8a49e3d64e8851c85e017eff3" + ref: dd1e2a31bab034c97f8ea5745d1aa0b70c245490 + resolved-ref: dd1e2a31bab034c97f8ea5745d1aa0b70c245490 url: "https://github.com/cypherstack/flutter_libsparkmobile.git" source: git - version: "0.0.1" + version: "0.0.2" flutter_lints: dependency: "direct dev" description: @@ -1273,13 +1273,14 @@ packages: source: hosted version: "1.0.11" logger: - dependency: transitive + dependency: "direct main" description: - name: logger - sha256: "697d067c60c20999686a0add96cf6aba723b3aa1f83ecf806a8097231529ec32" - url: "https://pub.dev" - source: hosted - version: "2.4.0" + path: "." + ref: "3c0cba27868ebb5c7d65ebc30a8e6e5342186692" + resolved-ref: "3c0cba27868ebb5c7d65ebc30a8e6e5342186692" + url: "https://github.com/cypherstack/logger" + source: git + version: "2.5.0" logging: dependency: transitive description: diff --git a/scripts/app_config/templates/pubspec.template b/scripts/app_config/templates/pubspec.template index bdb0df341..5a2b8e6cd 100644 --- a/scripts/app_config/templates/pubspec.template +++ b/scripts/app_config/templates/pubspec.template @@ -33,7 +33,7 @@ dependencies: flutter_libsparkmobile: git: url: https://github.com/cypherstack/flutter_libsparkmobile.git - ref: 9318bdd8e76e4dc8a49e3d64e8851c85e017eff3 + ref: dd1e2a31bab034c97f8ea5745d1aa0b70c245490 # cs_monero compat (unpublished) compat: @@ -138,7 +138,10 @@ dependencies: pointycastle: ^3.6.0 package_info_plus: ^8.0.2 lottie: ^2.3.2 - file_picker: ^8.0.3 + file_picker: + git: + url: https://github.com/cypherstack/flutter_file_picker.git + ref: b2849e63e1d418ad8d943c886cd3f4ed20d0ff23 connectivity_plus: ^4.0.1 isar: version: 3.1.8 @@ -206,6 +209,11 @@ dependencies: cs_monero_flutter_libs: 1.0.0-pre.0 monero_rpc: ^2.0.0 digest_auth: ^1.0.1 +# logger: ^2.5.0 + logger: + git: + url: https://github.com/cypherstack/logger + ref: 3c0cba27868ebb5c7d65ebc30a8e6e5342186692 dev_dependencies: flutter_test: @@ -233,6 +241,11 @@ flutter_native_splash: android_disable_fullscreen: true dependency_overrides: + logger: + git: + url: https://github.com/cypherstack/logger + ref: 3c0cba27868ebb5c7d65ebc30a8e6e5342186692 + # required to make devicelocale work web: ^0.5.0 @@ -270,12 +283,6 @@ dependency_overrides: url: https://github.com/cypherstack/stack-bip39.git ref: 0cd6d54e2860bea68fc50c801cb9db2a760192fb - - file_picker: - git: - url: https://github.com/cypherstack/flutter_file_picker.git - ref: 9abc0930081c9859884e073bd25ab88b2114d9e7 - crypto: 3.0.2 analyzer: ^6.7.0 pinenacl: ^0.6.0