| 1 | import 'package:cw_core/utils/print_verbose.dart'; |
| 2 | import 'package:cw_core/utils/proxy_wrapper.dart'; |
| 3 | import 'package:cw_core/crypto_currency.dart'; |
| 4 | import 'package:cake_wallet/entities/fiat_currency.dart'; |
| 5 | import 'dart:convert'; |
| 6 | import 'package:cake_wallet/.secrets.g.dart' as secrets; |
| 7 | |
| 8 | const _fiatApiClearNetAuthority = 'prices.cakewallet.com'; |
| 9 | const _fiatApiOnionAuthority = '46wisoe2uwipcj2j4og6smiq7hbmj34fkkrquwlzbbsqtgat7bf3erid.onion'; |
| 10 | const _fiatApiPath = '/v2/rates'; |
| 11 | |
| 12 | Future<double> _fetchPrice(String crypto, String fiat, bool torOnly) async { |
| 13 | final Map<String, String> queryParams = { |
| 14 | 'interval_count': '1', |
| 15 | 'base': crypto.split(".").first, |
| 16 | 'quote': fiat, |
| 17 | }; |
| 18 | |
| 19 | num price = 0.0; |
| 20 | |
| 21 | try { |
| 22 | final onionUri = Uri.http(_fiatApiOnionAuthority, _fiatApiPath, queryParams); |
| 23 | final clearnetUri = Uri.https(_fiatApiClearNetAuthority, _fiatApiPath, queryParams); |
| 24 | |
| 25 | final response = await ProxyWrapper() |
| 26 | .get(onionUri: onionUri, clearnetUri: torOnly ? onionUri : clearnetUri, headers: { |
| 27 | "x-api-key": secrets.fiatApiKey, |
| 28 | }); |
| 29 | |
| 30 | if (response.statusCode != 200) { |
| 31 | return 0.0; |
| 32 | } |
| 33 | |
| 34 | final responseJSON = json.decode(response.body) as Map<String, dynamic>; |
| 35 | final results = responseJSON['results'] as Map<String, dynamic>; |
| 36 | |
| 37 | if (results.isNotEmpty) { |
| 38 | price = results.values.first as num; |
| 39 | } |
| 40 | |
| 41 | return price.toDouble(); |
| 42 | } catch (e) { |
| 43 | return price.toDouble(); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | /// Override specific [CryptoCurrency] to fix its price to the price of another |
| 48 | /// e.g. nDEPS should have the same price as DEPS, but only DEPS is tracked |
| 49 | CryptoCurrency _overrideCryptoCurrency(CryptoCurrency crypto) { |
| 50 | if (crypto.title == CryptoCurrency.ndeps.title) return CryptoCurrency.deps; |
| 51 | return crypto; |
| 52 | } |
| 53 | |
| 54 | class FiatConversionService { |
| 55 | static Future<double> fetchPrice({ |
| 56 | required CryptoCurrency crypto, |
| 57 | required FiatCurrency fiat, |
| 58 | required bool torOnly, |
| 59 | }) async => |
| 60 | await _fetchPrice(_overrideCryptoCurrency(crypto).toString(), fiat.toString(), torOnly); |
| 61 | } |