-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprovider.dart
75 lines (60 loc) · 2.19 KB
/
provider.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// SPDX-License-Identifier: AGPL-3.0-or-later
import 'dart:async';
import 'package:archethic_dapp_framework_flutter/src/application/oracle/state.dart';
import 'package:archethic_lib_dart/archethic_lib_dart.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'provider.g.dart';
@riverpod
OracleService oracleService(Ref ref) {
// We use always mainnet values
return OracleService('https://mainnet.archethic.net');
}
@riverpod
class _ArchethicOracleUCONotifier extends _$ArchethicOracleUCONotifier {
StreamSubscription? archethicOracleSubscription;
late final OracleService _oracleService;
static final _logger = Logger('ArchethicOracleUCONotifier');
@override
Future<ArchethicOracleUCO> build() async {
_oracleService = ref.watch(oracleServiceProvider);
ref.onDispose(stopSubscription);
return _subscribe();
}
Future<void> startSubscription() async {
if (archethicOracleSubscription != null) return;
final oracleValue = await _subscribe();
await update((_) {
return oracleValue;
});
}
/// Starts listening to oracle stream.
///
/// Retrieves and returns current oracle value.
/// This is useful to immediately get oracle state.
Future<ArchethicOracleUCO> _subscribe() async {
_logger.info('Start listening to Oracle');
final oracleUcoPrice = await _oracleService.getOracleData();
final oracleStream = await _oracleService.subscribe();
archethicOracleSubscription =
oracleStream.map((event) => event.toArchethic).listen((oracleEvent) {
_logger.info(
'Oracle: ${oracleEvent.timestamp}, eur: ${oracleEvent.eur}, usd: ${oracleEvent.usd}',
);
update((_) {
return oracleEvent;
});
});
return oracleUcoPrice.toArchethic;
}
Future<void> stopSubscription() async {
_logger.info('Stop listening to Oracle');
if (archethicOracleSubscription == null) return;
await archethicOracleSubscription?.cancel();
archethicOracleSubscription = null;
}
}
abstract class ArchethicOracleUCOProviders {
static final archethicOracleUCO = _archethicOracleUCONotifierProvider;
}