diff --git a/assets/svg/share-2.svg b/assets/svg/share-2.svg
new file mode 100644
index 000000000..d002d2bff
--- /dev/null
+++ b/assets/svg/share-2.svg
@@ -0,0 +1,14 @@
+
diff --git a/lib/hive/db.dart b/lib/hive/db.dart
index da161ce2d..79e98050b 100644
--- a/lib/hive/db.dart
+++ b/lib/hive/db.dart
@@ -27,6 +27,7 @@ class DB {
static const String boxNamePrefs = "prefs";
static const String boxNameWalletsToDeleteOnStart = "walletsToDeleteOnStart";
static const String boxNamePriceCache = "priceAPIPrice24hCache";
+ static const String boxNameDBInfo = "dbInfo";
String boxNameTxCache({required Coin coin}) => "${coin.name}_txCache";
String boxNameSetCache({required Coin coin}) =>
@@ -50,6 +51,7 @@ class DB {
late final Box _walletInfoSource;
late final Box _boxPrefs;
late final Box _boxTradeLookup;
+ late final Box _boxDBInfo;
final Map> _walletBoxes = {};
@@ -80,13 +82,40 @@ class DB {
// open hive boxes
Future init() async {
if (!_initialized) {
+ if (Hive.isBoxOpen(boxNameDBInfo)) {
+ _boxDBInfo = Hive.box(boxNameDBInfo);
+ } else {
+ _boxDBInfo = await Hive.openBox(boxNameDBInfo);
+ }
await Hive.openBox(boxNameWalletsToDeleteOnStart);
- _boxPrefs = await Hive.openBox(boxNamePrefs);
+
+ if (Hive.isBoxOpen(boxNamePrefs)) {
+ _boxPrefs = Hive.box(boxNamePrefs);
+ } else {
+ _boxPrefs = await Hive.openBox(boxNamePrefs);
+ }
+
_boxAddressBook = await Hive.openBox(boxNameAddressBook);
_boxDebugInfo = await Hive.openBox(boxNameDebugInfo);
- _boxNodeModels = await Hive.openBox(boxNameNodeModels);
- _boxPrimaryNodes = await Hive.openBox(boxNamePrimaryNodes);
- _boxAllWalletsData = await Hive.openBox(boxNameAllWalletsData);
+
+ if (Hive.isBoxOpen(boxNameNodeModels)) {
+ _boxNodeModels = Hive.box(boxNameNodeModels);
+ } else {
+ _boxNodeModels = await Hive.openBox(boxNameNodeModels);
+ }
+
+ if (Hive.isBoxOpen(boxNamePrimaryNodes)) {
+ _boxPrimaryNodes = Hive.box(boxNamePrimaryNodes);
+ } else {
+ _boxPrimaryNodes = await Hive.openBox(boxNamePrimaryNodes);
+ }
+
+ if (Hive.isBoxOpen(boxNameAllWalletsData)) {
+ _boxAllWalletsData = Hive.box(boxNameAllWalletsData);
+ } else {
+ _boxAllWalletsData = await Hive.openBox(boxNameAllWalletsData);
+ }
+
_boxNotifications =
await Hive.openBox(boxNameNotifications);
_boxWatchedTransactions =
@@ -116,8 +145,13 @@ class DB {
name, WalletInfo.fromJson(Map.from(dyn as Map))));
for (final entry in mapped.entries) {
- _walletBoxes[entry.value.walletId] =
- await Hive.openBox(entry.value.walletId);
+ if (Hive.isBoxOpen(entry.value.walletId)) {
+ _walletBoxes[entry.value.walletId] =
+ Hive.box(entry.value.walletId);
+ } else {
+ _walletBoxes[entry.value.walletId] =
+ await Hive.openBox(entry.value.walletId);
+ }
}
}
diff --git a/lib/main.dart b/lib/main.dart
index 5ceb47e1a..10067ac19 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -51,6 +51,7 @@ import 'package:stackwallet/services/trade_service.dart';
import 'package:stackwallet/services/wallets.dart';
import 'package:stackwallet/utilities/cfcolors.dart';
import 'package:stackwallet/utilities/constants.dart';
+import 'package:stackwallet/utilities/db_version_migration.dart';
import 'package:stackwallet/utilities/enums/backup_frequency_type.dart';
import 'package:stackwallet/utilities/logger.dart';
import 'package:stackwallet/utilities/prefs.dart';
@@ -119,18 +120,16 @@ void main() async {
Hive.registerAdapter(UnspentCoinsInfoAdapter());
+ await Hive.openBox(DB.boxNameDBInfo);
+ int dbVersion = DB.instance.get(
+ boxName: DB.boxNameDBInfo, key: "hive_data_version") as int? ??
+ 0;
+ if (dbVersion < Constants.currentHiveDbVersion) {
+ await DbVersionMigrator().migrate(dbVersion);
+ }
+
monero.onStartup();
- // final wallets = await Hive.openBox('wallets');
- // await wallets.put('currentWalletName', "");
-
- // NOT USED YET
- // int dbVersion = await wallets.get("db_version");
- // if (dbVersion == null || dbVersion < Constants.currentDbVersion) {
- // if (dbVersion == null) dbVersion = 0;
- // await DbVersionMigrator().migrate(dbVersion);
- // }
-
// SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
// overlays: [SystemUiOverlay.bottom]);
await NotificationApi.init();
@@ -344,20 +343,23 @@ class _MaterialAppWithThemeState extends ConsumerState
_prefs = ref.read(prefsChangeNotifierProvider);
_wallets = ref.read(walletsChangeNotifierProvider);
- WidgetsBinding.instance.addPostFrameCallback((_) async {
- // fetch open file if it exists
- await getOpenFile();
+ if (Platform.isAndroid) {
+ WidgetsBinding.instance.addPostFrameCallback((_) async {
+ // fetch open file if it exists
+ await getOpenFile();
- if (ref.read(openedFromSWBFileStringStateProvider.state).state != null) {
- // waiting for loading to complete before going straight to restore if the app was opened via file
- await loadingCompleter.future;
+ if (ref.read(openedFromSWBFileStringStateProvider.state).state !=
+ null) {
+ // waiting for loading to complete before going straight to restore if the app was opened via file
+ await loadingCompleter.future;
- await goToRestoreSWB(
- ref.read(openedFromSWBFileStringStateProvider.state).state!);
- ref.read(openedFromSWBFileStringStateProvider.state).state = null;
- }
- // ref.read(shouldShowLockscreenOnResumeStateProvider.state).state = false;
- });
+ await goToRestoreSWB(
+ ref.read(openedFromSWBFileStringStateProvider.state).state!);
+ ref.read(openedFromSWBFileStringStateProvider.state).state = null;
+ }
+ // ref.read(shouldShowLockscreenOnResumeStateProvider.state).state = false;
+ });
+ }
super.initState();
}
@@ -378,14 +380,16 @@ class _MaterialAppWithThemeState extends ConsumerState
case AppLifecycleState.paused:
break;
case AppLifecycleState.resumed:
- // fetch open file if it exists
- await getOpenFile();
- // go straight to restore if the app was resumed via file
- if (ref.read(openedFromSWBFileStringStateProvider.state).state !=
- null) {
- await goToRestoreSWB(
- ref.read(openedFromSWBFileStringStateProvider.state).state!);
- ref.read(openedFromSWBFileStringStateProvider.state).state = null;
+ if (Platform.isAndroid) {
+ // fetch open file if it exists
+ await getOpenFile();
+ // go straight to restore if the app was resumed via file
+ if (ref.read(openedFromSWBFileStringStateProvider.state).state !=
+ null) {
+ await goToRestoreSWB(
+ ref.read(openedFromSWBFileStringStateProvider.state).state!);
+ ref.read(openedFromSWBFileStringStateProvider.state).state = null;
+ }
}
// if (ref.read(hasAuthenticatedOnStartStateProvider.state).state &&
// ref.read(shouldShowLockscreenOnResumeStateProvider.state).state) {
@@ -419,6 +423,7 @@ class _MaterialAppWithThemeState extends ConsumerState
}
}
+ /// should only be called on android currently
Future getOpenFile() async {
// update provider with new file content state
ref.read(openedFromSWBFileStringStateProvider.state).state =
@@ -432,6 +437,7 @@ class _MaterialAppWithThemeState extends ConsumerState
level: LogLevel.Info);
}
+ /// should only be called on android currently
Future resetOpenPath() async {
await platform.invokeMethod("resetOpenPath");
}
diff --git a/lib/models/exchange/estimated_rate_exchange_form_state.dart b/lib/models/exchange/estimated_rate_exchange_form_state.dart
index 210df8c95..4e63bbe20 100644
--- a/lib/models/exchange/estimated_rate_exchange_form_state.dart
+++ b/lib/models/exchange/estimated_rate_exchange_form_state.dart
@@ -1,10 +1,14 @@
import 'package:decimal/decimal.dart';
import 'package:flutter/cupertino.dart';
+import 'package:flutter/material.dart';
import 'package:stackwallet/models/exchange/change_now/currency.dart';
import 'package:stackwallet/services/change_now/change_now.dart';
import 'package:stackwallet/utilities/logger.dart';
class EstimatedRateExchangeFormState extends ChangeNotifier {
+ /// used in testing to inject mock
+ ChangeNow? cnTesting;
+
Decimal? _fromAmount;
Decimal? _toAmount;
@@ -16,9 +20,43 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
Currency? _from;
Currency? _to;
+ void Function(String)? _onError;
+
Currency? get from => _from;
Currency? get to => _to;
+ String get fromAmountString =>
+ _fromAmount == null ? "" : _fromAmount!.toStringAsFixed(8);
+ String get toAmountString =>
+ _toAmount == null ? "" : _toAmount!.toStringAsFixed(8);
+
+ String get rateDisplayString {
+ if (rate == null || from == null || to == null) {
+ return "N/A";
+ } else {
+ return "1 ${from!.ticker.toUpperCase()} ~${rate!.toStringAsFixed(8)} ${to!.ticker.toUpperCase()}";
+ }
+ }
+
+ bool get canExchange {
+ return _fromAmount != null &&
+ _fromAmount != Decimal.zero &&
+ _toAmount != null &&
+ rate != null &&
+ minimumSendWarning.isEmpty;
+ }
+
+ String get minimumSendWarning {
+ if (_from != null &&
+ _fromAmount != null &&
+ _minFromAmount != null &&
+ _fromAmount! < _minFromAmount!) {
+ return "Minimum amount ${_minFromAmount!.toString()} ${from!.ticker.toUpperCase()}";
+ }
+
+ return "";
+ }
+
Future init(Currency? from, Currency? to) async {
_from = from;
_to = to;
@@ -43,10 +81,6 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
final Decimal? newMinFromAmount = _minToAmount;
final Decimal? newMinToAmount = _minFromAmount;
- // final Decimal? newRate = rate == null
- // ? rate
- // : (Decimal.one / rate!).toDecimal(scaleOnInfinitePrecision: 12);
-
final Currency? newTo = from;
final Currency? newFrom = to;
@@ -63,48 +97,11 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
await _updateMinFromAmount(shouldNotifyListeners: false);
- rate = null;
-
- if (_fromAmount != null) {
- Decimal? amt;
- if (_minFromAmount != null) {
- if (_minFromAmount! > _fromAmount!) {
- amt = await getStandardEstimatedToAmount(
- fromAmount: _minFromAmount!, from: _from!, to: _to!);
- if (amt != null) {
- rate =
- (amt / _minFromAmount!).toDecimal(scaleOnInfinitePrecision: 12);
- }
- } else {
- amt = await getStandardEstimatedToAmount(
- fromAmount: _fromAmount!, from: _from!, to: _to!);
- if (amt != null) {
- rate = (amt / _fromAmount!).toDecimal(scaleOnInfinitePrecision: 12);
- }
- }
- }
- if (rate != null) {
- _toAmount = (_fromAmount! * rate!);
- }
- } else {
- if (_minFromAmount != null) {
- Decimal? amt = await getStandardEstimatedToAmount(
- fromAmount: _minFromAmount!, from: _from!, to: _to!);
- if (amt != null) {
- rate =
- (amt / _minFromAmount!).toDecimal(scaleOnInfinitePrecision: 12);
- }
- }
- }
+ await updateRate();
notifyListeners();
}
- String get fromAmountString =>
- _fromAmount == null ? "" : _fromAmount!.toStringAsFixed(8);
- String get toAmountString =>
- _toAmount == null ? "" : _toAmount!.toStringAsFixed(8);
-
Future updateTo(Currency to, bool shouldNotifyListeners) async {
try {
_to = to;
@@ -115,46 +112,8 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
}
await _updateMinFromAmount(shouldNotifyListeners: shouldNotifyListeners);
- // await _updateMinToAmount(shouldNotifyListeners: shouldNotifyListeners);
- rate = null;
-
- if (_fromAmount != null) {
- Decimal? amt;
- if (_minFromAmount != null) {
- if (_minFromAmount! > _fromAmount!) {
- amt = await getStandardEstimatedToAmount(
- fromAmount: _minFromAmount!, from: _from!, to: _to!);
- if (amt != null) {
- rate = (amt / _minFromAmount!)
- .toDecimal(scaleOnInfinitePrecision: 12);
- }
- debugPrint("A");
- } else {
- amt = await getStandardEstimatedToAmount(
- fromAmount: _fromAmount!, from: _from!, to: _to!);
- if (amt != null) {
- rate =
- (amt / _fromAmount!).toDecimal(scaleOnInfinitePrecision: 12);
- }
- debugPrint("B");
- }
- }
- if (rate != null) {
- _toAmount = (_fromAmount! * rate!);
- }
- debugPrint("C");
- } else {
- if (_minFromAmount != null) {
- Decimal? amt = await getStandardEstimatedToAmount(
- fromAmount: _minFromAmount!, from: _from!, to: _to!);
- if (amt != null) {
- rate =
- (amt / _minFromAmount!).toDecimal(scaleOnInfinitePrecision: 12);
- }
- debugPrint("D");
- }
- }
+ await updateRate();
debugPrint(
"_updated TO: _from=${_from!.ticker} _to=${_to!.ticker} _fromAmount=$_fromAmount _toAmount=$_toAmount rate:$rate");
@@ -163,7 +122,7 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
notifyListeners();
}
} catch (e, s) {
- Logging.instance.log("$e\n$s", level: LogLevel.Fatal);
+ Logging.instance.log("$e\n$s", level: LogLevel.Error);
}
}
@@ -179,40 +138,7 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
await _updateMinFromAmount(shouldNotifyListeners: shouldNotifyListeners);
- rate = null;
-
- if (_fromAmount != null) {
- Decimal? amt;
- if (_minFromAmount != null) {
- if (_minFromAmount! > _fromAmount!) {
- amt = await getStandardEstimatedToAmount(
- fromAmount: _minFromAmount!, from: _from!, to: _to!);
- if (amt != null) {
- rate = (amt / _minFromAmount!)
- .toDecimal(scaleOnInfinitePrecision: 12);
- }
- } else {
- amt = await getStandardEstimatedToAmount(
- fromAmount: _fromAmount!, from: _from!, to: _to!);
- if (amt != null) {
- rate =
- (amt / _fromAmount!).toDecimal(scaleOnInfinitePrecision: 12);
- }
- }
- }
- if (rate != null) {
- _toAmount = (_fromAmount! * rate!);
- }
- } else {
- if (_minFromAmount != null) {
- Decimal? amt = await getStandardEstimatedToAmount(
- fromAmount: _minFromAmount!, from: _from!, to: _to!);
- if (amt != null) {
- rate =
- (amt / _minFromAmount!).toDecimal(scaleOnInfinitePrecision: 12);
- }
- }
- }
+ await updateRate();
debugPrint(
"_updated FROM: _from=${_from!.ticker} _to=${_to!.ticker} _fromAmount=$_fromAmount _toAmount=$_toAmount rate:$rate");
@@ -220,55 +146,10 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
notifyListeners();
}
} catch (e, s) {
- Logging.instance.log("$e\n$s", level: LogLevel.Fatal);
+ Logging.instance.log("$e\n$s", level: LogLevel.Error);
}
}
- String get rateDisplayString {
- if (rate == null || from == null || to == null) {
- return "N/A";
- } else {
- return "1 ${from!.ticker.toUpperCase()} ~${rate!.toStringAsFixed(8)} ${to!.ticker.toUpperCase()}";
- }
- }
-
- bool get canExchange {
- return _fromAmount != null &&
- _fromAmount != Decimal.zero &&
- _toAmount != null &&
- rate != null &&
- minimumReceiveWarning.isEmpty &&
- minimumSendWarning.isEmpty;
- }
-
- String get minimumSendWarning {
- if (_from != null &&
- _fromAmount != null &&
- _minFromAmount != null &&
- _fromAmount! < _minFromAmount!) {
- return "Minimum amount ${_minFromAmount!.toString()} ${from!.ticker.toUpperCase()}";
- }
-
- return "";
- }
-
- String get minimumReceiveWarning {
- // TODO not sure this is needed
- // if (_toAmount != null &&
- // _minToAmount != null &&
- // _toAmount! < _minToAmount!) {
- // return "Minimum amount ${_minToAmount!.toString()} ${to.ticker.toUpperCase()}";
- // }
- return "";
- }
-
- // Future _updateMinToAmount({required bool shouldNotifyListeners}) async {
- // _minToAmount = await getStandardMinExchangeAmount(from: to!, to: from!);
- // if (shouldNotifyListeners) {
- // notifyListeners();
- // }
- // }
-
Future _updateMinFromAmount(
{required bool shouldNotifyListeners}) async {
_minFromAmount = await getStandardMinExchangeAmount(from: from!, to: to!);
@@ -277,48 +158,32 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
}
}
- Future setToAmountAndCalculateFromAmount(
- Decimal newToAmount,
- bool shouldNotifyListeners,
- ) async {
- // if (newToAmount == Decimal.zero) {
- // _fromAmount = Decimal.zero;
- // _toAmount = Decimal.zero;
- // if (shouldNotifyListeners) {
- // notifyListeners();
- // }
- // return;
- // }
-
- if (rate != null) {
- _fromAmount =
- (newToAmount / rate!).toDecimal(scaleOnInfinitePrecision: 12);
- }
-
- _toAmount = newToAmount;
- if (shouldNotifyListeners) {
- notifyListeners();
- }
- }
+ // Future setToAmountAndCalculateFromAmount(
+ // Decimal newToAmount,
+ // bool shouldNotifyListeners,
+ // ) async {
+ // if (newToAmount == Decimal.zero) {
+ // _fromAmount = Decimal.zero;
+ // }
+ //
+ // _toAmount = newToAmount;
+ // await updateRate();
+ // if (shouldNotifyListeners) {
+ // notifyListeners();
+ // }
+ // }
Future setFromAmountAndCalculateToAmount(
Decimal newFromAmount,
bool shouldNotifyListeners,
) async {
- // if (newFromAmount == Decimal.zero) {
- // _fromAmount = Decimal.zero;
- // _toAmount = Decimal.zero;
- // if (shouldNotifyListeners) {
- // notifyListeners();
- // }
- // return;
- // }
-
- if (rate != null) {
- _toAmount = (newFromAmount * rate!);
+ if (newFromAmount == Decimal.zero) {
+ _toAmount = Decimal.zero;
}
_fromAmount = newFromAmount;
+ await updateRate();
+
if (shouldNotifyListeners) {
notifyListeners();
}
@@ -329,8 +194,12 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
required Currency from,
required Currency to,
}) async {
- final response = await ChangeNow.instance.getEstimatedExchangeAmount(
- fromTicker: from.ticker, toTicker: to.ticker, fromAmount: fromAmount);
+ final response =
+ await (cnTesting ?? ChangeNow.instance).getEstimatedExchangeAmount(
+ fromTicker: from.ticker,
+ toTicker: to.ticker,
+ fromAmount: fromAmount,
+ );
if (response.value != null) {
return response.value!.estimatedAmount;
@@ -341,11 +210,31 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
}
}
+ // Future getStandardEstimatedFromAmount({
+ // required Decimal toAmount,
+ // required Currency from,
+ // required Currency to,
+ // }) async {
+ // final response = await (cnTesting ?? ChangeNow.instance)
+ // .getEstimatedExchangeAmount(
+ // fromTicker: from.ticker,
+ // toTicker: to.ticker,
+ // fromAmount: toAmount, );
+ //
+ // if (response.value != null) {
+ // return response.value!.fromAmount;
+ // } else {
+ // _onError?.call(
+ // "Failed to fetch estimated amount: ${response.exception?.toString()}");
+ // return null;
+ // }
+ // }
+
Future getStandardMinExchangeAmount({
required Currency from,
required Currency to,
}) async {
- final response = await ChangeNow.instance
+ final response = await (cnTesting ?? ChangeNow.instance)
.getMinimalExchangeAmount(fromTicker: from.ticker, toTicker: to.ticker);
if (response.value != null) {
@@ -357,8 +246,6 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
}
}
- void Function(String)? _onError;
-
void setOnError({
required void Function(String)? onError,
bool shouldNotifyListeners = false,
@@ -368,4 +255,25 @@ class EstimatedRateExchangeFormState extends ChangeNotifier {
notifyListeners();
}
}
+
+ Future updateRate() async {
+ rate = null;
+ final amount = _fromAmount;
+ final minAmount = _minFromAmount;
+ if (amount != null && amount > Decimal.zero) {
+ Decimal? amt;
+ if (minAmount != null) {
+ if (minAmount <= amount) {
+ amt = await getStandardEstimatedToAmount(
+ fromAmount: amount, from: _from!, to: _to!);
+ if (amt != null) {
+ rate = (amt / amount).toDecimal(scaleOnInfinitePrecision: 12);
+ }
+ }
+ }
+ if (rate != null && amt != null) {
+ _toAmount = amt;
+ }
+ }
+ }
}
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 7ce46630d..91c3f1a6d 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
@@ -164,7 +164,7 @@ class _Step4ViewState extends ConsumerState {
height: 8,
),
Text(
- "Send FIRO to the address below. Once it is received, ChangeNOW will send the BTC to the recipient address you provided. You can find this trade details and check its status in the list of trades.",
+ "Send ${model.sendTicker} to the address below. Once it is received, ChangeNOW will send the ${model.receiveTicker} to the recipient address you provided. You can find this trade details and check its status in the list of trades.",
style: STextStyles.itemSubtitle,
),
const SizedBox(
diff --git a/lib/pages/exchange_view/exchange_view.dart b/lib/pages/exchange_view/exchange_view.dart
index df659616f..b47ad3bf6 100644
--- a/lib/pages/exchange_view/exchange_view.dart
+++ b/lib/pages/exchange_view/exchange_view.dart
@@ -231,6 +231,65 @@ class _ExchangeViewState extends ConsumerState {
? ref.read(estimatedRateExchangeFormProvider).toAmountString
: ref.read(fixedRateExchangeFormProvider).toAmountString;
+ _sendFocusNode.addListener(() async {
+ if (!_sendFocusNode.hasFocus) {
+ final newFromAmount = Decimal.tryParse(_sendController.text);
+ if (newFromAmount != null) {
+ if (ref.read(prefsChangeNotifierProvider).exchangeRateType ==
+ ExchangeRateType.estimated) {
+ await ref
+ .read(estimatedRateExchangeFormProvider)
+ .setFromAmountAndCalculateToAmount(newFromAmount, true);
+ } else {
+ await ref
+ .read(fixedRateExchangeFormProvider)
+ .setFromAmountAndCalculateToAmount(newFromAmount, true);
+ }
+ } else {
+ if (ref.read(prefsChangeNotifierProvider).exchangeRateType ==
+ ExchangeRateType.estimated) {
+ await ref
+ .read(estimatedRateExchangeFormProvider)
+ .setFromAmountAndCalculateToAmount(Decimal.zero, true);
+ } else {
+ await ref
+ .read(fixedRateExchangeFormProvider)
+ .setFromAmountAndCalculateToAmount(Decimal.zero, true);
+ }
+ _receiveController.text = "";
+ }
+ }
+ });
+ _receiveFocusNode.addListener(() async {
+ if (!_receiveFocusNode.hasFocus) {
+ final newToAmount = Decimal.tryParse(_receiveController.text);
+ if (newToAmount != null) {
+ if (ref.read(prefsChangeNotifierProvider).exchangeRateType ==
+ ExchangeRateType.estimated) {
+ // await ref
+ // .read(estimatedRateExchangeFormProvider)
+ // .setToAmountAndCalculateFromAmount(newToAmount, true);
+ } else {
+ await ref
+ .read(fixedRateExchangeFormProvider)
+ .setToAmountAndCalculateFromAmount(newToAmount, true);
+ }
+ } else {
+ if (ref.read(prefsChangeNotifierProvider).exchangeRateType ==
+ ExchangeRateType.estimated) {
+ // await ref
+ // .read(estimatedRateExchangeFormProvider)
+ // .setToAmountAndCalculateFromAmount(Decimal.zero, true);
+ } else {
+ await ref
+ .read(fixedRateExchangeFormProvider)
+ .setToAmountAndCalculateFromAmount(Decimal.zero, true);
+ }
+ _sendController.text = "";
+ }
+ }
+ });
+
super.initState();
}
@@ -332,12 +391,12 @@ class _ExchangeViewState extends ConsumerState {
await ref
.read(estimatedRateExchangeFormProvider)
.setFromAmountAndCalculateToAmount(
- newFromAmount, true);
+ newFromAmount, false);
} else {
await ref
.read(fixedRateExchangeFormProvider)
.setFromAmountAndCalculateToAmount(
- newFromAmount, true);
+ newFromAmount, false);
}
} else {
if (ref
@@ -347,12 +406,12 @@ class _ExchangeViewState extends ConsumerState {
await ref
.read(estimatedRateExchangeFormProvider)
.setFromAmountAndCalculateToAmount(
- Decimal.zero, true);
+ Decimal.zero, false);
} else {
await ref
.read(fixedRateExchangeFormProvider)
.setFromAmountAndCalculateToAmount(
- Decimal.zero, true);
+ Decimal.zero, false);
}
_receiveController.text = "";
}
@@ -631,6 +690,10 @@ class _ExchangeViewState extends ConsumerState {
TextFormField(
focusNode: _receiveFocusNode,
controller: _receiveController,
+ readOnly: ref
+ .read(prefsChangeNotifierProvider)
+ .exchangeRateType ==
+ ExchangeRateType.estimated,
onTap: () {
if (_receiveController.text == "-") {
_receiveController.text = "";
@@ -643,30 +706,30 @@ class _ExchangeViewState extends ConsumerState {
.read(prefsChangeNotifierProvider)
.exchangeRateType ==
ExchangeRateType.estimated) {
- await ref
- .read(estimatedRateExchangeFormProvider)
- .setToAmountAndCalculateFromAmount(
- newToAmount, true);
+ // await ref
+ // .read(estimatedRateExchangeFormProvider)
+ // .setToAmountAndCalculateFromAmount(
+ // newToAmount, false);
} else {
await ref
.read(fixedRateExchangeFormProvider)
.setToAmountAndCalculateFromAmount(
- newToAmount, true);
+ newToAmount, false);
}
} else {
if (ref
.read(prefsChangeNotifierProvider)
.exchangeRateType ==
ExchangeRateType.estimated) {
- await ref
- .read(estimatedRateExchangeFormProvider)
- .setToAmountAndCalculateFromAmount(
- Decimal.zero, true);
+ // await ref
+ // .read(estimatedRateExchangeFormProvider)
+ // .setToAmountAndCalculateFromAmount(
+ // Decimal.zero, false);
} else {
await ref
.read(fixedRateExchangeFormProvider)
.setToAmountAndCalculateFromAmount(
- Decimal.zero, true);
+ Decimal.zero, false);
}
_sendController.text = "";
}
diff --git a/lib/pages/exchange_view/sub_widgets/step_row.dart b/lib/pages/exchange_view/sub_widgets/step_row.dart
index 88d6e06cd..5404eb98b 100644
--- a/lib/pages/exchange_view/sub_widgets/step_row.dart
+++ b/lib/pages/exchange_view/sub_widgets/step_row.dart
@@ -55,7 +55,7 @@ class StepRow extends StatelessWidget {
));
}
list.add(StepIndicator(
- step: count - 1,
+ step: count,
status: getStatus(count - 1),
));
return list;
diff --git a/lib/pages/exchange_view/trade_details_view.dart b/lib/pages/exchange_view/trade_details_view.dart
index 16c34891a..68b1f49a6 100644
--- a/lib/pages/exchange_view/trade_details_view.dart
+++ b/lib/pages/exchange_view/trade_details_view.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+
import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -10,6 +12,7 @@ import 'package:stackwallet/notifications/show_flush_bar.dart';
import 'package:stackwallet/pages/exchange_view/edit_trade_note_view.dart';
import 'package:stackwallet/pages/wallet_view/transaction_views/edit_note_view.dart';
import 'package:stackwallet/pages/wallet_view/transaction_views/transaction_details_view.dart';
+import 'package:stackwallet/providers/exchange/change_now_provider.dart';
import 'package:stackwallet/providers/exchange/trade_note_service_provider.dart';
import 'package:stackwallet/providers/global/trades_service_provider.dart';
import 'package:stackwallet/providers/providers.dart';
@@ -63,6 +66,26 @@ class _TradeDetailsViewState extends ConsumerState {
clipboard = widget.clipboard;
transactionIfSentFromStack = widget.transactionIfSentFromStack;
walletId = widget.walletId;
+
+ WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
+ final trade = ref
+ .read(tradesServiceProvider)
+ .trades
+ .firstWhere((e) => e.id == tradeId);
+
+ if (mounted && trade.statusObject == null ||
+ trade.statusObject!.amountSendDecimal.isEmpty) {
+ final status = await ref
+ .read(changeNowProvider)
+ .getTransactionStatus(id: trade.id);
+
+ if (mounted && status.value != null) {
+ await ref.read(tradesServiceProvider).edit(
+ trade: trade.copyWith(statusObject: status.value),
+ shouldNotifyListeners: true);
+ }
+ }
+ });
super.initState();
}
@@ -77,8 +100,6 @@ class _TradeDetailsViewState extends ConsumerState {
status = ChangeNowTransactionStatus.Failed;
}
- debugPrint("statusstatusstatusstatus: $status");
- debugPrint("statusstatusstatusstatusSTRING: $statusString");
switch (status) {
case ChangeNowTransactionStatus.New:
case ChangeNowTransactionStatus.Waiting:
@@ -113,6 +134,11 @@ class _TradeDetailsViewState extends ConsumerState {
debugPrint("hasTx: $hasTx");
debugPrint("trade: ${trade.toString()}");
+ final sendAmount = Decimal.tryParse(
+ trade.statusObject?.amountSendDecimal ?? "") ??
+ Decimal.tryParse(trade.statusObject?.expectedSendAmountDecimal ?? "") ??
+ Decimal.parse("-1");
+
return Scaffold(
backgroundColor: CFColors.almostWhite,
appBar: AppBar(
@@ -150,7 +176,7 @@ class _TradeDetailsViewState extends ConsumerState {
height: 4,
),
SelectableText(
- "${Format.localizedStringAsFixed(value: Decimal.parse(trade.statusObject?.amountSendDecimal ?? trade.amount), locale: ref.watch(
+ "${Format.localizedStringAsFixed(value: sendAmount, locale: ref.watch(
localeServiceChangeNotifierProvider
.select((value) => value.locale),
), decimalPlaces: trade.fromCurrency.toLowerCase() == "xmr" ? 12 : 8)} ${trade.fromCurrency.toUpperCase()}",
@@ -205,7 +231,7 @@ class _TradeDetailsViewState extends ConsumerState {
],
),
),
- if (!sentFromStack && hasTx)
+ if (!sentFromStack && !hasTx)
const SizedBox(
height: 12,
),
@@ -214,9 +240,8 @@ class _TradeDetailsViewState extends ConsumerState {
color: CFColors.warningBackground,
child: RichText(
text: TextSpan(
- text: "You must send at least ${Decimal.parse(
- trade.statusObject!.amountSendDecimal,
- ).toStringAsFixed(
+ text:
+ "You must send at least ${sendAmount.toStringAsFixed(
trade.fromCurrency.toLowerCase() == "xmr" ? 12 : 8,
)} ${trade.fromCurrency.toUpperCase()}. ",
style: STextStyles.label.copyWith(
@@ -225,9 +250,8 @@ class _TradeDetailsViewState extends ConsumerState {
),
children: [
TextSpan(
- text: "If you send less than ${Decimal.parse(
- trade.statusObject!.amountSendDecimal,
- ).toStringAsFixed(
+ text:
+ "If you send less than ${sendAmount.toStringAsFixed(
trade.fromCurrency.toLowerCase() == "xmr"
? 12
: 8,
@@ -623,11 +647,11 @@ class _TradeDetailsViewState extends ConsumerState {
onTap: () async {
final data = ClipboardData(text: trade.id);
await clipboard.setData(data);
- showFloatingFlushBar(
+ unawaited(showFloatingFlushBar(
type: FlushBarType.info,
message: "Copied to clipboard",
context: context,
- );
+ ));
},
child: SvgPicture.asset(
Assets.svg.copy,
diff --git a/lib/pages/exchange_view/wallet_initiated_exchange_view.dart b/lib/pages/exchange_view/wallet_initiated_exchange_view.dart
index 152826345..8a952fd8d 100644
--- a/lib/pages/exchange_view/wallet_initiated_exchange_view.dart
+++ b/lib/pages/exchange_view/wallet_initiated_exchange_view.dart
@@ -716,6 +716,10 @@ class _WalletInitiatedExchangeViewState
TextFormField(
focusNode: _receiveFocusNode,
controller: _receiveController,
+ readOnly: ref
+ .read(prefsChangeNotifierProvider)
+ .exchangeRateType ==
+ ExchangeRateType.estimated,
onTap: () {
if (_receiveController.text == "-") {
_receiveController.text = "";
@@ -728,10 +732,10 @@ class _WalletInitiatedExchangeViewState
.read(prefsChangeNotifierProvider)
.exchangeRateType ==
ExchangeRateType.estimated) {
- await ref
- .read(estimatedRateExchangeFormProvider)
- .setToAmountAndCalculateFromAmount(
- newToAmount, true);
+ // await ref
+ // .read(estimatedRateExchangeFormProvider)
+ // .setToAmountAndCalculateFromAmount(
+ // newToAmount, true);
} else {
await ref
.read(fixedRateExchangeFormProvider)
@@ -743,10 +747,10 @@ class _WalletInitiatedExchangeViewState
.read(prefsChangeNotifierProvider)
.exchangeRateType ==
ExchangeRateType.estimated) {
- await ref
- .read(estimatedRateExchangeFormProvider)
- .setToAmountAndCalculateFromAmount(
- Decimal.zero, true);
+ // await ref
+ // .read(estimatedRateExchangeFormProvider)
+ // .setToAmountAndCalculateFromAmount(
+ // Decimal.zero, true);
} else {
await ref
.read(fixedRateExchangeFormProvider)
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 a473d0d45..037677a40 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
@@ -6,10 +6,12 @@ import 'dart:ui' as ui;
import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
+import 'package:flutter_svg/svg.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:share_plus/share_plus.dart';
import 'package:stackwallet/notifications/show_flush_bar.dart';
+import 'package:stackwallet/utilities/assets.dart';
import 'package:stackwallet/utilities/cfcolors.dart';
import 'package:stackwallet/utilities/clipboard_interface.dart';
import 'package:stackwallet/utilities/constants.dart';
@@ -318,8 +320,7 @@ class _GenerateUriQrCodeViewState extends State {
child: QrImage(
data: uriString,
size: width,
- backgroundColor:
- CFColors.almostWhite,
+ backgroundColor: CFColors.white,
foregroundColor:
CFColors.stackAccent,
),
@@ -344,12 +345,40 @@ class _GenerateUriQrCodeViewState extends State {
CFColors.buttonGray,
),
),
- child: Text(
- "Share",
- style:
- STextStyles.button.copyWith(
- color: CFColors.stackAccent,
- ),
+ child: Row(
+ mainAxisAlignment:
+ MainAxisAlignment.center,
+ crossAxisAlignment:
+ CrossAxisAlignment.center,
+ children: [
+ Center(
+ child: SvgPicture.asset(
+ Assets.svg.share,
+ width: 14,
+ height: 14,
+ ),
+ ),
+ const SizedBox(
+ width: 4,
+ ),
+ Column(
+ children: [
+ Text(
+ "Share",
+ textAlign:
+ TextAlign.center,
+ style: STextStyles.button
+ .copyWith(
+ color: CFColors
+ .stackAccent,
+ ),
+ ),
+ const SizedBox(
+ height: 2,
+ ),
+ ],
+ ),
+ ],
),
),
),
diff --git a/lib/pages/receive_view/receive_view.dart b/lib/pages/receive_view/receive_view.dart
index 4662abac2..b0f49682b 100644
--- a/lib/pages/receive_view/receive_view.dart
+++ b/lib/pages/receive_view/receive_view.dart
@@ -1,36 +1,114 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:stackwallet/notifications/show_flush_bar.dart';
import 'package:stackwallet/pages/receive_view/generate_receiving_uri_qr_code_view.dart';
+import 'package:stackwallet/providers/providers.dart';
import 'package:stackwallet/route_generator.dart';
import 'package:stackwallet/utilities/assets.dart';
import 'package:stackwallet/utilities/cfcolors.dart';
import 'package:stackwallet/utilities/clipboard_interface.dart';
-import 'package:stackwallet/utilities/constants.dart';
import 'package:stackwallet/utilities/enums/coin_enum.dart';
import 'package:stackwallet/utilities/enums/flush_bar_type.dart';
import 'package:stackwallet/utilities/text_styles.dart';
import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart';
+import 'package:stackwallet/widgets/custom_buttons/blue_text_button.dart';
+import 'package:stackwallet/widgets/custom_loading_overlay.dart';
+import 'package:stackwallet/widgets/rounded_white_container.dart';
-class ReceiveView extends StatelessWidget {
+class ReceiveView extends ConsumerStatefulWidget {
const ReceiveView({
Key? key,
required this.coin,
- required this.receivingAddress,
+ required this.walletId,
this.clipboard = const ClipboardWrapper(),
}) : super(key: key);
static const String routeName = "/receiveView";
final Coin coin;
- final String receivingAddress;
+ final String walletId;
final ClipboardInterface clipboard;
+ @override
+ ConsumerState createState() => _ReceiveViewState();
+}
+
+class _ReceiveViewState extends ConsumerState {
+ late final Coin coin;
+ late final String walletId;
+ late final ClipboardInterface clipboard;
+
+ Future generateNewAddress() async {
+ bool shouldPop = false;
+ unawaited(
+ showDialog(
+ context: context,
+ builder: (_) {
+ return WillPopScope(
+ onWillPop: () async => shouldPop,
+ child: const CustomLoadingOverlay(
+ message: "Generating address",
+ eventBus: null,
+ ),
+ );
+ },
+ ),
+ );
+
+ await ref
+ .read(walletsChangeNotifierProvider)
+ .getManager(walletId)
+ .generateNewAddress();
+
+ shouldPop = true;
+
+ if (mounted) {
+ Navigator.of(context)
+ .popUntil(ModalRoute.withName(ReceiveView.routeName));
+ }
+ }
+
+ String receivingAddress = "";
+
+ @override
+ void initState() {
+ walletId = widget.walletId;
+ coin = widget.coin;
+ clipboard = widget.clipboard;
+
+ WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
+ final address = await ref
+ .read(walletsChangeNotifierProvider)
+ .getManager(walletId)
+ .currentReceivingAddress;
+ setState(() {
+ receivingAddress = address;
+ });
+ });
+
+ super.initState();
+ }
+
@override
Widget build(BuildContext context) {
debugPrint("BUILD: $runtimeType");
+
+ ref.listen(
+ ref
+ .read(walletsChangeNotifierProvider)
+ .getManagerProvider(walletId)
+ .select((value) => value.currentReceivingAddress),
+ (previous, next) {
+ if (next is Future) {
+ next.then((value) => setState(() => receivingAddress = value));
+ }
+ });
+
return Scaffold(
backgroundColor: CFColors.almostWhite,
appBar: AppBar(
@@ -52,15 +130,19 @@ class ReceiveView extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Container(
- decoration: BoxDecoration(
- color: CFColors.white,
- borderRadius: BorderRadius.circular(
- Constants.size.circularBorderRadius,
- ),
- ),
- child: Padding(
- padding: const EdgeInsets.all(12.0),
+ GestureDetector(
+ onTap: () {
+ clipboard.setData(
+ ClipboardData(text: receivingAddress),
+ );
+ showFloatingFlushBar(
+ type: FlushBarType.info,
+ message: "Copied to clipboard",
+ iconAsset: Assets.svg.copy,
+ context: context,
+ );
+ },
+ child: RoundedWhiteContainer(
child: Column(
children: [
Row(
@@ -70,35 +152,22 @@ class ReceiveView extends StatelessWidget {
style: STextStyles.itemSubtitle,
),
const Spacer(),
- GestureDetector(
- onTap: () {
- clipboard.setData(
- ClipboardData(text: receivingAddress),
- );
- showFloatingFlushBar(
- type: FlushBarType.info,
- message: "Copied to clipboard",
- iconAsset: Assets.svg.copy,
- context: context,
- );
- },
- child: Row(
- children: [
- SvgPicture.asset(
- Assets.svg.copy,
- width: 10,
- height: 10,
- color: CFColors.link2,
- ),
- const SizedBox(
- width: 4,
- ),
- Text(
- "Copy",
- style: STextStyles.link2,
- ),
- ],
- ),
+ Row(
+ children: [
+ SvgPicture.asset(
+ Assets.svg.copy,
+ width: 10,
+ height: 10,
+ color: CFColors.link2,
+ ),
+ const SizedBox(
+ width: 4,
+ ),
+ Text(
+ "Copy",
+ style: STextStyles.link2,
+ ),
+ ],
),
],
),
@@ -119,47 +188,62 @@ class ReceiveView extends StatelessWidget {
),
),
),
- const SizedBox(
- height: 30,
- ),
- Center(
- child: QrImage(
- data: "${coin.uriScheme}:$receivingAddress",
- size: MediaQuery.of(context).size.width / 2,
- foregroundColor: CFColors.stackAccent,
+ if (coin != Coin.epicCash)
+ const SizedBox(
+ height: 12,
),
- ),
- const SizedBox(
- height: 30,
- ),
- // Spacer(
- // flex: 7,
- // ),
- TextButton(
- onPressed: () {
- Navigator.of(context).push(
- RouteGenerator.getRoute(
- shouldUseMaterialRoute:
- RouteGenerator.useMaterialPageRoute,
- builder: (_) => GenerateUriQrCodeView(
- coin: coin,
- receivingAddress: receivingAddress,
- ),
- settings: const RouteSettings(
- name: GenerateUriQrCodeView.routeName,
- ),
+ if (coin != Coin.epicCash)
+ TextButton(
+ onPressed: generateNewAddress,
+ style: ButtonStyle(
+ backgroundColor: MaterialStateProperty.all(
+ CFColors.buttonGray,
+ ),
+ ),
+ child: Text(
+ "Generate new address",
+ style: STextStyles.button.copyWith(
+ color: CFColors.stackAccent,
),
- );
- },
- style: ButtonStyle(
- backgroundColor: MaterialStateProperty.all(
- CFColors.buttonGray,
),
),
- child: Text(
- "Generate QR Code",
- style: STextStyles.button.copyWith(
- color: CFColors.stackAccent,
+ const SizedBox(
+ height: 30,
+ ),
+ RoundedWhiteContainer(
+ child: Padding(
+ padding: const EdgeInsets.all(8.0),
+ child: Center(
+ child: Column(
+ children: [
+ QrImage(
+ data: "${coin.uriScheme}:$receivingAddress",
+ size: MediaQuery.of(context).size.width / 2,
+ foregroundColor: CFColors.stackAccent,
+ ),
+ const SizedBox(
+ height: 20,
+ ),
+ BlueTextButton(
+ text: "Create new QR code",
+ onTap: () async {
+ unawaited(Navigator.of(context).push(
+ RouteGenerator.getRoute(
+ shouldUseMaterialRoute:
+ RouteGenerator.useMaterialPageRoute,
+ builder: (_) => GenerateUriQrCodeView(
+ coin: coin,
+ receivingAddress: receivingAddress,
+ ),
+ settings: const RouteSettings(
+ name: GenerateUriQrCodeView.routeName,
+ ),
+ ),
+ ));
+ },
+ ),
+ ],
+ ),
),
),
),
diff --git a/lib/pages/wallet_view/wallet_view.dart b/lib/pages/wallet_view/wallet_view.dart
index 3f097ddf3..198e30904 100644
--- a/lib/pages/wallet_view/wallet_view.dart
+++ b/lib/pages/wallet_view/wallet_view.dart
@@ -532,19 +532,17 @@ class _WalletViewState extends ConsumerState {
onExchangePressed: () =>
_onExchangePressed(context),
onReceivePressed: () async {
- final address = await ref
- .read(managerProvider)
- .currentReceivingAddress;
final coin =
ref.read(managerProvider).coin;
if (mounted) {
- Navigator.of(context).pushNamed(
+ unawaited(
+ Navigator.of(context).pushNamed(
ReceiveView.routeName,
arguments: Tuple2(
- address,
+ walletId,
coin,
),
- );
+ ));
}
},
onSendPressed: () {
diff --git a/lib/providers/exchange/available_currencies_state_provider.dart b/lib/providers/exchange/available_currencies_state_provider.dart
index dee8cfa60..5b8395201 100644
--- a/lib/providers/exchange/available_currencies_state_provider.dart
+++ b/lib/providers/exchange/available_currencies_state_provider.dart
@@ -2,4 +2,4 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:stackwallet/models/exchange/change_now/currency.dart';
final availableChangeNowCurrenciesStateProvider =
- StateProvider>((ref) => []);
+ StateProvider>((ref) => []);
diff --git a/lib/providers/exchange/available_floating_rate_pairs_state_provider.dart b/lib/providers/exchange/available_floating_rate_pairs_state_provider.dart
index 5620d1d91..a157b0727 100644
--- a/lib/providers/exchange/available_floating_rate_pairs_state_provider.dart
+++ b/lib/providers/exchange/available_floating_rate_pairs_state_provider.dart
@@ -2,4 +2,5 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:stackwallet/models/exchange/change_now/available_floating_rate_pair.dart';
final availableFloatingRatePairsStateProvider =
- StateProvider>((ref) => []);
+ StateProvider>(
+ (ref) => []);
diff --git a/lib/route_generator.dart b/lib/route_generator.dart
index 329018d9a..001c21b0d 100644
--- a/lib/route_generator.dart
+++ b/lib/route_generator.dart
@@ -681,7 +681,7 @@ class RouteGenerator {
return getRoute(
shouldUseMaterialRoute: useMaterialPageRoute,
builder: (_) => ReceiveView(
- receivingAddress: args.item1,
+ walletId: args.item1,
coin: args.item2,
),
settings: RouteSettings(
diff --git a/lib/services/coins/bitcoin/bitcoin_wallet.dart b/lib/services/coins/bitcoin/bitcoin_wallet.dart
index 0750e9b93..342fb7b91 100644
--- a/lib/services/coins/bitcoin/bitcoin_wallet.dart
+++ b/lib/services/coins/bitcoin/bitcoin_wallet.dart
@@ -3825,4 +3825,34 @@ class BitcoinWallet extends CoinServiceAPI {
return available - estimatedFee;
}
+
+ @override
+ Future generateNewAddress() async {
+ try {
+ await _incrementAddressIndexForChain(
+ 0, DerivePathType.bip84); // First increment the receiving index
+ final newReceivingIndex = DB.instance.get(
+ boxName: walletId,
+ key: 'receivingIndexP2WPKH') as int; // Check the new receiving index
+ final newReceivingAddress = await _generateAddressForChain(
+ 0,
+ newReceivingIndex,
+ DerivePathType
+ .bip84); // Use new index to derive a new receiving address
+ await _addToAddressesArrayForChain(
+ newReceivingAddress,
+ 0,
+ DerivePathType
+ .bip84); // Add that new receiving address to the array of receiving addresses
+ _currentReceivingAddress = Future(() =>
+ newReceivingAddress); // Set the new receiving address that the service
+
+ return true;
+ } catch (e, s) {
+ Logging.instance.log(
+ "Exception rethrown from generateNewAddress(): $e\n$s",
+ level: LogLevel.Error);
+ return false;
+ }
+ }
}
diff --git a/lib/services/coins/coin_service.dart b/lib/services/coins/coin_service.dart
index 3d8b1bd10..bc0e4be28 100644
--- a/lib/services/coins/coin_service.dart
+++ b/lib/services/coins/coin_service.dart
@@ -212,4 +212,6 @@ abstract class CoinServiceAPI {
bool get isConnected;
Future estimateFeeFor(int satoshiAmount, int feeRate);
+
+ Future generateNewAddress();
}
diff --git a/lib/services/coins/dogecoin/dogecoin_wallet.dart b/lib/services/coins/dogecoin/dogecoin_wallet.dart
index 7a3a70a96..a7b2132ad 100644
--- a/lib/services/coins/dogecoin/dogecoin_wallet.dart
+++ b/lib/services/coins/dogecoin/dogecoin_wallet.dart
@@ -3011,6 +3011,35 @@ class DogecoinWallet extends CoinServiceAPI {
return available - estimatedFee;
}
+
+ Future generateNewAddress() async {
+ try {
+ await _incrementAddressIndexForChain(
+ 0, DerivePathType.bip44); // First increment the receiving index
+ final newReceivingIndex = DB.instance.get(
+ boxName: walletId,
+ key: 'receivingIndexP2PKH') as int; // Check the new receiving index
+ final newReceivingAddress = await _generateAddressForChain(
+ 0,
+ newReceivingIndex,
+ DerivePathType
+ .bip44); // Use new index to derive a new receiving address
+ await _addToAddressesArrayForChain(
+ newReceivingAddress,
+ 0,
+ DerivePathType
+ .bip44); // Add that new receiving address to the array of receiving addresses
+ _currentReceivingAddressP2PKH = Future(() =>
+ newReceivingAddress); // Set the new receiving address that the service
+
+ return true;
+ } catch (e, s) {
+ Logging.instance.log(
+ "Exception rethrown from generateNewAddress(): $e\n$s",
+ level: LogLevel.Error);
+ return false;
+ }
+ }
}
// Dogecoin Network
diff --git a/lib/services/coins/epiccash/epiccash_wallet.dart b/lib/services/coins/epiccash/epiccash_wallet.dart
index b57244009..514ddb79f 100644
--- a/lib/services/coins/epiccash/epiccash_wallet.dart
+++ b/lib/services/coins/epiccash/epiccash_wallet.dart
@@ -77,11 +77,8 @@ Future executeNative(Map arguments) async {
final startHeight = arguments['startHeight'] as int?;
final numberOfBlocks = arguments['numberOfBlocks'] as int?;
Map result = {};
- if (!(wallet == null ||
- startHeight == null ||
- numberOfBlocks == null)) {
- var outputs =
- await scanOutPuts(wallet, startHeight, numberOfBlocks);
+ if (!(wallet == null || startHeight == null || numberOfBlocks == null)) {
+ var outputs = await scanOutPuts(wallet, startHeight, numberOfBlocks);
result['outputs'] = outputs;
sendPort.send(result);
return;
@@ -111,8 +108,8 @@ Future executeNative(Map arguments) async {
epicboxConfig == null)) {
Logging.instance
.log("SECRET_KEY_INDEX_IS $secretKeyIndex", level: LogLevel.Info);
- result['result'] = await getSubscribeRequest(
- wallet, secretKeyIndex, epicboxConfig);
+ result['result'] =
+ await getSubscribeRequest(wallet, secretKeyIndex, epicboxConfig);
sendPort.send(result);
return;
}
@@ -122,8 +119,7 @@ Future executeNative(Map arguments) async {
Map result = {};
if (!(wallet == null || slates == null)) {
- result['result'] =
- await processSlates(wallet, slates.toString());
+ result['result'] = await processSlates(wallet, slates.toString());
sendPort.send(result);
return;
}
@@ -135,8 +131,8 @@ Future executeNative(Map arguments) async {
if (!(wallet == null ||
refreshFromNode == null ||
minimumConfirmations == null)) {
- var res = await getWalletInfo(
- wallet, refreshFromNode, minimumConfirmations);
+ var res =
+ await getWalletInfo(wallet, refreshFromNode, minimumConfirmations);
result['result'] = res;
sendPort.send(result);
return;
@@ -166,11 +162,9 @@ Future executeNative(Map arguments) async {
final amount = arguments['amount'] as int?;
final minimumConfirmations = arguments['minimumConfirmations'] as int?;
Map result = {};
- if (!(wallet == null ||
- amount == null ||
- minimumConfirmations == null)) {
- var res = await getTransactionFees(
- wallet, amount, minimumConfirmations);
+ if (!(wallet == null || amount == null || minimumConfirmations == null)) {
+ var res =
+ await getTransactionFees(wallet, amount, minimumConfirmations);
result['result'] = res;
sendPort.send(result);
return;
@@ -198,7 +192,8 @@ Future executeNative(Map arguments) async {
}
} else if (function == "txHttpSend") {
final wallet = arguments['wallet'] as String?;
- final selectionStrategyIsAll = arguments['selectionStrategyIsAll'] as int?;
+ final selectionStrategyIsAll =
+ arguments['selectionStrategyIsAll'] as int?;
final minimumConfirmations = arguments['minimumConfirmations'] as int?;
final message = arguments['message'] as String?;
final amount = arguments['amount'] as int?;
@@ -218,7 +213,6 @@ Future executeNative(Map arguments) async {
sendPort.send(result);
return;
}
-
}
Logging.instance.log(
"Error Arguments for $function not formatted correctly",
@@ -245,8 +239,7 @@ void stop(ReceivePort port) {
// Keep Wrapper functions outside of the class to avoid memory leaks and errors about receive ports and illegal arguments.
// TODO: Can get rid of this wrapper and call it in a full isolate instead of compute() if we want more control over this
-Future _cancelTransactionWrapper(
- Tuple2 data) async {
+Future _cancelTransactionWrapper(Tuple2 data) async {
// assuming this returns an empty string on success
// or an error message string on failure
return cancelTransaction(data.item1, data.item2);
@@ -290,8 +283,7 @@ Future _initWalletWrapper(
Future _initGetAddressInfoWrapper(
Tuple3 data) async {
- String walletAddress =
- getAddressInfo(data.item1, data.item2, data.item3);
+ String walletAddress = getAddressInfo(data.item1, data.item2, data.item3);
return walletAddress;
}
@@ -727,7 +719,7 @@ class EpicCashWallet extends CoinServiceAPI {
/// returns an empty String on success, error message on failure
Future cancelPendingTransaction(String tx_slate_id) async {
final String wallet =
- (await _secureStore.read(key: '${_walletId}_wallet'))!;
+ (await _secureStore.read(key: '${_walletId}_wallet'))!;
String? result;
await m.protect(() async {
@@ -754,7 +746,8 @@ class EpicCashWallet extends CoinServiceAPI {
String receiverAddress = txData['addresss'] as String;
await m.protect(() async {
- if (receiverAddress.startsWith("http://") || receiverAddress.startsWith("https://")) {
+ if (receiverAddress.startsWith("http://") ||
+ receiverAddress.startsWith("https://")) {
const int selectionStrategyIsAll = 0;
ReceivePort receivePort = await getIsolate({
"function": "txHttpSend",
@@ -774,9 +767,8 @@ class EpicCashWallet extends CoinServiceAPI {
throw Exception("txHttpSend isolate failed");
}
stop(receivePort);
- Logging.instance.log('Closing txHttpSend!\n $message',
- level: LogLevel.Info);
-
+ Logging.instance
+ .log('Closing txHttpSend!\n $message', level: LogLevel.Info);
} else {
ReceivePort receivePort = await getIsolate({
"function": "createTransaction",
@@ -809,7 +801,6 @@ class EpicCashWallet extends CoinServiceAPI {
await putSendToAddresses(sendTx);
-
Logging.instance.log("CONFIRM_RESULT_IS $sendTx", level: LogLevel.Info);
final decodeData = json.decode(sendTx);
@@ -818,9 +809,9 @@ class EpicCashWallet extends CoinServiceAPI {
String errorMessage = decodeData[1] as String;
throw Exception("Transaction failed with error code $errorMessage");
} else {
-
//If it's HTTP send no need to post to epicbox
- if (!(receiverAddress.startsWith("http://") || receiverAddress.startsWith("https://"))) {
+ if (!(receiverAddress.startsWith("http://") ||
+ receiverAddress.startsWith("https://"))) {
final postSlateRequest = decodeData[1];
final postToServer = await postSlate(
txData['addresss'] as String, postSlateRequest as String);
@@ -969,10 +960,9 @@ class EpicCashWallet extends CoinServiceAPI {
level: LogLevel.Info);
final config = await getRealConfig();
- final password =
- await _secureStore.read(key: '${_walletId}_password');
+ final password = await _secureStore.read(key: '${_walletId}_password');
- final walletOpen = openWallet(config!, password!);
+ final walletOpen = openWallet(config, password!);
await _secureStore.write(key: '${_walletId}_wallet', value: walletOpen);
if ((DB.instance.get(boxName: walletId, key: "id")) == null) {
@@ -1297,7 +1287,6 @@ class EpicCashWallet extends CoinServiceAPI {
Future startScans() async {
try {
-
final wallet = await _secureStore.read(key: '${_walletId}_wallet');
var restoreHeight =
@@ -1445,7 +1434,6 @@ class EpicCashWallet extends CoinServiceAPI {
//Store Epic box address info
await storeEpicboxInfo();
-
} catch (e, s) {
Logging.instance
.log("Error recovering wallet $e\n$s", level: LogLevel.Error);
@@ -1724,11 +1712,13 @@ class EpicCashWallet extends CoinServiceAPI {
subscribeRequest['signature'] as String, slate as String);
}
- if (response.contains("Error Wallet store error: DB Not Found Error")) {
+ if (response
+ .contains("Error Wallet store error: DB Not Found Error")) {
//Already processed - to be deleted
- Logging.instance.log("DELETING_PROCESSED_SLATE",
- level: LogLevel.Info);
- final slateDelete = await deleteSlate(currentAddress, subscribeRequest['signature'] as String, slate as String);
+ Logging.instance
+ .log("DELETING_PROCESSED_SLATE", level: LogLevel.Info);
+ final slateDelete = await deleteSlate(currentAddress,
+ subscribeRequest['signature'] as String, slate as String);
Logging.instance.log("DELETE_SLATE_RESPONSE $slateDelete",
level: LogLevel.Info);
} else {
@@ -1738,14 +1728,14 @@ class EpicCashWallet extends CoinServiceAPI {
if (slateStatus == "PendingProcessing") {
//Encrypt slate
String encryptedSlate = await getEncryptedSlate(
- wallet!,
+ wallet,
slateSender,
currentReceivingIndex,
epicboxConfig!,
decodedResponse[1] as String);
final postSlateToServer =
- await postSlate(slateSender, encryptedSlate);
+ await postSlate(slateSender, encryptedSlate);
await deleteSlate(currentAddress,
subscribeRequest['signature'] as String, slate as String);
@@ -1753,7 +1743,8 @@ class EpicCashWallet extends CoinServiceAPI {
level: LogLevel.Info);
} else {
//Finalise Slate
- final processSlate = json.decode(decodedResponse[1] as String);
+ final processSlate =
+ json.decode(decodedResponse[1] as String);
Logging.instance.log(
"PROCESSED_SLATE_TO_FINALIZE $processSlate",
level: LogLevel.Info);
@@ -1762,8 +1753,7 @@ class EpicCashWallet extends CoinServiceAPI {
String txSlateId = tx[0]['tx_slate_id'] as String;
Logging.instance
.log("TX_SLATE_ID_IS $txSlateId", level: LogLevel.Info);
- final postToNode = await postSlateToNode(
- wallet!, txSlateId);
+ final postToNode = await postSlateToNode(wallet, txSlateId);
await deleteSlate(currentAddress,
subscribeRequest['signature'] as String, slate as String);
Logging.instance.log("POST_SLATE_RESPONSE $postToNode",
@@ -2316,4 +2306,29 @@ class EpicCashWallet extends CoinServiceAPI {
// TODO: implement this
return currentFee;
}
+
+ // not used in epic currently
+ @override
+ Future generateNewAddress() async {
+ try {
+ // await incrementAddressIndexForChain(
+ // 0); // First increment the receiving index
+ // final newReceivingIndex =
+ // DB.instance.get(boxName: walletId, key: 'receivingIndex')
+ // as int; // Check the new receiving index
+ // final newReceivingAddress = await _generateAddressForChain(0,
+ // newReceivingIndex); // Use new index to derive a new receiving address
+ // await addToAddressesArrayForChain(newReceivingAddress,
+ // 0); // Add that new receiving address to the array of receiving addresses
+ // _currentReceivingAddress = Future(() =>
+ // newReceivingAddress); // Set the new receiving address that the service
+
+ return true;
+ } catch (e, s) {
+ Logging.instance.log(
+ "Exception rethrown from generateNewAddress(): $e\n$s",
+ level: LogLevel.Error);
+ return false;
+ }
+ }
}
diff --git a/lib/services/coins/firo/firo_wallet.dart b/lib/services/coins/firo/firo_wallet.dart
index f469b195a..ae937c80d 100644
--- a/lib/services/coins/firo/firo_wallet.dart
+++ b/lib/services/coins/firo/firo_wallet.dart
@@ -3858,4 +3858,28 @@ class FiroWallet extends CoinServiceAPI {
rethrow;
}
}
+
+ @override
+ Future generateNewAddress() async {
+ try {
+ await incrementAddressIndexForChain(
+ 0); // First increment the receiving index
+ final newReceivingIndex =
+ DB.instance.get(boxName: walletId, key: 'receivingIndex')
+ as int; // Check the new receiving index
+ final newReceivingAddress = await _generateAddressForChain(0,
+ newReceivingIndex); // Use new index to derive a new receiving address
+ await addToAddressesArrayForChain(newReceivingAddress,
+ 0); // Add that new receiving address to the array of receiving addresses
+ _currentReceivingAddress = Future(() =>
+ newReceivingAddress); // Set the new receiving address that the service
+
+ return true;
+ } catch (e, s) {
+ Logging.instance.log(
+ "Exception rethrown from generateNewAddress(): $e\n$s",
+ level: LogLevel.Error);
+ return false;
+ }
+ }
}
diff --git a/lib/services/coins/manager.dart b/lib/services/coins/manager.dart
index 659db73bd..c8329ec28 100644
--- a/lib/services/coins/manager.dart
+++ b/lib/services/coins/manager.dart
@@ -266,4 +266,12 @@ class Manager with ChangeNotifier {
Future estimateFeeFor(int satoshiAmount, int feeRate) async {
return _currentWallet.estimateFeeFor(satoshiAmount, feeRate);
}
+
+ Future generateNewAddress() async {
+ final success = await _currentWallet.generateNewAddress();
+ if (success) {
+ notifyListeners();
+ }
+ return success;
+ }
}
diff --git a/lib/services/coins/monero/monero_wallet.dart b/lib/services/coins/monero/monero_wallet.dart
index 95794a356..b63e711a4 100644
--- a/lib/services/coins/monero/monero_wallet.dart
+++ b/lib/services/coins/monero/monero_wallet.dart
@@ -1521,4 +1521,33 @@ class MoneroWallet extends CoinServiceAPI {
10000;
return fee;
}
+
+ @override
+ Future generateNewAddress() async {
+ try {
+ const String indexKey = "receivingIndex";
+ // First increment the receiving index
+ await _incrementAddressIndexForChain(0);
+ final newReceivingIndex =
+ DB.instance.get(boxName: walletId, key: indexKey) as int;
+
+ // Use new index to derive a new receiving address
+ final newReceivingAddress =
+ await _generateAddressForChain(0, newReceivingIndex);
+
+ // Add that new receiving address to the array of receiving addresses
+ await _addToAddressesArrayForChain(newReceivingAddress, 0);
+
+ // Set the new receiving address that the service
+
+ _currentReceivingAddress = Future(() => newReceivingAddress);
+
+ return true;
+ } catch (e, s) {
+ Logging.instance.log(
+ "Exception rethrown from generateNewAddress(): $e\n$s",
+ level: LogLevel.Error);
+ return false;
+ }
+ }
}
diff --git a/lib/utilities/assets.dart b/lib/utilities/assets.dart
index 9adc50e59..906dd509c 100644
--- a/lib/utilities/assets.dart
+++ b/lib/utilities/assets.dart
@@ -84,6 +84,7 @@ class _SVG {
String get solidSliders => "assets/svg/sliders-solid.svg";
String get questionMessage => "assets/svg/message-question.svg";
String get envelope => "assets/svg/envelope.svg";
+ String get share => "assets/svg/share-2.svg";
String get receive => "assets/svg/tx-icon-receive.svg";
String get receivePending => "assets/svg/tx-icon-receive-pending.svg";
diff --git a/lib/utilities/constants.dart b/lib/utilities/constants.dart
index b8e5b5bce..3b82cde40 100644
--- a/lib/utilities/constants.dart
+++ b/lib/utilities/constants.dart
@@ -33,7 +33,7 @@ abstract class Constants {
// Enable Logger.print statements
static const bool disableLogger = false;
- static const int currentDbVersion = 0;
+ static const int currentHiveDbVersion = 1;
static List possibleLengthsForCoin(Coin coin) {
final List values = [];
diff --git a/lib/utilities/db_version_migration.dart b/lib/utilities/db_version_migration.dart
index ad92b5a59..ec26c5c13 100644
--- a/lib/utilities/db_version_migration.dart
+++ b/lib/utilities/db_version_migration.dart
@@ -1,5 +1,16 @@
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
+import 'package:hive/hive.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx.dart';
+import 'package:stackwallet/hive/db.dart';
+import 'package:stackwallet/models/lelantus_coin.dart';
+import 'package:stackwallet/models/node_model.dart';
+import 'package:stackwallet/services/node_service.dart';
+import 'package:stackwallet/services/wallets_service.dart';
+import 'package:stackwallet/utilities/default_nodes.dart';
+import 'package:stackwallet/utilities/enums/coin_enum.dart';
import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
class DbVersionMigrator {
Future migrate(
@@ -8,83 +19,107 @@ class DbVersionMigrator {
FlutterSecureStorage(),
),
}) async {
- // final wallets = await Hive.openBox('wallets');
- // final names = Map.from((await wallets.get("names")) ?? {});
- //
- // switch (fromVersion) {
- // case 0:
- // // migrate each
- // for (final entry in names.entries) {
- // final walletId = entry.value;
- // final walletName = entry.key;
- //
- // // move main/test network to walletId based
- // final network = await wallets.get("${entry.key}_network");
- // await wallets.put("${walletId}_network", network);
- // await wallets.delete("${walletName}_network");
- //
- // final old = await Hive.openBox(walletName);
- // final wallet = await Hive.openBox(walletId);
- //
- // // notes
- // final oldNotes = await old.get("notes");
- // await wallet.put("notes", oldNotes);
- // await old.delete("notes");
- //
- // // address book
- // final addressBook = await old.get("addressBookEntries");
- // await wallet.put("addressBookEntries", addressBook);
- // await old.put("addressBookEntries", null);
- //
- // // receiveDerivations
- // Map newReceiveDerivations = {};
- // final receiveDerivations =
- // Map.from(await old.get("receiveDerivations") ?? {});
- //
- // for (int i = 0; i < receiveDerivations.length; i++) {
- // receiveDerivations[i].remove("fingerprint");
- // receiveDerivations[i].remove("identifier");
- // receiveDerivations[i].remove("privateKey");
- // newReceiveDerivations["$i"] = receiveDerivations[i];
- // }
- // final receiveDerivationsString = jsonEncode(newReceiveDerivations);
- //
- // await secureStore.write(
- // key: "${walletId}_receiveDerivations",
- // value: receiveDerivationsString);
- // await old.delete("receiveDerivations");
- //
- // // changeDerivations
- // Map newChangeDerivations = {};
- // final changeDerivations =
- // Map.from(await old.get("changeDerivations") ?? {});
- //
- // for (int i = 0; i < changeDerivations.length; i++) {
- // changeDerivations[i].remove("fingerprint");
- // changeDerivations[i].remove("identifier");
- // changeDerivations[i].remove("privateKey");
- // newChangeDerivations["$i"] = changeDerivations[i];
- // }
- // final changeDerivationsString = jsonEncode(newChangeDerivations);
- //
- // await secureStore.write(
- // key: "${walletId}_changeDerivations",
- // value: changeDerivationsString);
- // await old.delete("changeDerivations");
- // }
- //
- // // finally update version
- // await wallets.put("db_version", 1);
- //
- // return;
- // // not needed yet
- // // return migrate(1);
- //
- // // case 1:
- // // return migrate(2);
- //
- // default:
- // return;
- // }
+ switch (fromVersion) {
+ case 0:
+ await Hive.openBox(DB.boxNameAllWalletsData);
+ await Hive.openBox(DB.boxNamePrefs);
+ final walletsService = WalletsService();
+ final nodeService = NodeService();
+ final prefs = Prefs.instance;
+ final walletInfoList = await walletsService.walletNames;
+ await prefs.init();
+
+ ElectrumX? client;
+ int? latestSetId;
+
+ // only instantiate client if there are firo wallets
+ if (walletInfoList.values.any((element) => element.coin == Coin.firo)) {
+ await Hive.openBox(DB.boxNameNodeModels);
+ await Hive.openBox(DB.boxNamePrimaryNodes);
+ final node = nodeService.getPrimaryNodeFor(coin: Coin.firo) ??
+ DefaultNodes.firo;
+ List failovers = nodeService
+ .failoverNodesFor(coin: Coin.firo)
+ .map(
+ (e) => ElectrumXNode(
+ address: e.host,
+ port: e.port,
+ name: e.name,
+ id: e.id,
+ useSSL: e.useSSL,
+ ),
+ )
+ .toList();
+
+ client = ElectrumX.from(
+ node: ElectrumXNode(
+ address: node.host,
+ port: node.port,
+ name: node.name,
+ id: node.id,
+ useSSL: node.useSSL),
+ prefs: prefs,
+ failovers: failovers,
+ );
+
+ try {
+ latestSetId = await client.getLatestCoinId();
+ } catch (e) {
+ // default to 2 for now
+ latestSetId = 2;
+ Logging.instance.log(
+ "Failed to fetch latest coin id during firo db migrate: $e \nUsing a default value of 2",
+ level: LogLevel.Warning);
+ }
+ }
+
+ for (final walletInfo in walletInfoList.values) {
+ // migrate each firo wallet's lelantus coins
+ if (walletInfo.coin == Coin.firo) {
+ await Hive.openBox(walletInfo.walletId);
+ final _lelantusCoins = DB.instance.get(
+ boxName: walletInfo.walletId, key: '_lelantus_coins') as List?;
+ final List