2020-09-21 11:50:26 +00:00
|
|
|
import 'package:cake_wallet/entities/crypto_currency.dart';
|
|
|
|
import 'package:cake_wallet/entities/fiat_currency.dart';
|
2020-01-04 19:31:52 +00:00
|
|
|
import 'dart:convert';
|
2020-09-21 11:50:26 +00:00
|
|
|
import 'package:flutter/foundation.dart';
|
2020-01-04 19:31:52 +00:00
|
|
|
import 'package:http/http.dart';
|
|
|
|
|
|
|
|
const fiatApiAuthority = 'fiat-api.cakewallet.com';
|
|
|
|
const fiatApiPath = '/v1/rates';
|
|
|
|
|
2020-09-21 11:50:26 +00:00
|
|
|
Future<double> _fetchPrice(Map<String, dynamic> args) async {
|
|
|
|
final crypto = args['crypto'] as CryptoCurrency;
|
|
|
|
final fiat = args['fiat'] as FiatCurrency;
|
2020-01-04 19:31:52 +00:00
|
|
|
double price = 0.0;
|
|
|
|
|
|
|
|
try {
|
|
|
|
final fiatStringified = fiat.toString();
|
2021-05-07 07:36:38 +00:00
|
|
|
final uri = Uri.https(fiatApiAuthority, fiatApiPath,
|
|
|
|
<String, String>{'convert': fiatStringified});
|
2020-01-04 19:31:52 +00:00
|
|
|
final response = await get(uri.toString());
|
|
|
|
|
|
|
|
if (response.statusCode != 200) {
|
|
|
|
return 0.0;
|
|
|
|
}
|
|
|
|
|
2020-01-08 12:26:34 +00:00
|
|
|
final responseJSON = json.decode(response.body) as Map<String, dynamic>;
|
2020-01-10 16:11:14 +00:00
|
|
|
final data = responseJSON['data'] as List<dynamic>;
|
2020-01-04 19:31:52 +00:00
|
|
|
|
|
|
|
for (final item in data) {
|
2021-05-07 07:36:38 +00:00
|
|
|
if (item['symbol'] == crypto.title) {
|
2020-01-08 12:26:34 +00:00
|
|
|
price = item['quote'][fiatStringified]['price'] as double;
|
2020-01-04 19:31:52 +00:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return price;
|
|
|
|
} catch (e) {
|
|
|
|
return price;
|
|
|
|
}
|
|
|
|
}
|
2020-09-21 11:50:26 +00:00
|
|
|
|
|
|
|
Future<double> _fetchPriceAsync(
|
|
|
|
CryptoCurrency crypto, FiatCurrency fiat) async =>
|
|
|
|
compute(_fetchPrice, {'fiat': fiat, 'crypto': crypto});
|
|
|
|
|
|
|
|
class FiatConversionService {
|
2021-05-07 07:36:38 +00:00
|
|
|
static Future<double> fetchPrice(
|
|
|
|
CryptoCurrency crypto, FiatCurrency fiat) async =>
|
2020-09-21 11:50:26 +00:00
|
|
|
await _fetchPriceAsync(crypto, fiat);
|
|
|
|
}
|