stack_wallet/lib/services/price_service.dart

84 lines
2.1 KiB
Dart
Raw Normal View History

2022-08-26 08:11:35 +00:00
import 'dart:async';
import 'package:decimal/decimal.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart';
import 'package:stackwallet/services/price.dart';
import 'package:stackwallet/utilities/enums/coin_enum.dart';
import 'package:tuple/tuple.dart';
class PriceService extends ChangeNotifier {
late final String baseTicker;
2023-02-28 16:36:24 +00:00
static Set<String> tokenContractAddressesToCheck = {};
2022-08-26 08:11:35 +00:00
final Duration updateInterval = const Duration(seconds: 60);
Timer? _timer;
final Map<Coin, Tuple2<Decimal, double>> _cachedPrices = {
for (final coin in Coin.values) coin: Tuple2(Decimal.zero, 0.0)
};
2023-02-28 16:36:24 +00:00
final Map<String, Tuple2<Decimal, double>> _cachedTokenPrices = {};
2022-08-26 08:11:35 +00:00
final _priceAPI = PriceAPI(Client());
Tuple2<Decimal, double> getPrice(Coin coin) => _cachedPrices[coin]!;
2023-02-28 16:36:24 +00:00
Tuple2<Decimal, double> getTokenPrice(String contractAddress) =>
_cachedTokenPrices[contractAddress.toLowerCase()] ??
Tuple2(Decimal.zero, 0);
PriceService(this.baseTicker);
2022-08-26 08:11:35 +00:00
Future<void> updatePrice() async {
final priceMap =
await _priceAPI.getPricesAnd24hChange(baseCurrency: baseTicker);
bool shouldNotify = false;
for (final map in priceMap.entries) {
if (_cachedPrices[map.key] != map.value) {
_cachedPrices[map.key] = map.value;
shouldNotify = true;
}
}
2023-02-28 16:36:24 +00:00
if (tokenContractAddressesToCheck.isNotEmpty) {
final tokenPriceMap = await _priceAPI.getPricesAnd24hChangeForEthTokens(
contractAddresses: tokenContractAddressesToCheck,
baseCurrency: baseTicker,
);
for (final map in tokenPriceMap.entries) {
if (_cachedTokenPrices[map.key] != map.value) {
_cachedTokenPrices[map.key] = map.value;
shouldNotify = true;
}
}
}
2022-08-26 08:11:35 +00:00
if (shouldNotify) {
notifyListeners();
}
}
void cancel() {
_timer?.cancel();
_timer = null;
}
void start(bool rightAway) {
if (rightAway) {
updatePrice();
}
_timer?.cancel();
_timer = Timer.periodic(updateInterval, (_) {
updatePrice();
});
}
@override
void dispose() {
cancel();
super.dispose();
}
}