import "package:hash_wallet/entities/fiat_currency.dart"; import "package:hash_wallet/new-ui/model/charts/datetime_extension.dart"; import "package:cw_core/amount/money.dart"; import "package:cw_core/crypto_currency.dart"; import "package:cw_core/currency.dart"; import "package:cw_core/db/sqlite.dart"; import "package:sqflite/sqflite.dart"; Currency currencyFromApiString(String key) { final parts = key.split("."); final type = parts[0]; final id = parts[1]; switch (type) { case "fiat": return FiatCurrency.deserialize(raw: id); case "crypto": return CryptoCurrency.fromString(id); case "evm": throw UnimplementedError(); case "sol": throw UnimplementedError(); } throw Exception("unknown api string"); } class PriceData implements Comparable { const PriceData({required this.time, required this.base, required this.quote,}); factory PriceData.fromJson(Map json) => PriceData( time: DateTimeX.fromSecondsSinceEpoch(json["timestamp"] as int), base: currencyFromApiString(json["fromCurrency"] as String), quote: Money.parse( json["price"] as String, currencyFromApiString(json["toCurrency"] as String), strictParsing: false), ); final DateTime time; final Currency base; final Money quote; static const tableName = "PriceData"; Map toJson() => { "timestamp": time.secondsSinceEpoch.toString(), "price": quote.toString(), "fromCurrency": base.apiString, "toCurrency": quote.currency.apiString, }; static Future> get( Currency from, Currency to, DateTime? start, DateTime? end, ) async { final json = await db!.query( tableName, where: "fromCurrency = ? AND toCurrency = ? AND timestamp >= ? AND timestamp <= ?", whereArgs: [ from.apiString, to.apiString, start?.secondsSinceEpoch ?? 0, // dart doesn't have INT_MAX, apparently. end?.secondsSinceEpoch ?? 0x7FFFFFFFFFFFFFFF, ], ); return List.generate(json.length, (index) => PriceData.fromJson(json[index])); } Future insert() async { await db!.insert(tableName, toJson(), conflictAlgorithm: ConflictAlgorithm.replace); } static Future insertMany(Iterable data) async { if (data.isEmpty) { return; } final batch = db!.batch(); for (final datum in data) { batch.insert( tableName, datum.toJson(), conflictAlgorithm: ConflictAlgorithm.replace, ); } await batch.commit(noResult: true); } @override bool operator ==(Object other) => other is PriceData && time == other.time && base == other.base && quote.currency == other.quote.currency; @override int get hashCode => Object.hash(time, base, quote.currency); @override int compareTo(PriceData other) => time.compareTo(other.time); }