cake_wallet/lib/buy/moonpay/moonpay_provider.dart

306 lines
10 KiB
Dart
Raw Normal View History

import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/buy/buy_amount.dart';
import 'package:cake_wallet/buy/buy_exception.dart';
import 'package:cake_wallet/buy/buy_provider.dart';
import 'package:cake_wallet/buy/buy_provider_description.dart';
import 'package:cake_wallet/buy/order.dart';
import 'package:cake_wallet/exchange/trade_state.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/palette.dart';
import 'package:cake_wallet/routes.dart';
import 'package:cake_wallet/src/widgets/alert_with_one_action.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/themes/theme_base.dart';
import 'package:cake_wallet/utils/device_info.dart';
import 'package:crypto/crypto.dart';
import 'package:cw_core/crypto_currency.dart';
2021-12-24 12:37:24 +00:00
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:url_launcher/url_launcher.dart';
2021-12-08 12:46:01 +00:00
class MoonPaySellProvider extends BuyProvider {
MoonPaySellProvider({
required SettingsStore settingsStore,
required WalletBase wallet,
bool isTestEnvironment = false,
}) : baseUrl = isTestEnvironment ? _baseTestUrl : _baseProductUrl,
this._settingsStore = settingsStore,
super(wallet: wallet, isTestEnvironment: isTestEnvironment);
final SettingsStore _settingsStore;
2021-12-08 12:46:01 +00:00
static const _baseTestUrl = 'sell-sandbox.moonpay.com';
2021-12-08 12:46:01 +00:00
static const _baseProductUrl = 'sell.moonpay.com';
static const _cIdBaseUrl = 'exchange-helper.cakewallet.com';
@override
String get providerDescription =>
'MoonPay offers a fast and simple way to buy and sell cryptocurrencies';
@override
String get title => 'MoonPay';
@override
String get lightIcon => 'assets/images/moonpay_light.png';
@override
String get darkIcon => 'assets/images/moonpay_dark.png';
static String themeToMoonPayTheme(ThemeBase theme) {
switch (theme.type) {
case ThemeType.bright:
case ThemeType.light:
return 'light';
case ThemeType.dark:
return 'dark';
}
}
static String get _apiKey => secrets.moonPayApiKey;
static String get _exchangeHelperApiKey => secrets.exchangeHelperApiKey;
2021-12-08 12:46:01 +00:00
final String baseUrl;
Future<String> getMoonpaySignature(String query) async {
final uri = Uri.https(_cIdBaseUrl, "/api/moonpay");
final response = await post(
uri,
headers: {
'Content-Type': 'application/json',
'x-api-key': _exchangeHelperApiKey,
},
body: json.encode({'query': query}),
);
if (response.statusCode == 200) {
return (jsonDecode(response.body) as Map<String, dynamic>)['signature'] as String;
} else {
throw Exception(
'Provider currently unavailable. Status: ${response.statusCode} ${response.body}');
}
}
Future<Uri> requestMoonPayUrl({
required CryptoCurrency currency,
required String refundWalletAddress,
required SettingsStore settingsStore,
}) async {
final customParams = {
'theme': themeToMoonPayTheme(settingsStore.currentTheme),
'language': settingsStore.languageCode,
'colorCode': settingsStore.currentTheme.type == ThemeType.dark
? '#${Palette.blueCraiola.value.toRadixString(16).substring(2, 8)}'
: '#${Palette.moderateSlateBlue.value.toRadixString(16).substring(2, 8)}',
};
2021-12-08 12:46:01 +00:00
final originalUri = Uri.https(
baseUrl,
'',
<String, dynamic>{
2021-12-08 12:46:01 +00:00
'apiKey': _apiKey,
'defaultBaseCurrencyCode': _normalizeCurrency(currency),
'refundWalletAddress': refundWalletAddress,
}..addAll(customParams),
);
final signature = await getMoonpaySignature('?${originalUri.query}');
2021-12-08 12:46:01 +00:00
if (isTestEnvironment) {
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
return originalUri;
2021-12-08 12:46:01 +00:00
}
final query = Map<String, dynamic>.from(originalUri.queryParameters);
query['signature'] = signature;
final signedUri = originalUri.replace(queryParameters: query);
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
return signedUri;
2021-12-08 12:46:01 +00:00
}
@override
Future<void> launchProvider(BuildContext context, bool? isBuyAction) async {
try {
final uri = await requestMoonPayUrl(
currency: wallet.currency,
refundWalletAddress: wallet.walletAddresses.address,
settingsStore: _settingsStore,
);
if (await canLaunchUrl(uri)) {
if (DeviceInfo.instance.isMobile) {
Navigator.of(context).pushNamed(Routes.webViewPage, arguments: ['MoonPay', uri]);
} else {
await launchUrl(uri, mode: LaunchMode.externalApplication);
}
} else {
throw Exception('Could not launch URL');
}
} catch (e) {
await showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertWithOneAction(
alertTitle: 'MoonPay',
alertContent: 'The MoonPay service is currently unavailable: $e',
buttonText: S.of(context).ok,
buttonAction: () => Navigator.of(context).pop(),
);
},
);
}
}
String _normalizeCurrency(CryptoCurrency currency) {
if (currency == CryptoCurrency.maticpoly) {
return "MATIC_POLYGON";
}
return currency.toString().toLowerCase();
}
2021-12-08 12:46:01 +00:00
}
class MoonPayBuyProvider extends BuyProvider {
2022-10-12 17:09:57 +00:00
MoonPayBuyProvider({required WalletBase wallet, bool isTestEnvironment = false})
: baseUrl = isTestEnvironment ? _baseTestUrl : _baseProductUrl,
super(wallet: wallet, isTestEnvironment: isTestEnvironment);
static const _baseTestUrl = 'https://buy-staging.moonpay.com';
static const _baseProductUrl = 'https://buy.moonpay.com';
static const _apiUrl = 'https://api.moonpay.com';
static const _currenciesSuffix = '/v3/currencies';
static const _quoteSuffix = '/buy_quote';
static const _transactionsSuffix = '/v1/transactions';
static const _ipAddressSuffix = '/v4/ip_address';
static const _apiKey = secrets.moonPayApiKey;
static const _secretKey = secrets.moonPaySecretKey;
@override
String get title => 'MoonPay';
@override
String get providerDescription =>
'MoonPay offers a fast and simple way to buy and sell cryptocurrencies';
@override
String get lightIcon => 'assets/images/moonpay_light.png';
@override
String get darkIcon => 'assets/images/moonpay_dark.png';
String get currencyCode => walletTypeToCryptoCurrency(wallet.type).title.toLowerCase();
String get trackUrl => baseUrl + '/transaction_receipt?transactionId=';
String baseUrl;
Future<String> requestUrl(String amount, String sourceCurrency) async {
final enabledPaymentMethods = 'credit_debit_card%2Capple_pay%2Cgoogle_pay%2Csamsung_pay'
'%2Csepa_bank_transfer%2Cgbp_bank_transfer%2Cgbp_open_banking_payment';
final suffix = '?apiKey=' +
_apiKey +
'&currencyCode=' +
currencyCode +
'&enabledPaymentMethods=' +
enabledPaymentMethods +
'&walletAddress=' +
wallet.walletAddresses.address +
'&baseCurrencyCode=' +
sourceCurrency.toLowerCase() +
'&baseCurrencyAmount=' +
amount +
'&lockAmount=true' +
'&showAllCurrencies=false' +
'&showWalletAddressForm=false';
final originalUrl = baseUrl + suffix;
final messageBytes = utf8.encode(suffix);
final key = utf8.encode(_secretKey);
final hmac = Hmac(sha256, key);
final digest = hmac.convert(messageBytes);
final signature = base64.encode(digest.bytes);
final urlWithSignature = originalUrl + '&signature=${Uri.encodeComponent(signature)}';
return isTestEnvironment ? originalUrl : urlWithSignature;
}
Future<BuyAmount> calculateAmount(String amount, String sourceCurrency) async {
final url = _apiUrl +
_currenciesSuffix +
'/$currencyCode' +
_quoteSuffix +
'/?apiKey=' +
_apiKey +
'&baseCurrencyAmount=' +
amount +
'&baseCurrencyCode=' +
sourceCurrency.toLowerCase();
2022-10-12 17:09:57 +00:00
final uri = Uri.parse(url);
final response = await get(uri);
if (response.statusCode != 200) {
throw BuyException(title: providerDescription, content: 'Quote is not found!');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final sourceAmount = responseJSON['totalAmount'] as double;
final destAmount = responseJSON['quoteCurrencyAmount'] as double;
final minSourceAmount = responseJSON['baseCurrency']['minAmount'] as int;
return BuyAmount(
sourceAmount: sourceAmount, destAmount: destAmount, minAmount: minSourceAmount);
}
Future<Order> findOrderById(String id) async {
final url = _apiUrl + _transactionsSuffix + '/$id' + '?apiKey=' + _apiKey;
2022-10-12 17:09:57 +00:00
final uri = Uri.parse(url);
final response = await get(uri);
if (response.statusCode != 200) {
throw BuyException(title: providerDescription, content: 'Transaction $id is not found!');
}
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
final status = responseJSON['status'] as String;
final state = TradeState.deserialize(raw: status);
final createdAtRaw = responseJSON['createdAt'] as String;
final createdAt = DateTime.parse(createdAtRaw).toLocal();
final amount = responseJSON['quoteCurrencyAmount'] as double;
return Order(
id: id,
provider: BuyProviderDescription.moonPay,
transferId: id,
state: state,
createdAt: createdAt,
amount: amount.toString(),
receiveAddress: wallet.walletAddresses.address,
walletId: wallet.id);
}
static Future<bool> onEnabled() async {
final url = _apiUrl + _ipAddressSuffix + '?apiKey=' + _apiKey;
var isBuyEnable = false;
2022-10-12 17:09:57 +00:00
final uri = Uri.parse(url);
final response = await get(uri);
try {
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
isBuyEnable = responseJSON['isBuyAllowed'] as bool;
} catch (e) {
isBuyEnable = false;
print(e.toString());
}
return isBuyEnable;
}
@override
Future<void> launchProvider(BuildContext context, bool? isBuyAction) =>
throw UnimplementedError();
}