CakeWallet/lib/buy/meld/meld_buy_provider.dart
cyan 5082dc20f3
CW-519 Enable built-in Tor (#1950)
* tor wip

* Enable tor on iOS

* Prevent app lag when node is exceptionally slow (usually over tor)

* fix: logic in daemonBlockchainHeight refresh
fix: storing tor state

* Pin ledger_flutter_plus dependency to fix builds

* bump arti version

* wip

* add single httpclient

* route everything I was able to catch trough the built-in tor node

* Enable proxy for http.Client [run tests]

* add tor proxy support to cw_evm, cw_tron and cw_polygon [run tests]

* remove log pollution, cleanup [skip slack]

* fix tests not working in latest main [skip slack] [run tests]

* remove cw_wownero import

* fix build issues

* migrate all remaining calls to use ProxyWrapper
add a CI action to enforce using ProxyWrapper instead of http/http.dart to prevent leaks

* fix tor background sync (will work on test builds after #2142 is merged and this PR is rebased on top)

* wip [skip ci]

* relicense to GPLv3 add socks5 license, build fixes

* use ProxyWrapper instead of http in robinhood

* Revert "relicense to GPLv3"

* feat(cw_bitcoin): support socks proxy and CakeTor

* fix(tor): migrate OCP and EVM over to ProxyWrapper()

* chore: cleanup
fix: show tor loading screen when app is starting

* fix: tor switch properly dismisses fullscreen loading dialog
fix: connectToNode after tor startup on app start

* fix(tor): status check for xmr/wow/zano

* fix(tor): onramper request fix

* fix(api): ServicesResponse is now being cached and doesn't fetch data everytime DashboardViewModel is being rebuilt
fix(tor): do not fallback to clearnet when tor failed.
fix(tor): do not leak connections during app startup
chore: refactor bootstrap() function to be separated into bootstrapOffline and bootstrapOnline
fix(cw_bitcoin): migrate payjoin to use ProxyWrapper

* [skip ci] remove print

* address comments from review

* fix: derusting tor implementation

Instead of rust-based Arti I've moved back to the
OG C++ tor implementation.
This fixed all issues we had with Tor.
- onion services now work
- all requests are going through without random errors
- we don't have to navigate a maze of multiple forks of multiple packages
- fully working `torrc` config file (probably will be needed for Tari).
- logging for Tor client
- and so on.

feat: network logging tab
feat: use built-in proxy on Tails - this should resolve all issues for Tails users (needs testing though)

* fix conflicts with main
bump https to fix build issue
relax store() call

* fix(cw_wownero): tor connection
fix(tor): connection issues

* fix(cw_evm): add missing chainId
fix(cw_core): solana rpc fix

* feat: mark tor as experimental
fix: drop anonpay onion authority
fix: drop fiatapi onion authority
fix: drop trocador onion authority
fix: disable networkimage when tor is enabled
fix: handle cakepay errors gracefully

* fix re-formatting [skip ci]

* changes from review

* Delete android/.kotlin/sessions/kotlin-compiler-2468481326039681181.salive

* fix missing imports

* Update pubspec_base.yaml

---------

Co-authored-by: OmarHatem <omarh.ismail1@gmail.com>
2025-06-20 22:56:18 +03:00

281 lines
9 KiB
Dart

import 'dart:convert';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/buy/buy_provider.dart';
import 'package:cake_wallet/buy/buy_quote.dart';
import 'package:cake_wallet/buy/pairs_utils.dart';
import 'package:cake_wallet/buy/payment_method.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/src/widgets/alert_with_one_action.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:flutter/material.dart';
import 'dart:developer';
import 'package:url_launcher/url_launcher.dart';
class MeldBuyProvider extends BuyProvider {
MeldBuyProvider({required WalletBase wallet, bool isTestEnvironment = false})
: super(
wallet: wallet,
isTestEnvironment: isTestEnvironment,
ledgerVM: null,
supportedCryptoList: supportedCryptoToFiatPairs(
notSupportedCrypto: _notSupportedCrypto, notSupportedFiat: _notSupportedFiat),
supportedFiatList: supportedFiatToCryptoPairs(
notSupportedFiat: _notSupportedFiat, notSupportedCrypto: _notSupportedCrypto));
static const _isProduction = false;
static const _baseUrl = _isProduction ? 'api.meld.io' : 'api-sb.meld.io';
static const _providersProperties = '/service-providers/properties';
static const _paymentMethodsPath = '/payment-methods';
static const _quotePath = '/payments/crypto/quote';
static const String sandboxUrl = 'sb.fluidmoney.xyz';
static const String productionUrl = 'fluidmoney.xyz';
static const String _baseWidgetUrl = _isProduction ? productionUrl : sandboxUrl;
static String get _testApiKey => secrets.meldTestApiKey;
static const List<CryptoCurrency> _notSupportedCrypto = [];
static const List<FiatCurrency> _notSupportedFiat = [];
static String get _testPublicKey => '' ; //secrets.meldTestPublicKey;
@override
String get title => 'Meld';
@override
String get providerDescription => 'Meld Buy Provider';
@override
String get lightIcon => 'assets/images/meld_logo.svg';
@override
String get darkIcon => 'assets/images/meld_logo.svg';
@override
bool get isAggregator => true;
@override
Future<List<PaymentMethod>> getAvailablePaymentTypes(
String fiatCurrency, CryptoCurrency cryptoCurrency, bool isBuyAction) async {
final params = {'fiatCurrencies': fiatCurrency, 'statuses': 'LIVE,RECENTLY_ADDED,BUILDING'};
final path = '$_providersProperties$_paymentMethodsPath';
final url = Uri.https(_baseUrl, path, params);
try {
final response = await ProxyWrapper().get(
clearnetUri: url,
headers: {
'Authorization': _isProduction ? '' : _testApiKey,
'Meld-Version': '2023-12-19',
'accept': 'application/json',
'content-type': 'application/json',
},
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as List<dynamic>;
final paymentMethods =
data.map((e) => PaymentMethod.fromMeldJson(e as Map<String, dynamic>)).toList();
return paymentMethods;
} else {
printV('Meld: Failed to fetch payment types');
return List<PaymentMethod>.empty();
}
} catch (e) {
printV('Meld: Failed to fetch payment types: $e');
return List<PaymentMethod>.empty();
}
}
@override
Future<List<Quote>?> fetchQuote(
{required CryptoCurrency cryptoCurrency,
required FiatCurrency fiatCurrency,
required double amount,
required bool isBuyAction,
required String walletAddress,
PaymentType? paymentType,
String? customPaymentMethodType,
String? countryCode}) async {
String? paymentMethod;
if (paymentType != null && paymentType != PaymentType.all) {
paymentMethod = normalizePaymentMethod(paymentType);
if (paymentMethod == null) paymentMethod = paymentType.name;
}
log('Meld: Fetching buy quote: ${isBuyAction ? cryptoCurrency : fiatCurrency} -> ${isBuyAction ? fiatCurrency : cryptoCurrency}, amount: $amount');
final url = Uri.https(_baseUrl, _quotePath);
final headers = {
'Authorization': _testApiKey,
'Meld-Version': '2023-12-19',
'accept': 'application/json',
'content-type': 'application/json',
};
final body = jsonEncode({
'countryCode': countryCode,
'destinationCurrencyCode': isBuyAction ? fiatCurrency.name : cryptoCurrency.title,
'sourceAmount': amount,
'sourceCurrencyCode': isBuyAction ? cryptoCurrency.title : fiatCurrency.name,
if (paymentMethod != null) 'paymentMethod': paymentMethod,
});
try {
final response = await ProxyWrapper().post(
clearnetUri: url,
headers: headers,
body: body,
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as Map<String, dynamic>;
final paymentType = _getPaymentTypeByString(data['paymentMethodType'] as String?);
final quote = Quote.fromMeldJson(data, isBuyAction, paymentType);
quote.setFiatCurrency = fiatCurrency;
quote.setCryptoCurrency = cryptoCurrency;
return [quote];
} else {
return null;
}
} catch (e) {
printV('Error fetching buy quote: $e');
return null;
}
}
Future<void>? launchProvider(
{required BuildContext context,
required Quote quote,
required double amount,
required bool isBuyAction,
required String cryptoCurrencyAddress,
String? countryCode}) async {
final actionType = isBuyAction ? 'BUY' : 'SELL';
final params = {
'publicKey': _isProduction ? '' : _testPublicKey,
'countryCode': countryCode,
//'paymentMethodType': normalizePaymentMethod(paymentMethod.paymentMethodType),
'sourceAmount': amount.toString(),
'sourceCurrencyCode': quote.fiatCurrency,
'destinationCurrencyCode': quote.cryptoCurrency,
'walletAddress': cryptoCurrencyAddress,
'transactionType': actionType
};
final uri = Uri.https(_baseWidgetUrl, '', params);
try {
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else {
throw Exception('Could not launch URL');
}
} catch (e) {
await showPopUp<void>(
context: context,
builder: (BuildContext context) {
return AlertWithOneAction(
alertTitle: "Meld",
alertContent: S.of(context).buy_provider_unavailable + ': $e',
buttonText: S.of(context).ok,
buttonAction: () => Navigator.of(context).pop());
});
}
}
String? normalizePaymentMethod(PaymentType paymentType) {
switch (paymentType) {
case PaymentType.creditCard:
return 'CREDIT_DEBIT_CARD';
case PaymentType.applePay:
return 'APPLE_PAY';
case PaymentType.googlePay:
return 'GOOGLE_PAY';
case PaymentType.neteller:
return 'NETELLER';
case PaymentType.skrill:
return 'SKRILL';
case PaymentType.sepa:
return 'SEPA';
case PaymentType.sepaInstant:
return 'SEPA_INSTANT';
case PaymentType.ach:
return 'ACH';
case PaymentType.achInstant:
return 'INSTANT_ACH';
case PaymentType.Khipu:
return 'KHIPU';
case PaymentType.ovo:
return 'OVO';
case PaymentType.zaloPay:
return 'ZALOPAY';
case PaymentType.zaloBankTransfer:
return 'ZA_BANK_TRANSFER';
case PaymentType.gcash:
return 'GCASH';
case PaymentType.imps:
return 'IMPS';
case PaymentType.dana:
return 'DANA';
case PaymentType.ideal:
return 'IDEAL';
default:
return null;
}
}
PaymentType _getPaymentTypeByString(String? paymentMethod) {
switch (paymentMethod?.toUpperCase()) {
case 'CREDIT_DEBIT_CARD':
return PaymentType.creditCard;
case 'APPLE_PAY':
return PaymentType.applePay;
case 'GOOGLE_PAY':
return PaymentType.googlePay;
case 'NETELLER':
return PaymentType.neteller;
case 'SKRILL':
return PaymentType.skrill;
case 'SEPA':
return PaymentType.sepa;
case 'SEPA_INSTANT':
return PaymentType.sepaInstant;
case 'ACH':
return PaymentType.ach;
case 'INSTANT_ACH':
return PaymentType.achInstant;
case 'KHIPU':
return PaymentType.Khipu;
case 'OVO':
return PaymentType.ovo;
case 'ZALOPAY':
return PaymentType.zaloPay;
case 'ZA_BANK_TRANSFER':
return PaymentType.zaloBankTransfer;
case 'GCASH':
return PaymentType.gcash;
case 'IMPS':
return PaymentType.imps;
case 'DANA':
return PaymentType.dana;
case 'IDEAL':
return PaymentType.ideal;
default:
return PaymentType.all;
}
}
}