-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathexchange_data_loading_service.dart
More file actions
452 lines (420 loc) · 14.2 KB
/
Copy pathexchange_data_loading_service.dart
File metadata and controls
452 lines (420 loc) · 14.2 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*
* This file is part of Stack Wallet.
*
* Copyright (c) 2023 Cypher Stack
* All Rights Reserved.
* The code is distributed under GPLv3 license, see LICENSE file for details.
* Generated by Cypher Stack on 2023-05-26
*
*/
import 'package:flutter/foundation.dart';
import 'package:isar/isar.dart';
import 'package:tuple/tuple.dart';
import '../../app_config.dart';
import '../../db/hive/db.dart';
import '../../models/exchange/active_pair.dart';
import '../../models/exchange/aggregate_currency.dart';
import '../../models/isar/exchange_cache/currency.dart';
import '../../models/isar/exchange_cache/pair.dart';
import '../../utilities/enums/exchange_rate_type_enum.dart';
import '../../utilities/logger.dart';
import '../../utilities/prefs.dart';
import '../../utilities/stack_file_system.dart';
import 'change_now/change_now_exchange.dart';
import 'nanswap/nanswap_exchange.dart';
import 'trocador/trocador_exchange.dart';
class ExchangeDataLoadingService {
ExchangeDataLoadingService._();
static final ExchangeDataLoadingService _instance =
ExchangeDataLoadingService._();
static ExchangeDataLoadingService get instance => _instance;
Isar? _isar;
Isar get isar => _isar!;
VoidCallback? onLoadingError;
VoidCallback? onLoadingComplete;
static const int cacheVersion = 1;
static int get currentCacheVersion =>
DB.instance.get<dynamic>(
boxName: DB.boxNameDBInfo,
key: "exchange_data_cache_version",
)
as int? ??
0;
Future<void> _updateCurrentCacheVersion(int version) async {
await DB.instance.put<dynamic>(
boxName: DB.boxNameDBInfo,
key: "exchange_data_cache_version",
value: version,
);
}
Future<void> initDB() async {
if (_isar != null) return;
await _isar?.close();
_isar = await Isar.open(
[
CurrencySchema,
// PairSchema,
],
directory: (await StackFileSystem.applicationIsarDirectory()).path,
// inspector: kDebugMode,
inspector: false,
name: "exchange_cache",
maxSizeMiB: 64,
);
}
Future<void> setCurrenciesIfEmpty(
ActivePair? pair,
ExchangeRateType rateType,
) async {
if (pair?.send == null && pair?.receive == null) {
if (await isar.currencies.count() > 0) {
pair?.setSend(
await getAggregateCurrency(
AppConfig.swapDefaults.from,
AppConfig.swapDefaults.fromFuzzyNet,
rateType,
null,
),
notifyListeners: false,
);
pair?.setReceive(
await getAggregateCurrency(
AppConfig.swapDefaults.to,
AppConfig.swapDefaults.toFuzzyNet,
rateType,
null,
),
notifyListeners: false,
);
}
}
}
Future<AggregateCurrency?> getAggregateCurrency(
String ticker,
String fuzzyNet,
ExchangeRateType rateType,
String? contract,
) async {
final List<Currency> currencies;
if (contract != null) {
currencies =
await ExchangeDataLoadingService.instance.isar.currencies
.filter()
.tokenContractEqualTo(contract)
.and()
.group(
(q) =>
rateType == ExchangeRateType.fixed
? q
.rateTypeEqualTo(SupportedRateType.both)
.or()
.rateTypeEqualTo(SupportedRateType.fixed)
: q
.rateTypeEqualTo(SupportedRateType.both)
.or()
.rateTypeEqualTo(SupportedRateType.estimated),
)
.findAll();
} else {
currencies =
await ExchangeDataLoadingService.instance.isar.currencies
.filter()
.group(
(q) =>
rateType == ExchangeRateType.fixed
? q
.rateTypeEqualTo(SupportedRateType.both)
.or()
.rateTypeEqualTo(SupportedRateType.fixed)
: q
.rateTypeEqualTo(SupportedRateType.both)
.or()
.rateTypeEqualTo(SupportedRateType.estimated),
)
.and()
.tickerEqualTo(ticker, caseSensitive: false)
.and()
.tokenContractIsNull()
.findAll();
}
currencies.retainWhere((e) => e.getFuzzyNet() == fuzzyNet);
final items = currencies
.map((e) => Tuple2(e.exchangeName, e))
.toList(growable: false);
return items.isNotEmpty
? AggregateCurrency(exchangeCurrencyPairs: items)
: null;
}
bool get isLoading => _locked;
bool _locked = false;
Future<void> loadAll() async {
if (!_locked) {
_locked = true;
if (_isar == null) {
await initDB();
}
Logging.instance.d("ExchangeDataLoadingService.loadAll starting...");
final start = DateTime.now();
try {
/*
// Old exchange data loading code.
await Future.wait([
_loadChangeNowCurrencies(),
// _loadChangeNowFixedRatePairs(),
// _loadChangeNowEstimatedRatePairs(),
// loadSimpleswapFixedRateCurrencies(ref),
// loadSimpleswapFloatingRateCurrencies(ref),
loadMajesticBankCurrencies(),
loadTrocadorCurrencies(),
]);
// quicker to load available currencies on the fly for a specific base currency
// await _loadChangeNowFixedRatePairs();
// await _loadChangeNowEstimatedRatePairs();
*/
// Exchanges which support Tor just get treated normally.
final futures = [
// loadMajesticBankCurrencies(),
loadTrocadorCurrencies(),
loadNanswapCurrencies(),
];
// If using Tor, don't load data for exchanges which don't support Tor.
//
// Add to this list when adding an exchange which doesn't supports Tor.
if (!Prefs.instance.useTor) {
futures.add(_loadChangeNowCurrencies());
}
// wait for all loading futures to complete
await Future.wait(futures);
Logging.instance.d(
"ExchangeDataLoadingService.loadAll finished in ${DateTime.now().difference(start).inSeconds} seconds",
);
onLoadingComplete?.call();
await _updateCurrentCacheVersion(cacheVersion);
} catch (e, s) {
Logging.instance.e(
"ExchangeDataLoadingService.loadAll failed after ${DateTime.now().difference(start).inSeconds} seconds: ",
error: e,
stackTrace: s,
);
onLoadingError?.call();
}
_locked = false;
}
}
Future<void> _loadChangeNowCurrencies() async {
if (_isar == null) {
await initDB();
}
final exchange = ChangeNowExchange.instance;
final responseCurrencies = await exchange.getAllCurrencies(false);
if (responseCurrencies.value != null) {
await isar.writeTxn(() async {
final idsToDelete =
await isar.currencies
.where()
.exchangeNameEqualTo(ChangeNowExchange.exchangeName)
.idProperty()
.findAll();
await isar.currencies.deleteAll(idsToDelete);
await isar.currencies.putAll(responseCurrencies.value!);
});
} else {
Logging.instance.w(
"Failed to load changeNOW currencies: ${responseCurrencies.exception?.message}",
);
return;
}
}
// Future<void> _loadChangeNowFixedRatePairs() async {
// final exchange = ChangeNowExchange.instance;
//
// final responsePairs = await compute(exchange.getAllPairs, true);
//
// if (responsePairs.value != null) {
// await isar.writeTxn(() async {
// final idsToDelete2 = await isar.pairs
// .where()
// .exchangeNameEqualTo(ChangeNowExchange.exchangeName)
// .filter()
// .rateTypeEqualTo(SupportedRateType.fixed)
// .idProperty()
// .findAll();
// await isar.pairs.deleteAll(idsToDelete2);
// await isar.pairs.putAll(responsePairs.value!);
// });
// } else {
// Logging.instance.log(
// "Failed to load changeNOW available fixed rate pairs: ${responsePairs.exception?.message}",
// level: LogLevel.Error);
// return;
// }
// }
// Future<void> _loadChangeNowEstimatedRatePairs() async {
// final exchange = ChangeNowExchange.instance;
//
// final responsePairs = await compute(exchange.getAllPairs, false);
//
// if (responsePairs.value != null) {
// await isar.writeTxn(() async {
// final idsToDelete = await isar.pairs
// .where()
// .exchangeNameEqualTo(ChangeNowExchange.exchangeName)
// .filter()
// .rateTypeEqualTo(SupportedRateType.estimated)
// .idProperty()
// .findAll();
// await isar.pairs.deleteAll(idsToDelete);
// await isar.pairs.putAll(responsePairs.value!);
// });
// } else {
// Logging.instance.log(
// "Failed to load changeNOW available floating rate pairs: ${responsePairs.exception?.message}",
// level: LogLevel.Error);
// return;
// }
// }
//
// Future<void> loadSimpleswapFloatingRateCurrencies(WidgetRef ref) async {
// final exchange = SimpleSwapExchange();
// final responseCurrencies = await exchange.getAllCurrencies(false);
//
// if (responseCurrencies.value != null) {
// ref
// .read(availableSimpleswapCurrenciesProvider)
// .updateFloatingCurrencies(responseCurrencies.value!);
//
// final responsePairs = await exchange.getAllPairs(false);
//
// if (responsePairs.value != null) {
// ref
// .read(availableSimpleswapCurrenciesProvider)
// .updateFloatingPairs(responsePairs.value!);
// } else {
// Logging.instance.log(
// "loadSimpleswapFloatingRateCurrencies: $responsePairs",
// level: LogLevel.Warning,
// );
// }
// } else {
// Logging.instance.log(
// "loadSimpleswapFloatingRateCurrencies: $responseCurrencies",
// level: LogLevel.Warning,
// );
// }
// }
//
// Future<void> loadSimpleswapFixedRateCurrencies(WidgetRef ref) async {
// final exchange = SimpleSwapExchange();
// final responseCurrencies = await exchange.getAllCurrencies(true);
//
// if (responseCurrencies.value != null) {
// ref
// .read(availableSimpleswapCurrenciesProvider)
// .updateFixedCurrencies(responseCurrencies.value!);
//
// final responsePairs = await exchange.getAllPairs(true);
//
// if (responsePairs.value != null) {
// ref
// .read(availableSimpleswapCurrenciesProvider)
// .updateFixedPairs(responsePairs.value!);
// } else {
// Logging.instance.log(
// "loadSimpleswapFixedRateCurrencies: $responsePairs",
// level: LogLevel.Warning,
// );
// }
// } else {
// Logging.instance.log(
// "loadSimpleswapFixedRateCurrencies: $responseCurrencies",
// level: LogLevel.Warning,
// );
// }
// }
// Future<void> loadMajesticBankCurrencies() async {
// if (_isar == null) {
// await initDB();
// }
// final exchange = MajesticBankExchange.instance;
// final responseCurrencies = await exchange.getAllCurrencies(false);
//
// if (responseCurrencies.value != null) {
// await isar.writeTxn(() async {
// final idsToDelete =
// await isar.currencies
// .where()
// .exchangeNameEqualTo(MajesticBankExchange.exchangeName)
// .idProperty()
// .findAll();
// await isar.currencies.deleteAll(idsToDelete);
// await isar.currencies.putAll(responseCurrencies.value!);
// });
// } else {
// Logging.instance.w("loadMajesticBankCurrencies: $responseCurrencies");
// }
// }
Future<void> loadTrocadorCurrencies() async {
if (_isar == null) {
await initDB();
}
final exchange = TrocadorExchange.instance;
final responseCurrencies = await exchange.getAllCurrencies(false);
if (responseCurrencies.value != null) {
await isar.writeTxn(() async {
final idsToDelete =
await isar.currencies
.where()
.exchangeNameEqualTo(TrocadorExchange.exchangeName)
.idProperty()
.findAll();
await isar.currencies.deleteAll(idsToDelete);
await isar.currencies.putAll(responseCurrencies.value!);
});
} else {
Logging.instance.w("loadTrocadorCurrencies: $responseCurrencies");
}
}
Future<void> loadNanswapCurrencies() async {
if (_isar == null) {
await initDB();
}
final responseCurrencies = await NanswapExchange.instance.getAllCurrencies(
false,
);
if (responseCurrencies.value != null) {
await isar.writeTxn(() async {
final idsToDelete =
await isar.currencies
.where()
.exchangeNameEqualTo(NanswapExchange.exchangeName)
.idProperty()
.findAll();
await isar.currencies.deleteAll(idsToDelete);
await isar.currencies.putAll(responseCurrencies.value!);
});
} else {
Logging.instance.w("loadNanswapCurrencies: $responseCurrencies");
}
}
// Future<void> loadMajesticBankPairs() async {
// final exchange = MajesticBankExchange.instance;
//
// final responsePairs = await exchange.getAllPairs(false);
// if (responsePairs.value != null) {
// await isar.writeTxn(() async {
// final idsToDelete2 = await isar.pairs
// .where()
// .exchangeNameEqualTo(MajesticBankExchange.exchangeName)
// .idProperty()
// .findAll();
// await isar.pairs.deleteAll(idsToDelete2);
// await isar.pairs.putAll(responsePairs.value!);
// });
// } else {
// Logging.instance.log(
// "loadMajesticBankCurrencies: $responsePairs",
// level: LogLevel.Warning,
// );
// }
// }
}