Skip to content

Commit

Permalink
fix: fetch fiat rates on start (#1592)
Browse files Browse the repository at this point in the history
  • Loading branch information
justinenerio authored Oct 14, 2024
1 parent 3776779 commit 101d434
Showing 1 changed file with 22 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ class ConversionRatesRepository {
required JupiterPriceClient jupiterClient,
}) : _db = db,
_ecClient = ecClient,
_jupiterClient = jupiterClient {
_initCache();
}
_jupiterClient = jupiterClient;

final MyDatabase _db;
final JupiterPriceClient _jupiterClient;
Expand All @@ -36,6 +34,12 @@ class ConversionRatesRepository {
final Map<String, Map<String, Decimal>> _ratesCache = {};
StreamSubscription<void>? _cacheSubscription;

@postConstruct
void init() {
_initCache();
_fetchFiatRates();
}

void _initCache() {
_cacheSubscription =
_db.select(_db.conversionRatesRows).watch().listen((rows) {
Expand Down Expand Up @@ -123,21 +127,24 @@ class ConversionRatesRepository {

AsyncResult<void> refresh(FiatCurrency currency, Iterable<Token> tokens) =>
_cache.fetchEither(() async {
final data = await _ecClient.getRates().then((p) => p.usdc);

await _db.into(_db.conversionRatesRows).insert(
ConversionRatesRowsCompanion.insert(
token: Currency.usdc.token.address,
fiatCurrency: currency.symbol,
rate: data.toString(),
updatedAt: DateTime.now(),
),
mode: InsertMode.replace,
);

await _fetchFiatRates(currency: currency);
await _fetchTokens(currency, tokens);
});

Future<void> _fetchFiatRates({FiatCurrency? currency}) async {
final data = await _ecClient.getRates().then((p) => p.usdc);

await _db.into(_db.conversionRatesRows).insert(
ConversionRatesRowsCompanion.insert(
token: Currency.usdc.token.address,
fiatCurrency: currency?.symbol ?? Currency.usd.symbol,
rate: data.toString(),
updatedAt: DateTime.now(),
),
mode: InsertMode.replace,
);
}

@disposeMethod
void dispose() {
_cacheSubscription?.cancel();
Expand Down

0 comments on commit 101d434

Please sign in to comment.