cake_wallet/lib/core/fiat_conversion_service.dart

57 lines
1.6 KiB
Dart
Raw Normal View History

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/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 _fiatApiClearNetAuthority = 'fiat-api.cakewallet.com';
const _fiatApiOnionAuthority = 'n4z7bdcmwk2oyddxvzaap3x2peqcplh3pzdy7tpkk5ejz5n4mhfvoxqd.onion';
const _fiatApiPath = '/v2/rates';
2020-01-04 19:31:52 +00:00
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;
final torOnly = args['torOnly'] as bool;
2020-01-04 19:31:52 +00:00
double price = 0.0;
try {
final uri = Uri.https(
torOnly ? _fiatApiOnionAuthority : _fiatApiClearNetAuthority,
_fiatApiPath,
<String, String>{
'interval_count': '1',
'base': crypto.toString(),
'quote': fiat.toString(),
},
);
2022-10-12 17:09:57 +00:00
final response = await get(uri);
2020-01-04 19:31:52 +00:00
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>;
final results = responseJSON['results'] as Map<String, dynamic>;
2020-01-04 19:31:52 +00:00
if (results.isNotEmpty) {
price = results.values.first as double;
2020-01-04 19:31:52 +00:00
}
return price;
} catch (e) {
return price;
}
}
2020-09-21 11:50:26 +00:00
Future<double> _fetchPriceAsync(CryptoCurrency crypto, FiatCurrency fiat, bool torOnly) async =>
compute(_fetchPrice, {'fiat': fiat, 'crypto': crypto, 'torOnly': torOnly});
2020-09-21 11:50:26 +00:00
class FiatConversionService {
static Future<double> fetchPrice({
required CryptoCurrency crypto,
required FiatCurrency fiat,
required bool torOnly,
}) async =>
await _fetchPriceAsync(crypto, fiat, torOnly);
2020-09-21 11:50:26 +00:00
}