From 9afed201c6f65f21ca52bd69a4e6130220627642 Mon Sep 17 00:00:00 2001 From: Serhii Date: Sat, 8 Jul 2023 05:30:05 +0300 Subject: [PATCH] CW-424-ChangeNOW-add-payload-details (#979) * add payload details * remove unused import * fix payload --- .../changenow_exchange_provider.dart | 93 ++++++++++--------- lib/utils/distribution_info.dart | 39 ++++++++ .../exchange/exchange_trade_view_model.dart | 3 +- .../exchange/exchange_view_model.dart | 2 +- lib/view_model/trade_details_view_model.dart | 2 +- 5 files changed, 94 insertions(+), 45 deletions(-) create mode 100644 lib/utils/distribution_info.dart diff --git a/lib/exchange/changenow/changenow_exchange_provider.dart b/lib/exchange/changenow/changenow_exchange_provider.dart index b37a513ac..ecfe888e7 100644 --- a/lib/exchange/changenow/changenow_exchange_provider.dart +++ b/lib/exchange/changenow/changenow_exchange_provider.dart @@ -1,6 +1,10 @@ import 'dart:convert'; +import 'dart:io'; import 'package:cake_wallet/exchange/trade_not_found_exeption.dart'; +import 'package:cake_wallet/store/settings_store.dart'; import 'package:cake_wallet/utils/device_info.dart'; +import 'package:cake_wallet/utils/distribution_info.dart'; +import 'package:cake_wallet/wallet_type_utils.dart'; import 'package:http/http.dart'; import 'package:cake_wallet/.secrets.g.dart' as secrets; import 'package:cw_core/crypto_currency.dart'; @@ -14,7 +18,7 @@ import 'package:cake_wallet/exchange/changenow/changenow_request.dart'; import 'package:cake_wallet/exchange/exchange_provider_description.dart'; class ChangeNowExchangeProvider extends ExchangeProvider { - ChangeNowExchangeProvider() + ChangeNowExchangeProvider({required this.settingsStore}) : _lastUsedRateId = '', super( pairList: CryptoCurrency.all @@ -25,7 +29,8 @@ class ChangeNowExchangeProvider extends ExchangeProvider { .expand((i) => i) .toList()); - static final apiKey = DeviceInfo.instance.isMobile ? secrets.changeNowApiKey : secrets.changeNowApiKeyDesktop; + static final apiKey = + DeviceInfo.instance.isMobile ? secrets.changeNowApiKey : secrets.changeNowApiKeyDesktop; static const apiAuthority = 'api.changenow.io'; static const createTradePath = '/v2/exchange'; static const findTradeByIdPath = '/v2/exchange/by-id'; @@ -46,21 +51,22 @@ class ChangeNowExchangeProvider extends ExchangeProvider { bool get supportsFixedRate => true; @override - ExchangeProviderDescription get description => - ExchangeProviderDescription.changeNow; + ExchangeProviderDescription get description => ExchangeProviderDescription.changeNow; @override Future checkIsAvailable() async => true; + final SettingsStore settingsStore; + String _lastUsedRateId; static String getFlow(bool isFixedRate) => isFixedRate ? 'fixed-rate' : 'standard'; @override - Future fetchLimits({ - required CryptoCurrency from, - required CryptoCurrency to, - required bool isFixedRateMode}) async { + Future fetchLimits( + {required CryptoCurrency from, + required CryptoCurrency to, + required bool isFixedRateMode}) async { final headers = {apiHeaderKey: apiKey}; final normalizedFrom = normalizeCryptoCurrency(from); final normalizedTo = normalizeCryptoCurrency(to); @@ -70,10 +76,11 @@ class ChangeNowExchangeProvider extends ExchangeProvider { 'toCurrency': normalizedTo, 'fromNetwork': networkFor(from), 'toNetwork': networkFor(to), - 'flow': flow}; + 'flow': flow + }; final uri = Uri.https(apiAuthority, rangePath, params); final response = await get(uri, headers: headers); - + if (response.statusCode == 400) { final responseJSON = json.decode(response.body) as Map; final error = responseJSON['error'] as String; @@ -87,19 +94,24 @@ class ChangeNowExchangeProvider extends ExchangeProvider { final responseJSON = json.decode(response.body) as Map; return Limits( - min: responseJSON['minAmount'] as double?, - max: responseJSON['maxAmount'] as double?); + min: responseJSON['minAmount'] as double?, max: responseJSON['maxAmount'] as double?); } @override Future createTrade({required TradeRequest request, required bool isFixedRateMode}) async { final _request = request as ChangeNowRequest; - final headers = { - apiHeaderKey: apiKey, - 'Content-Type': 'application/json'}; + final distributionPath = await DistributionInfo.instance.getDistributionPath(); + final formattedAppVersion = int.tryParse(settingsStore.appVersion.replaceAll('.', '')) ?? 0; + final payload = { + 'app': isMoneroOnly ? 'monerocom' : 'cakewallet', + 'device': Platform.operatingSystem, + 'distribution': distributionPath, + 'version': formattedAppVersion + }; + final headers = {apiHeaderKey: apiKey, 'Content-Type': 'application/json'}; final flow = getFlow(isFixedRateMode); final type = isFixedRateMode ? 'reverse' : 'direct'; - final body = { + final body = { 'fromCurrency': normalizeCryptoCurrency(_request.from), 'toCurrency': normalizeCryptoCurrency(_request.to), 'fromNetwork': networkFor(_request.from), @@ -109,7 +121,8 @@ class ChangeNowExchangeProvider extends ExchangeProvider { 'address': _request.address, 'flow': flow, 'type': type, - 'refundAddress': _request.refundAddress + 'refundAddress': _request.refundAddress, + 'payload': payload, }; if (isFixedRateMode) { @@ -164,7 +177,7 @@ class ChangeNowExchangeProvider extends ExchangeProvider { Future findTradeById({required String id}) async { final headers = {apiHeaderKey: apiKey}; final params = {'id': id}; - final uri = Uri.https(apiAuthority,findTradeByIdPath, params); + final uri = Uri.https(apiAuthority, findTradeByIdPath, params); final response = await get(uri, headers: headers); if (response.statusCode == 404) { @@ -175,8 +188,7 @@ class ChangeNowExchangeProvider extends ExchangeProvider { final responseJSON = json.decode(response.body) as Map; final error = responseJSON['message'] as String; - throw TradeNotFoundException(id, - provider: description, description: error); + throw TradeNotFoundException(id, provider: description, description: error); } if (response.statusCode != 200) { @@ -234,19 +246,20 @@ class ChangeNowExchangeProvider extends ExchangeProvider { 'fromNetwork': networkFor(from), 'toNetwork': networkFor(to), 'type': type, - 'flow': flow}; + 'flow': flow + }; if (isReverse) { params['toAmount'] = amount.toString(); } else { params['fromAmount'] = amount.toString(); } - + final uri = Uri.https(apiAuthority, estimatedAmountPath, params); final response = await get(uri, headers: headers); final responseJSON = json.decode(response.body) as Map; final fromAmount = double.parse(responseJSON['fromAmount'].toString()); - final toAmount = double.parse(responseJSON['toAmount'].toString()); + final toAmount = double.parse(responseJSON['toAmount'].toString()); final rateId = responseJSON['rateId'] as String? ?? ''; if (rateId.isNotEmpty) { @@ -254,35 +267,31 @@ class ChangeNowExchangeProvider extends ExchangeProvider { } return isReverse ? (amount / fromAmount) : (toAmount / amount); - } catch(e) { + } catch (e) { print(e.toString()); return 0.0; } } - + String networkFor(CryptoCurrency currency) { switch (currency) { case CryptoCurrency.usdt: return CryptoCurrency.btc.title.toLowerCase(); default: - return currency.tag != null - ? currency.tag!.toLowerCase() - : currency.title.toLowerCase(); - } + return currency.tag != null ? currency.tag!.toLowerCase() : currency.title.toLowerCase(); } - } +} - String normalizeCryptoCurrency(CryptoCurrency currency) { - switch(currency) { - case CryptoCurrency.zec: - return 'zec'; - case CryptoCurrency.usdcpoly: - return 'usdcmatic'; - case CryptoCurrency.maticpoly: - return 'maticmainnet'; - default: - return currency.title.toLowerCase(); - } - +String normalizeCryptoCurrency(CryptoCurrency currency) { + switch (currency) { + case CryptoCurrency.zec: + return 'zec'; + case CryptoCurrency.usdcpoly: + return 'usdcmatic'; + case CryptoCurrency.maticpoly: + return 'maticmainnet'; + default: + return currency.title.toLowerCase(); } +} diff --git a/lib/utils/distribution_info.dart b/lib/utils/distribution_info.dart new file mode 100644 index 000000000..859c507a3 --- /dev/null +++ b/lib/utils/distribution_info.dart @@ -0,0 +1,39 @@ +import 'dart:io'; +import 'package:package_info/package_info.dart'; + +enum DistributionType { googleplay, github, appstore, fdroid } + +class DistributionInfo { + DistributionInfo._(); + + static DistributionInfo get instance => DistributionInfo._(); + + Future getDistributionPath() async { + final isPlayStore = await isInstalledFromPlayStore(); + final distributionPath = _getDistributionPath(isPlayStore); + + return distributionPath.name; + } + + DistributionType _getDistributionPath(bool isPlayStore) { + if (isPlayStore) { + return DistributionType.googleplay; + } else if (Platform.isAndroid) { + return DistributionType.github; + } else if (Platform.isIOS) { + return DistributionType.appstore; + } else { + return DistributionType.github; + } + } + + Future isInstalledFromPlayStore() async { + try { + final packageInfo = await PackageInfo.fromPlatform(); + return packageInfo.packageName == 'com.android.vending'; + } catch (e) { + print('Error: $e'); + return false; + } + } +} diff --git a/lib/view_model/exchange/exchange_trade_view_model.dart b/lib/view_model/exchange/exchange_trade_view_model.dart index d5aeaa4fc..bfc7f9588 100644 --- a/lib/view_model/exchange/exchange_trade_view_model.dart +++ b/lib/view_model/exchange/exchange_trade_view_model.dart @@ -36,7 +36,8 @@ abstract class ExchangeTradeViewModelBase with Store { _provider = XMRTOExchangeProvider(); break; case ExchangeProviderDescription.changeNow: - _provider = ChangeNowExchangeProvider(); + _provider = + ChangeNowExchangeProvider(settingsStore: sendViewModel.balanceViewModel.settingsStore); break; case ExchangeProviderDescription.morphToken: _provider = MorphTokenExchangeProvider(trades: trades); diff --git a/lib/view_model/exchange/exchange_view_model.dart b/lib/view_model/exchange/exchange_view_model.dart index f823001a4..2b848a5ae 100644 --- a/lib/view_model/exchange/exchange_view_model.dart +++ b/lib/view_model/exchange/exchange_view_model.dart @@ -130,7 +130,7 @@ abstract class ExchangeViewModelBase with Store { final SharedPreferences sharedPreferences; List get _allProviders => [ - ChangeNowExchangeProvider(), + ChangeNowExchangeProvider(settingsStore: _settingsStore), SideShiftExchangeProvider(), SimpleSwapExchangeProvider(), TrocadorExchangeProvider(useTorOnly: _useTorOnly), diff --git a/lib/view_model/trade_details_view_model.dart b/lib/view_model/trade_details_view_model.dart index 1e8a90c6f..c0b1ac461 100644 --- a/lib/view_model/trade_details_view_model.dart +++ b/lib/view_model/trade_details_view_model.dart @@ -40,7 +40,7 @@ abstract class TradeDetailsViewModelBase with Store { _provider = XMRTOExchangeProvider(); break; case ExchangeProviderDescription.changeNow: - _provider = ChangeNowExchangeProvider(); + _provider = ChangeNowExchangeProvider(settingsStore: settingsStore); break; case ExchangeProviderDescription.morphToken: _provider = MorphTokenExchangeProvider(trades: trades);