Cw 171 exchange auto selector bug (#523)

* Fix de-selecting exchange providers not getting saved

* only change field value when the amount is better than the already existing one

* Show calculated amount after getting the best value from all providers

* Catch exceptions to avoid stopping the providers calculate amount APIs

* Fix Splay map only saving the last value obtained

* Show limits for the provider with the highest rate

* Load limits on currency pair change

* Show limits for lowest min provider

* Show limits for lowest min and highest max

* Sync best rate every 10 seconds instead of calculating it on every amount change

* Fix conflicts with flutter upgrade
Add null safety to changes in exchange_view_model.dart

* Remove un-necessary checks
This commit is contained in:
Omar Hatem 2022-10-20 19:47:36 +02:00 committed by GitHub
parent 6046385236
commit 7e7217008c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 162 additions and 150 deletions

View file

@ -56,7 +56,7 @@ class SimpleSwapExchangeProvider extends ExchangeProvider {
final uri = Uri.https(apiAuthority, getEstimatePath, params); final uri = Uri.https(apiAuthority, getEstimatePath, params);
final response = await get(uri); final response = await get(uri);
if (response.body == null) return 0.00; if (response.body == null || response.body == "null") return 0.00;
final data = json.decode(response.body) as String; final data = json.decode(response.body) as String;
return double.parse(data); return double.parse(data);
@ -151,8 +151,8 @@ class SimpleSwapExchangeProvider extends ExchangeProvider {
} }
final responseJSON = json.decode(response.body) as Map<String, dynamic>; final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final min = responseJSON['min'] != null ? double.tryParse(responseJSON['min'] as String) : null; final min = double.tryParse(responseJSON['min'] as String? ?? '');
final max = responseJSON['max'] != null ? double.parse(responseJSON['max'] as String) : null; final max = double.tryParse(responseJSON['max'] as String? ?? '');
return Limits(min: min, max: max); return Limits(min: min, max: max);
} }

View file

@ -179,6 +179,7 @@ class ExchangePage extends BasePage {
padding: EdgeInsets.fromLTRB(24, 100, 24, 32), padding: EdgeInsets.fromLTRB(24, 100, 24, 32),
child: Observer( child: Observer(
builder: (_) => ExchangeCard( builder: (_) => ExchangeCard(
onDispose: disposeBestRateSync,
hasAllAmount: exchangeViewModel.hasAllAmount, hasAllAmount: exchangeViewModel.hasAllAmount,
allAmount: exchangeViewModel.hasAllAmount allAmount: exchangeViewModel.hasAllAmount
? () => exchangeViewModel ? () => exchangeViewModel
@ -265,6 +266,7 @@ class ExchangePage extends BasePage {
EdgeInsets.only(top: 29, left: 24, right: 24), EdgeInsets.only(top: 29, left: 24, right: 24),
child: Observer( child: Observer(
builder: (_) => ExchangeCard( builder: (_) => ExchangeCard(
onDispose: disposeBestRateSync,
amountFocusNode: _receiveAmountFocus, amountFocusNode: _receiveAmountFocus,
addressFocusNode: _receiveAddressFocus, addressFocusNode: _receiveAddressFocus,
key: receiveKey, key: receiveKey,
@ -743,13 +745,13 @@ class ExchangePage extends BasePage {
if (_receiveAmountFocus.hasFocus) { if (_receiveAmountFocus.hasFocus) {
exchangeViewModel.isFixedRateMode = true; exchangeViewModel.isFixedRateMode = true;
} }
exchangeViewModel.changeReceiveAmount(amount: receiveAmountController.text); // exchangeViewModel.changeReceiveAmount(amount: receiveAmountController.text);
}); });
_depositAmountFocus.addListener(() { _depositAmountFocus.addListener(() {
exchangeViewModel.isFixedRateMode = false; exchangeViewModel.isFixedRateMode = false;
exchangeViewModel.changeDepositAmount( // exchangeViewModel.changeDepositAmount(
amount: depositAmountController.text); // amount: depositAmountController.text);
}); });
_isReactionsSet = true; _isReactionsSet = true;
@ -791,4 +793,6 @@ class ExchangePage extends BasePage {
final address = await extractAddressFromParsed(context, parsedAddress); final address = await extractAddressFromParsed(context, parsedAddress);
return address; return address;
} }
void disposeBestRateSync() => exchangeViewModel.bestRateSync?.cancel();
} }

View file

@ -37,7 +37,8 @@ class ExchangeCard extends StatefulWidget {
this.addressFocusNode, this.addressFocusNode,
this.allAmount, this.allAmount,
this.onPushPasteButton, this.onPushPasteButton,
this.onPushAddressBookButton}) this.onPushAddressBookButton,
this.onDispose})
: super(key: key); : super(key: key);
final List<CryptoCurrency> currencies; final List<CryptoCurrency> currencies;
@ -63,6 +64,7 @@ class ExchangeCard extends StatefulWidget {
final VoidCallback? allAmount; final VoidCallback? allAmount;
final void Function(BuildContext context)? onPushPasteButton; final void Function(BuildContext context)? onPushPasteButton;
final void Function(BuildContext context)? onPushAddressBookButton; final void Function(BuildContext context)? onPushAddressBookButton;
final Function()? onDispose;
@override @override
ExchangeCardState createState() => ExchangeCardState(); ExchangeCardState createState() => ExchangeCardState();
@ -106,6 +108,13 @@ class ExchangeCardState extends State<ExchangeCard> {
super.initState(); super.initState();
} }
@override
void dispose() {
widget.onDispose?.call();
super.dispose();
}
void changeLimits({String? min, String? max}) { void changeLimits({String? min, String? max}) {
setState(() { setState(() {
_min = min; _min = min;

View file

@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:collection'; import 'dart:collection';
import 'dart:convert'; import 'dart:convert';
@ -59,12 +60,12 @@ abstract class ExchangeViewModelBase with Store {
receiveCurrency = wallet.currency, receiveCurrency = wallet.currency,
depositCurrency = wallet.currency, depositCurrency = wallet.currency,
providerList = [ChangeNowExchangeProvider(), SideShiftExchangeProvider(), SimpleSwapExchangeProvider()], providerList = [ChangeNowExchangeProvider(), SideShiftExchangeProvider(), SimpleSwapExchangeProvider()],
selectedProviders = ObservableList<ExchangeProvider>(), selectedProviders = ObservableList<ExchangeProvider>() {
currentTradeAvailableProviders = SplayTreeMap<double, ExchangeProvider>() {
const excludeDepositCurrencies = [CryptoCurrency.btt, CryptoCurrency.nano]; const excludeDepositCurrencies = [CryptoCurrency.btt, CryptoCurrency.nano];
const excludeReceiveCurrencies = [CryptoCurrency.xlm, CryptoCurrency.xrp, const excludeReceiveCurrencies = [CryptoCurrency.xlm, CryptoCurrency.xrp,
CryptoCurrency.bnb, CryptoCurrency.btt, CryptoCurrency.nano]; CryptoCurrency.bnb, CryptoCurrency.btt, CryptoCurrency.nano];
_initialPairBasedOnWallet(); _initialPairBasedOnWallet();
final Map<String, dynamic> exchangeProvidersSelection = json final Map<String, dynamic> exchangeProvidersSelection = json
.decode(sharedPreferences.getString(PreferencesKey.exchangeProvidersSelection) ?? "{}") as Map<String, dynamic>; .decode(sharedPreferences.getString(PreferencesKey.exchangeProvidersSelection) ?? "{}") as Map<String, dynamic>;
@ -76,6 +77,11 @@ abstract class ExchangeViewModelBase with Store {
: (exchangeProvidersSelection[element.title] as bool)) : (exchangeProvidersSelection[element.title] as bool))
.toList()); .toList());
_setAvailableProviders();
_calculateBestRate();
bestRateSync = Timer.periodic(Duration(seconds: 10), (timer) => _calculateBestRate());
isDepositAddressEnabled = !(depositCurrency == wallet.currency); isDepositAddressEnabled = !(depositCurrency == wallet.currency);
isReceiveAddressEnabled = !(receiveCurrency == wallet.currency); isReceiveAddressEnabled = !(receiveCurrency == wallet.currency);
depositAmount = ''; depositAmount = '';
@ -119,8 +125,15 @@ abstract class ExchangeViewModelBase with Store {
/// Maps in dart are not sorted by default /// Maps in dart are not sorted by default
/// SplayTreeMap is a map sorted by keys /// SplayTreeMap is a map sorted by keys
/// will use it to sort available providers /// will use it to sort available providers
/// depending on the amount they yield for the current trade /// based on the rate they yield for the current trade
SplayTreeMap<double, ExchangeProvider> currentTradeAvailableProviders; ///
///
/// initialize with descending comparator
/// since we want largest rate first
final SplayTreeMap<double, ExchangeProvider> _sortedAvailableProviders =
SplayTreeMap<double, ExchangeProvider>((double a, double b) => b.compareTo(a));
final List<ExchangeProvider> _tradeAvailableProviders = [];
@observable @observable
ObservableList<ExchangeProvider> selectedProviders; ObservableList<ExchangeProvider> selectedProviders;
@ -191,6 +204,10 @@ abstract class ExchangeViewModelBase with Store {
final SettingsStore _settingsStore; final SettingsStore _settingsStore;
double _bestRate = 0.0;
late Timer bestRateSync;
@action @action
void changeDepositCurrency({required CryptoCurrency currency}) { void changeDepositCurrency({required CryptoCurrency currency}) {
depositCurrency = currency; depositCurrency = currency;
@ -210,68 +227,11 @@ abstract class ExchangeViewModelBase with Store {
} }
@action @action
void changeReceiveAmount({required String amount}) { Future<void> changeReceiveAmount({required String amount}) async {
receiveAmount = amount; receiveAmount = amount;
isReverse = true; isReverse = true;
if (amount == null || amount.isEmpty) { if (amount.isEmpty) {
depositAmount = '';
receiveAmount = '';
return;
}
final _enteredAmount = double.parse(amount.replaceAll(',', '.')) ?? 0;
currentTradeAvailableProviders.clear();
for (var provider in selectedProviders) {
/// if this provider is not valid for the current pair, skip it
if (!providersForCurrentPair().contains(provider)) {
continue;
}
provider
.calculateAmount(
from: receiveCurrency,
to: depositCurrency,
amount: _enteredAmount,
isFixedRateMode: isFixedRateMode,
isReceiveAmount: true)
.then((amount) {
final from = isFixedRateMode
? receiveCurrency
: depositCurrency;
final to = isFixedRateMode
? depositCurrency
: receiveCurrency;
provider.fetchLimits(
from: from,
to: to,
isFixedRateMode: isFixedRateMode,
).then((limits) {
/// if the entered amount doesn't exceed the limits of this provider
if ((limits?.max ?? double.maxFinite) >= _enteredAmount
&& (limits?.min ?? 0) <= _enteredAmount) {
/// add this provider as its valid for this trade
/// will be sorted ascending already since
/// we seek the least deposit amount
currentTradeAvailableProviders[amount] = provider;
}
return amount;
}).then((amount) => depositAmount = _cryptoNumberFormat
.format(amount)
.toString()
.replaceAll(RegExp('\\,'), ''));
});
}
}
@action
void changeDepositAmount({required String amount}) {
depositAmount = amount;
isReverse = false;
if (amount == null || amount.isEmpty) {
depositAmount = ''; depositAmount = '';
receiveAmount = ''; receiveAmount = '';
return; return;
@ -279,93 +239,115 @@ abstract class ExchangeViewModelBase with Store {
final _enteredAmount = double.tryParse(amount.replaceAll(',', '.')) ?? 0; final _enteredAmount = double.tryParse(amount.replaceAll(',', '.')) ?? 0;
currentTradeAvailableProviders.clear(); if (_bestRate == 0) {
for (var provider in selectedProviders) { depositAmount = S.current.fetching;
/// if this provider is not valid for the current pair, skip it
if (!providersForCurrentPair().contains(provider)) { await _calculateBestRate();
continue; }
depositAmount = _cryptoNumberFormat
.format(_enteredAmount / _bestRate)
.toString()
.replaceAll(RegExp('\\,'), '');
}
@action
Future<void> changeDepositAmount({required String amount}) async {
depositAmount = amount;
isReverse = false;
if (amount.isEmpty) {
depositAmount = '';
receiveAmount = '';
return;
}
final _enteredAmount = double.tryParse(amount.replaceAll(',', '.')) ?? 0;
/// in case the best rate was not calculated yet
if (_bestRate == 0) {
receiveAmount = S.current.fetching;
await _calculateBestRate();
}
receiveAmount = _cryptoNumberFormat
.format(_bestRate * _enteredAmount)
.toString()
.replaceAll(RegExp('\\,'), '');
}
Future<void> _calculateBestRate() async {
final result = await Future.wait<double>(
_tradeAvailableProviders
.map((element) => element.calculateAmount(
from: depositCurrency,
to: receiveCurrency,
amount: 1,
isFixedRateMode: isFixedRateMode,
isReceiveAmount: false))
);
_sortedAvailableProviders.clear();
for (int i=0;i<result.length;i++) {
if (result[i] != 0) {
/// add this provider as its valid for this trade
_sortedAvailableProviders[result[i]] = _tradeAvailableProviders[i];
} }
provider }
.calculateAmount( if (_sortedAvailableProviders.isNotEmpty) {
from: depositCurrency, _bestRate = _sortedAvailableProviders.keys.first;
to: receiveCurrency,
amount: _enteredAmount,
isFixedRateMode: isFixedRateMode,
isReceiveAmount: false)
.then((amount) {
final from = isFixedRateMode
? receiveCurrency
: depositCurrency;
final to = isFixedRateMode
? depositCurrency
: receiveCurrency;
provider.fetchLimits(
from: from,
to: to,
isFixedRateMode: isFixedRateMode,
).then((limits) {
/// if the entered amount doesn't exceed the limits of this provider
if ((limits?.max ?? double.maxFinite) >= _enteredAmount
&& (limits?.min ?? 0) <= _enteredAmount) {
/// add this provider as its valid for this trade
/// subtract from maxFinite so the provider
/// with the largest amount would be sorted ascending
currentTradeAvailableProviders[double.maxFinite - amount] = provider;
}
return amount;
}).then((amount) => receiveAmount =
receiveAmount = _cryptoNumberFormat
.format(amount)
.toString()
.replaceAll(RegExp('\\,'), ''));
});
} }
} }
@action @action
Future loadLimits() async { Future<void> loadLimits() async {
if (selectedProviders.isEmpty) { if (selectedProviders.isEmpty) {
return; return;
} }
limitsState = LimitsIsLoading(); limitsState = LimitsIsLoading();
try { final from = isFixedRateMode
final from = isFixedRateMode
? receiveCurrency ? receiveCurrency
: depositCurrency; : depositCurrency;
final to = isFixedRateMode final to = isFixedRateMode
? depositCurrency ? depositCurrency
: receiveCurrency; : receiveCurrency;
limits = await selectedProviders.first.fetchLimits( double lowestMin = double.maxFinite;
from: from, double? highestMax = 0.0;
to: to,
isFixedRateMode: isFixedRateMode);
/// if the first provider limits is bounded then check with other providers for (var provider in selectedProviders) {
/// for the highest maximum limit /// if this provider is not valid for the current pair, skip it
if (limits.max != null) { if (!providersForCurrentPair().contains(provider)) {
for (int i = 1;i < selectedProviders.length;i++) { continue;
final Limits tempLimits = await selectedProviders[i].fetchLimits(
from: from,
to: to,
isFixedRateMode: isFixedRateMode);
/// set the limits with the maximum provider limit
/// if there is a provider with null max then it's the maximum limit
if ((tempLimits.max ?? double.maxFinite) > limits.max!) {
limits = tempLimits;
}
}
} }
try {
final tempLimits = await provider.fetchLimits(
from: from,
to: to,
isFixedRateMode: isFixedRateMode);
if (tempLimits.min != null && tempLimits.min! < lowestMin) {
lowestMin = tempLimits.min!;
}
if (highestMax != null && (tempLimits.max ?? double.maxFinite) > highestMax) {
highestMax = tempLimits.max;
}
} catch (e) {
continue;
}
}
if (lowestMin < double.maxFinite) {
limits = Limits(min: lowestMin, max: highestMax);
limitsState = LimitsLoadedSuccessfully(limits: limits); limitsState = LimitsLoadedSuccessfully(limits: limits);
} catch (e) { } else {
limitsState = LimitsLoadedFailure(error: e.toString()); limitsState = LimitsLoadedFailure(error: 'Limits loading failed');
} }
} }
@ -374,7 +356,7 @@ abstract class ExchangeViewModelBase with Store {
TradeRequest? request; TradeRequest? request;
String amount = ''; String amount = '';
for (var provider in currentTradeAvailableProviders.values) { for (var provider in _sortedAvailableProviders.values) {
if (!(await provider.checkIsAvailable())) { if (!(await provider.checkIsAvailable())) {
continue; continue;
} }
@ -383,7 +365,7 @@ abstract class ExchangeViewModelBase with Store {
request = SideShiftRequest( request = SideShiftRequest(
depositMethod: depositCurrency, depositMethod: depositCurrency,
settleMethod: receiveCurrency, settleMethod: receiveCurrency,
depositAmount: depositAmount?.replaceAll(',', '.') ?? '', depositAmount: depositAmount.replaceAll(',', '.'),
settleAddress: receiveAddress, settleAddress: receiveAddress,
refundAddress: depositAddress, refundAddress: depositAddress,
); );
@ -394,7 +376,7 @@ abstract class ExchangeViewModelBase with Store {
request = SimpleSwapRequest( request = SimpleSwapRequest(
from: depositCurrency, from: depositCurrency,
to: receiveCurrency, to: receiveCurrency,
amount: depositAmount?.replaceAll(',', '.') ?? '', amount: depositAmount.replaceAll(',', '.'),
address: receiveAddress, address: receiveAddress,
refundAddress: depositAddress, refundAddress: depositAddress,
); );
@ -405,8 +387,8 @@ abstract class ExchangeViewModelBase with Store {
request = XMRTOTradeRequest( request = XMRTOTradeRequest(
from: depositCurrency, from: depositCurrency,
to: receiveCurrency, to: receiveCurrency,
amount: depositAmount?.replaceAll(',', '.') ?? '', amount: depositAmount.replaceAll(',', '.'),
receiveAmount: receiveAmount?.replaceAll(',', '.') ?? '', receiveAmount: receiveAmount.replaceAll(',', '.'),
address: receiveAddress, address: receiveAddress,
refundAddress: depositAddress, refundAddress: depositAddress,
isBTCRequest: isReceiveAmountEntered); isBTCRequest: isReceiveAmountEntered);
@ -417,8 +399,8 @@ abstract class ExchangeViewModelBase with Store {
request = ChangeNowRequest( request = ChangeNowRequest(
from: depositCurrency, from: depositCurrency,
to: receiveCurrency, to: receiveCurrency,
fromAmount: depositAmount?.replaceAll(',', '.') ?? '', fromAmount: depositAmount.replaceAll(',', '.'),
toAmount: receiveAmount?.replaceAll(',', '.') ?? '', toAmount: receiveAmount.replaceAll(',', '.'),
refundAddress: depositAddress, refundAddress: depositAddress,
address: receiveAddress, address: receiveAddress,
isReverse: isReverse); isReverse: isReverse);
@ -429,7 +411,7 @@ abstract class ExchangeViewModelBase with Store {
request = MorphTokenRequest( request = MorphTokenRequest(
from: depositCurrency, from: depositCurrency,
to: receiveCurrency, to: receiveCurrency,
amount: depositAmount?.replaceAll(',', '.') ?? '', amount: depositAmount.replaceAll(',', '.'),
refundAddress: depositAddress, refundAddress: depositAddress,
address: receiveAddress); address: receiveAddress);
amount = depositAmount; amount = depositAmount;
@ -437,7 +419,7 @@ abstract class ExchangeViewModelBase with Store {
amount = amount.replaceAll(',', '.'); amount = amount.replaceAll(',', '.');
if (limitsState is LimitsLoadedSuccessfully && amount != null) { if (limitsState is LimitsLoadedSuccessfully) {
if (double.parse(amount) < limits.min!) { if (double.parse(amount) < limits.min!) {
continue; continue;
} else if (limits.max != null && double.parse(amount) > limits.max!) { } else if (limits.max != null && double.parse(amount) > limits.max!) {
@ -527,7 +509,7 @@ abstract class ExchangeViewModelBase with Store {
final providers = providerList final providers = providerList
.where((provider) => provider.pairList .where((provider) => provider.pairList
.where((pair) => .where((pair) =>
pair.from == (from ?? depositCurrency) && pair.to == (to ?? receiveCurrency)) pair.from == from && pair.to == to)
.isNotEmpty) .isNotEmpty)
.toList(); .toList();
@ -537,6 +519,10 @@ abstract class ExchangeViewModelBase with Store {
void _onPairChange() { void _onPairChange() {
depositAmount = ''; depositAmount = '';
receiveAmount = ''; receiveAmount = '';
loadLimits();
_setAvailableProviders();
_bestRate = 0;
_calculateBestRate();
} }
void _initialPairBasedOnWallet() { void _initialPairBasedOnWallet() {
@ -579,11 +565,15 @@ abstract class ExchangeViewModelBase with Store {
@action @action
void addExchangeProvider(ExchangeProvider provider) { void addExchangeProvider(ExchangeProvider provider) {
selectedProviders.add(provider); selectedProviders.add(provider);
if (providersForCurrentPair().contains(provider)) {
_tradeAvailableProviders.add(provider);
}
} }
@action @action
void removeExchangeProvider(ExchangeProvider provider) { void removeExchangeProvider(ExchangeProvider provider) {
selectedProviders.remove(provider); selectedProviders.remove(provider);
_tradeAvailableProviders.remove(provider);
} }
@action @action
@ -593,13 +583,14 @@ abstract class ExchangeViewModelBase with Store {
isFixedRateMode = false; isFixedRateMode = false;
_defineIsReceiveAmountEditable(); _defineIsReceiveAmountEditable();
loadLimits(); loadLimits();
_bestRate = 0;
_calculateBestRate();
final Map<String, dynamic> exchangeProvidersSelection = json final Map<String, dynamic> exchangeProvidersSelection = json
.decode(sharedPreferences.getString(PreferencesKey.exchangeProvidersSelection) ?? "{}") as Map<String, dynamic>; .decode(sharedPreferences.getString(PreferencesKey.exchangeProvidersSelection) ?? "{}") as Map<String, dynamic>;
exchangeProvidersSelection.updateAll((key, dynamic value) => false); for (var provider in providerList) {
for (var provider in selectedProviders) { exchangeProvidersSelection[provider.title] = selectedProviders.contains(provider);
exchangeProvidersSelection[provider.title] = true;
} }
sharedPreferences.setString( sharedPreferences.setString(
@ -612,4 +603,12 @@ abstract class ExchangeViewModelBase with Store {
final providersForPair = providersForCurrentPair(); final providersForPair = providersForCurrentPair();
return selectedProviders.any((element) => element.isAvailable && providersForPair.contains(element)); return selectedProviders.any((element) => element.isAvailable && providersForPair.contains(element));
} }
void _setAvailableProviders() {
_tradeAvailableProviders.clear();
_tradeAvailableProviders.addAll(
selectedProviders
.where((provider) => providersForCurrentPair().contains(provider)));
}
} }