Give each Monero account a swipeable card with its balance and QR
This commit is contained in:
@@ -1,34 +1,49 @@
|
||||
import Foundation
|
||||
|
||||
/// USD prices for the two tickers the wallet supports, fetched from a public
|
||||
/// price API and cached briefly so a screen does not fetch on every refresh.
|
||||
/// Fiat prices for the two tickers the wallet supports, fetched from a public
|
||||
/// price API. Cached briefly in memory and in UserDefaults so screens do not
|
||||
/// refetch on every refresh, and so the currency conversion shows up instantly
|
||||
/// on a cold start.
|
||||
final class PriceService {
|
||||
static let shared = PriceService()
|
||||
|
||||
struct Prices: Codable {
|
||||
var xrp: Double?
|
||||
var xmr: Double?
|
||||
var currency: String
|
||||
var fetchedAt: Date?
|
||||
}
|
||||
|
||||
private static let cacheLifetime: TimeInterval = 60
|
||||
private static let defaultsKey = "koins.prices"
|
||||
|
||||
private var memory: Prices?
|
||||
private var inFlight: Task<Prices, Never>?
|
||||
|
||||
private init() {}
|
||||
private init() {
|
||||
if let data = UserDefaults.standard.data(forKey: Self.defaultsKey),
|
||||
let saved = try? JSONDecoder().decode(Prices.self, from: data) {
|
||||
memory = saved
|
||||
}
|
||||
}
|
||||
|
||||
func prices() async -> Prices {
|
||||
if let memory, let fetchedAt = memory.fetchedAt,
|
||||
func prices(currency: String) async -> Prices {
|
||||
if let memory,
|
||||
memory.currency == currency,
|
||||
let fetchedAt = memory.fetchedAt,
|
||||
Date().timeIntervalSince(fetchedAt) < Self.cacheLifetime {
|
||||
return memory
|
||||
}
|
||||
if let inFlight { return await inFlight.value }
|
||||
|
||||
let task = Task<Prices, Never> { [weak self] in
|
||||
guard let self else { return Prices(fetchedAt: nil) }
|
||||
let prices = await self.fetch()
|
||||
self.memory = prices
|
||||
return prices
|
||||
guard let self else { return Prices(currency: currency, fetchedAt: nil) }
|
||||
let fetched = await self.fetch(currency: currency)
|
||||
self.memory = fetched
|
||||
if let data = try? JSONEncoder().encode(fetched) {
|
||||
UserDefaults.standard.set(data, forKey: Self.defaultsKey)
|
||||
}
|
||||
return fetched
|
||||
}
|
||||
inFlight = task
|
||||
let result = await task.value
|
||||
@@ -36,13 +51,14 @@ final class PriceService {
|
||||
return result
|
||||
}
|
||||
|
||||
private func fetch() async -> Prices {
|
||||
if let prices = try? await fromCoinGecko() { return prices }
|
||||
return (try? await fromKraken()) ?? Prices(fetchedAt: nil)
|
||||
private func fetch(currency: String) async -> Prices {
|
||||
if let prices = try? await fromCoinGecko(currency: currency) { return prices }
|
||||
return (try? await fromKraken(currency: currency)) ?? Prices(currency: currency, fetchedAt: nil)
|
||||
}
|
||||
|
||||
private func fromCoinGecko() async throws -> Prices {
|
||||
guard let url = URL(string: "https://api.coingecko.com/api/v3/simple/price?ids=monero,ripple&vs_currencies=usd") else {
|
||||
private func fromCoinGecko(currency: String) async throws -> Prices {
|
||||
let code = currency.lowercased()
|
||||
guard let url = URL(string: "https://api.coingecko.com/api/v3/simple/price?ids=monero,ripple&vs_currencies=\(code)") else {
|
||||
throw XRPError.network("Invalid price endpoint")
|
||||
}
|
||||
let (data, response) = try await URLSession.shared.data(from: url)
|
||||
@@ -51,13 +67,23 @@ final class PriceService {
|
||||
}
|
||||
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] ?? [:]
|
||||
return Prices(
|
||||
xrp: (json["ripple"] as? [String: Any]).flatMap { ($0["usd"] as? NSNumber)?.doubleValue },
|
||||
xmr: (json["monero"] as? [String: Any]).flatMap { ($0["usd"] as? NSNumber)?.doubleValue },
|
||||
xrp: (json["ripple"] as? [String: Any]).flatMap { ($0[code] as? NSNumber)?.doubleValue },
|
||||
xmr: (json["monero"] as? [String: Any]).flatMap { ($0[code] as? NSNumber)?.doubleValue },
|
||||
currency: currency,
|
||||
fetchedAt: Date())
|
||||
}
|
||||
|
||||
private func fromKraken() async throws -> Prices {
|
||||
guard let url = URL(string: "https://api.kraken.com/0/public/Ticker?pair=XRPUSD,XMRUSD") else {
|
||||
/// Kraken only lists USD and EUR for both assets; anything else just yields
|
||||
/// no price rather than a wrong one.
|
||||
private func fromKraken(currency: String) async throws -> Prices {
|
||||
let supported: [String: (xrp: String, xmr: String)] = [
|
||||
"USD": ("XXRPZUSD", "XXMRZUSD"),
|
||||
"EUR": ("XXRPZEUR", "XXMRZEUR"),
|
||||
]
|
||||
guard let pairs = supported[currency] else {
|
||||
throw XRPError.network("Kraken has no \(currency) pairs")
|
||||
}
|
||||
guard let url = URL(string: "https://api.kraken.com/0/public/Ticker?pair=\(pairs.xrp),\(pairs.xmr)") else {
|
||||
throw XRPError.network("Invalid price endpoint")
|
||||
}
|
||||
let (data, response) = try await URLSession.shared.data(from: url)
|
||||
@@ -72,8 +98,9 @@ final class PriceService {
|
||||
.flatMap { entry in (entry["c"] as? [Any])?.first }
|
||||
.flatMap { ($0 as? String).flatMap(Double.init) }
|
||||
}
|
||||
return Prices(xrp: lastTrade("XXRPZUSD") ?? lastTrade("XRPUSD"),
|
||||
xmr: lastTrade("XXMRZUSD") ?? lastTrade("XMRUSD"),
|
||||
return Prices(xrp: lastTrade(pairs.xrp),
|
||||
xmr: lastTrade(pairs.xmr),
|
||||
currency: currency,
|
||||
fetchedAt: Date())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user