cake_wallet/lib/exchange/changenow/changenow_exchange_provider.dart

304 lines
11 KiB
Dart
Raw Normal View History

2020-01-04 19:31:52 +00:00
import 'dart:convert';
import 'dart:io';
2020-09-21 11:50:26 +00:00
import 'package:cake_wallet/exchange/trade_not_found_exeption.dart';
import 'package:cake_wallet/store/settings_store.dart';
Dashboard desktop view (#737) * Add build scripts for macOS. Add macos for cw_monero plugin. Add macos proj to the application. * - Update Flutter secure storage to work with macos - Enable uni links only on Mobile - Update devcelocale to work with macos * Add network access to mac * Change Dashboard view on desktop size screens * Add on Tap to desktop_action_button.dart Remove unused functions * Fix arch match for monero lib for darwin x86_64 -> x86-64 * Add Bundle ID in entitlements files through app config script * Update deployment target to 10.13 * Revert back to Cake fork for secure storage * Revert back to Cake fork for secure storage * Revert mac os version * Revert mac os version * Add platform channel specific code for mac os * Add desktop sidebar * [skip ci] Add desktop sidebar * [skip ci] Add desktop sidebar * - Remove legacy migration from macos - Remove wake lock native code and just use the ready made package * Remove wake lock native code and just use the ready made package * Remove unstoppable domain from macos since it's not supported * Temporarily fetch unstoppable domains only on mobile * refactor desktop settings sidebar * Ignore increasing brightness for non-mobile platforms * Add Wallet selection dropdown to dashboard desktop view * Generate MacOS icons * localize settings * fix dashboard sidebar and responsive utils * Change Mac os app name and bundle id * Fix exchange page as fullScreenDialog * Remove constants * - Refactor onRamper to have a single point of modification - Enlarge initial app size - update Flutter and Packages * Add pubspec.lock and Podfile.lock to gitignore * Remove Podfile.lock from cache * Fix bug on sidebar reset * Fix issues from code review * [skip ci] reformat desktop dashboard * [skip ci] reformat desktop dashboard * Revert removing .lock files * Revert changes in .gitignore * [skip ci] remove .project changes * [skip ci] remove .project changes * Separate Dashboard desktop view from mobile view * constraint images and pincoded box * Remove drawer from mac os * - Listen to keyboard events in PIN screen - Fix PIN buttons style * Fix desktop nav bar UI * Add Marketplace to dashboard view * Update trailing icon to open transaction page * Update widget contraints * Add empty trailing to center page title on desktop * Refresh desktop dashboard actions on wallet change * Change ionia welcome page animation * Fix Constrained width screens UI * Refactor sidebar state management * remove empty line * Add max width constrain to Welcome page * Change Exchange page UI depending on platform * - Change design/paddings for Send page on desktop view - Make AddTemplateButton instead of having it duplicated in send/exchange * Fix Desktop dashboard actions background color * Constrain primary Buttons width * Make side menu items toggle back to dashboard * Add padding to support page * Add width constraints to desktop dashboard * Fix UI issues, paddings and alignments * Rename misleading variable Change initial mac window size * Fix wallet create in settings * remove unnecessary code * remove unnecessary code * Remove duplicated constrains * - Use close icon on main screens - Minor UI fixes * fix pageview controller reset index * Add create and restore wallet options to dropdown menu * Fix desktop background color and address book view issues * Fix input field * Add onFieldSubmitted to allow "enter" button interaction * Fix issue from code review * Fix Popup width constraint and add focus orders * Fix variable name * Fix issues from code review * refactor dropdown items * Fix alignment in create and restore wallet screens * Fix dropdown change state bug Hide scanner for desktop * remove space * override navbar with desktopnavbar * Remove autofocus * remove unused code * Fix ionia input field alignment * Replace removed code * Add app lock feature on mac * Add assertion to avoid null * Add Nano currency image * Enable adding contact from send screen * Fix UI issues Add missing translation * pop only PIN screen after successful auth * Add back wallet settings page to desktop settings actions * Fix Navigation animation for settings screens * Fixate MobX version to fix restore issue * CW-324 Refresh current settings page if wallet changed (#811) * Fix refresh current settings page if wallet changed * Fix refresh current settings page if wallet changed * Refresh Wallet Seeds/Keys List upon wallet change --------- Co-authored-by: OmarHatem <omarh.ismail1@gmail.com> * Remove navigation workaround for duplicate key, and fix the issue by handling creation/disposing of global key (#840) * Cw 323 add wallet list to settings on mac (#843) * Remove navigation workaround for duplicate key, and fix the issue by handling creation/disposing of global key * - Register Wallet List as singleton in Desktop to be modify the same instance from settings and dropdown - General Fixes and Enhancements * Fix Changing/Restoring wallet from settings * Fix Create wallet not showing seeds screens if launched from settings * Add max width constraint for Alerts * - Add Desktop API keys - Fix Change back up password issue - Fix Popup width * Sync Mac with latest main updates * Swap Transactions icon with lock icon * Save backup file locally on desktop * Sync with latest main updates * Fix Navigation issues with anonpay * Update macos build version * Remove deprecated custom wake lock code for Android * Remove Legacy CryptoSwift package from MacOS * - Refactor Payfura page code - Add OnRamper new configs to onramper_buy_provider.dart - Fix Conflicts with main * Updated device locale package * Update android tools * Revert changes and update only gradle version * Downgrade android tools version * Update gradle version * Update package/gradle/plugin version * - Fixate device locale version - Downgrade gradle version * Update kotlin version * Update gradle version * Trial for a custom fork from devicelocale * Fixate shared preferences package version * Revert gradle version * Revert kotlin version * Downgrade gradle version * Downgrade gradle version * Repair cache and clean before build * Fixate flutter version * update google services version * revert google services version * Force shared pref android version * Override shared prefs android package version * Override shared prefs android package [skip ci] --------- Co-authored-by: M <m@cakewallet.com> Co-authored-by: Godwin Asuquo <godilite@gmail.com> Co-authored-by: Godwin Asuquo <41484542+godilite@users.noreply.github.com>
2023-04-14 04:39:08 +00:00
import 'package:cake_wallet/utils/device_info.dart';
import 'package:cake_wallet/utils/distribution_info.dart';
import 'package:cake_wallet/wallet_type_utils.dart';
2020-01-04 19:31:52 +00:00
import 'package:http/http.dart';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
2021-12-24 12:37:24 +00:00
import 'package:cw_core/crypto_currency.dart';
2020-09-21 11:50:26 +00:00
import 'package:cake_wallet/exchange/exchange_pair.dart';
import 'package:cake_wallet/exchange/exchange_provider.dart';
import 'package:cake_wallet/exchange/limits.dart';
import 'package:cake_wallet/exchange/trade.dart';
import 'package:cake_wallet/exchange/trade_request.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cake_wallet/exchange/changenow/changenow_request.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
2020-01-04 19:31:52 +00:00
class ChangeNowExchangeProvider extends ExchangeProvider {
ChangeNowExchangeProvider({required this.settingsStore})
2022-01-26 15:44:15 +00:00
: _lastUsedRateId = '',
super(
2020-01-08 12:26:34 +00:00
pairList: CryptoCurrency.all
.where((i) => i != CryptoCurrency.xhv)
2020-11-10 14:58:40 +00:00
.map((i) => CryptoCurrency.all
.where((i) => i != CryptoCurrency.xhv)
.map((k) => ExchangePair(from: i, to: k, reverse: true)))
2020-01-08 12:26:34 +00:00
.expand((i) => i)
.toList());
static final apiKey =
DeviceInfo.instance.isMobile ? secrets.changeNowApiKey : secrets.changeNowApiKeyDesktop;
2022-01-26 15:44:15 +00:00
static const apiAuthority = 'api.changenow.io';
static const createTradePath = '/v2/exchange';
static const findTradeByIdPath = '/v2/exchange/by-id';
static const estimatedAmountPath = '/v2/exchange/estimated-amount';
static const rangePath = '/v2/exchange/range';
static const apiHeaderKey = 'x-changenow-api-key';
2020-01-04 19:31:52 +00:00
2020-01-08 12:26:34 +00:00
@override
2020-01-04 19:31:52 +00:00
String get title => 'ChangeNOW';
2020-01-08 12:26:34 +00:00
2020-11-10 14:58:40 +00:00
@override
bool get isAvailable => true;
@override
bool get isEnabled => true;
@override
bool get supportsFixedRate => true;
2020-01-08 12:26:34 +00:00
@override
ExchangeProviderDescription get description => ExchangeProviderDescription.changeNow;
2020-01-04 19:31:52 +00:00
2020-11-10 14:58:40 +00:00
@override
Future<bool> checkIsAvailable() async => true;
final SettingsStore settingsStore;
2022-01-26 15:44:15 +00:00
String _lastUsedRateId;
static String getFlow(bool isFixedRate) => isFixedRate ? 'fixed-rate' : 'standard';
2020-01-08 12:26:34 +00:00
@override
Future<Limits> fetchLimits(
{required CryptoCurrency from,
required CryptoCurrency to,
required bool isFixedRateMode}) async {
2022-01-26 15:44:15 +00:00
final headers = {apiHeaderKey: apiKey};
final flow = getFlow(isFixedRateMode);
final params = <String, String>{
'fromCurrency': _normalizeCurrency(from),
'toCurrency': _normalizeCurrency(to),
'fromNetwork': _networkFor(from),
'toNetwork': _networkFor(to),
'flow': flow
};
2022-01-26 15:44:15 +00:00
final uri = Uri.https(apiAuthority, rangePath, params);
final response = await get(uri, headers: headers);
2022-01-26 15:44:15 +00:00
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
2022-01-26 15:44:15 +00:00
final error = responseJSON['error'] as String;
final message = responseJSON['message'] as String;
throw Exception('${error}\n$message');
}
2022-01-26 15:44:15 +00:00
if (response.statusCode != 200) {
2022-10-12 17:09:57 +00:00
throw Exception('Unexpected http status: ${response.statusCode}');
}
2022-01-26 15:44:15 +00:00
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
return Limits(
min: responseJSON['minAmount'] as double?, max: responseJSON['maxAmount'] as double?);
2020-01-04 19:31:52 +00:00
}
2020-01-08 12:26:34 +00:00
@override
2022-10-12 17:09:57 +00:00
Future<Trade> createTrade({required TradeRequest request, required bool isFixedRateMode}) async {
2020-01-04 19:31:52 +00:00
final _request = request as ChangeNowRequest;
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'};
2022-01-26 15:44:15 +00:00
final flow = getFlow(isFixedRateMode);
final type = isFixedRateMode ? 'reverse' : 'direct';
final body = <String, dynamic>{
'fromCurrency': _normalizeCurrency(_request.from),
'toCurrency': _normalizeCurrency(_request.to),
'fromNetwork': _networkFor(_request.from),
'toNetwork': _networkFor(_request.to),
if (!isFixedRateMode) 'fromAmount': _request.fromAmount,
if (isFixedRateMode) 'toAmount': _request.toAmount,
2020-01-04 19:31:52 +00:00
'address': _request.address,
2022-01-26 15:44:15 +00:00
'flow': flow,
'type': type,
'refundAddress': _request.refundAddress,
'payload': payload,
2020-01-04 19:31:52 +00:00
};
2022-01-26 15:44:15 +00:00
if (isFixedRateMode) {
// since we schedule to calculate the rate every 5 seconds we need to ensure that
// we have the latest rate id with the given inputs before creating the trade
await fetchRate(
from: _request.from,
to: _request.to,
amount: double.tryParse(_request.toAmount) ?? 0,
isFixedRateMode: true,
isReceiveAmount: true,
);
2022-01-26 15:44:15 +00:00
body['rateId'] = _lastUsedRateId;
}
2020-01-08 12:26:34 +00:00
2022-01-26 15:44:15 +00:00
final uri = Uri.https(apiAuthority, createTradePath);
final response = await post(uri, headers: headers, body: json.encode(body));
2022-01-26 15:44:15 +00:00
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['error'] as String;
final message = responseJSON['message'] as String;
throw Exception('${error}\n$message');
}
2020-01-04 19:31:52 +00:00
2022-01-26 15:44:15 +00:00
if (response.statusCode != 200) {
2022-10-12 17:09:57 +00:00
throw Exception('Unexpected http status: ${response.statusCode}');
2020-01-04 19:31:52 +00:00
}
2020-01-08 12:26:34 +00:00
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final id = responseJSON['id'] as String;
final inputAddress = responseJSON['payinAddress'] as String;
final refundAddress = responseJSON['refundAddress'] as String;
final extraId = responseJSON['payinExtraId'] as String?;
final payoutAddress = responseJSON['payoutAddress'] as String;
2020-01-04 19:31:52 +00:00
return Trade(
2020-01-08 12:26:34 +00:00
id: id,
2020-01-04 19:31:52 +00:00
from: _request.from,
to: _request.to,
provider: description,
2020-01-08 12:26:34 +00:00
inputAddress: inputAddress,
refundAddress: refundAddress,
extraId: extraId,
2020-01-04 19:31:52 +00:00
createdAt: DateTime.now(),
amount: responseJSON['fromAmount']?.toString() ?? _request.fromAmount,
state: TradeState.created,
payoutAddress: payoutAddress);
2020-01-04 19:31:52 +00:00
}
2020-01-08 12:26:34 +00:00
@override
2022-10-12 17:09:57 +00:00
Future<Trade> findTradeById({required String id}) async {
2022-01-26 15:44:15 +00:00
final headers = {apiHeaderKey: apiKey};
final params = <String, String>{'id': id};
final uri = Uri.https(apiAuthority, findTradeByIdPath, params);
2022-01-26 15:44:15 +00:00
final response = await get(uri, headers: headers);
2020-01-04 19:31:52 +00:00
2022-01-26 15:44:15 +00:00
if (response.statusCode == 404) {
throw TradeNotFoundException(id, provider: description);
}
2020-01-08 12:26:34 +00:00
2022-01-26 15:44:15 +00:00
if (response.statusCode == 400) {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final error = responseJSON['message'] as String;
2020-01-04 19:31:52 +00:00
throw TradeNotFoundException(id, provider: description, description: error);
2022-01-26 15:44:15 +00:00
}
if (response.statusCode != 200) {
2022-10-12 17:09:57 +00:00
throw Exception('Unexpected http status: ${response.statusCode}');
2020-01-04 19:31:52 +00:00
}
2020-01-08 12:26:34 +00:00
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final fromCurrency = responseJSON['fromCurrency'] as String;
final from = CryptoCurrency.fromString(fromCurrency);
final toCurrency = responseJSON['toCurrency'] as String;
final to = CryptoCurrency.fromString(toCurrency);
final inputAddress = responseJSON['payinAddress'] as String;
2022-01-26 15:44:15 +00:00
final expectedSendAmount = responseJSON['expectedAmountFrom'].toString();
2020-01-08 12:26:34 +00:00
final status = responseJSON['status'] as String;
final state = TradeState.deserialize(raw: status);
final extraId = responseJSON['payinExtraId'] as String?;
final outputTransaction = responseJSON['payoutHash'] as String?;
final expiredAtRaw = responseJSON['validUntil'] as String?;
final payoutAddress = responseJSON['payoutAddress'] as String;
final expiredAt = DateTime.tryParse(expiredAtRaw ?? '')?.toLocal();
return Trade(
id: id,
from: from,
to: to,
provider: description,
inputAddress: inputAddress,
amount: expectedSendAmount,
state: state,
extraId: extraId,
expiredAt: expiredAt,
outputTransaction: outputTransaction,
payoutAddress: payoutAddress);
2020-01-04 19:31:52 +00:00
}
2020-01-08 12:26:34 +00:00
@override
Future<double> fetchRate(
2022-10-12 17:09:57 +00:00
{required CryptoCurrency from,
required CryptoCurrency to,
required double amount,
required bool isFixedRateMode,
required bool isReceiveAmount}) async {
2022-01-26 15:44:15 +00:00
try {
if (amount == 0) {
return 0.0;
}
2022-01-26 15:44:15 +00:00
final headers = {apiHeaderKey: apiKey};
final isReverse = isReceiveAmount;
final type = isReverse ? 'reverse' : 'direct';
final flow = getFlow(isFixedRateMode);
final params = <String, String>{
'fromCurrency': _normalizeCurrency(from),
'toCurrency': _normalizeCurrency(to),
'fromNetwork': _networkFor(from),
'toNetwork': _networkFor(to),
2022-01-26 15:44:15 +00:00
'type': type,
'flow': flow
};
2022-01-26 15:44:15 +00:00
if (isReverse) {
params['toAmount'] = amount.toString();
} else {
params['fromAmount'] = amount.toString();
}
2022-01-26 15:44:15 +00:00
final uri = Uri.https(apiAuthority, estimatedAmountPath, params);
final response = await get(uri, headers: headers);
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
2022-01-26 15:44:15 +00:00
final fromAmount = double.parse(responseJSON['fromAmount'].toString());
final toAmount = double.parse(responseJSON['toAmount'].toString());
final rateId = responseJSON['rateId'] as String? ?? '';
2020-01-04 19:31:52 +00:00
2022-01-26 15:44:15 +00:00
if (rateId.isNotEmpty) {
_lastUsedRateId = rateId;
}
return isReverse ? (amount / fromAmount) : (toAmount / amount);
} catch (e) {
2022-01-26 15:44:15 +00:00
print(e.toString());
return 0.0;
}
}
String _networkFor(CryptoCurrency currency) {
switch (currency) {
case CryptoCurrency.usdt:
return 'btc';
default:
return currency.tag != null ? _normalizeTag(currency.tag!) : currency.title.toLowerCase();
}
}
String _normalizeCurrency(CryptoCurrency currency) {
switch (currency) {
case CryptoCurrency.zec:
return 'zec';
default:
return currency.title.toLowerCase();
}
}
String _normalizeTag(String tag) {
switch (tag) {
case 'POLY':
return 'matic';
case 'LN':
return 'lightning';
case 'AVAXC':
return 'cchain';
default:
return tag.toLowerCase();
}
}
}