Show each wallet's balance in USD

This commit is contained in:
2026-09-29 21:02:45 +08:00
parent 0b1b253d30
commit 58d862161e
4 changed files with 115 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
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.
final class PriceService {
static let shared = PriceService()
struct Prices: Codable {
var xrp: Double?
var xmr: Double?
var fetchedAt: Date?
}
private static let cacheLifetime: TimeInterval = 60
private var memory: Prices?
private var inFlight: Task<Prices, Never>?
private init() {}
func prices() async -> Prices {
if let memory, 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
}
inFlight = task
let result = await task.value
inFlight = nil
return result
}
private func fetch() async -> Prices {
if let prices = try? await fromCoinGecko() { return prices }
return (try? await fromKraken()) ?? Prices(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 {
throw XRPError.network("Invalid price endpoint")
}
let (data, response) = try await URLSession.shared.data(from: url)
guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
throw XRPError.network("CoinGecko request failed")
}
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 },
fetchedAt: Date())
}
private func fromKraken() async throws -> Prices {
guard let url = URL(string: "https://api.kraken.com/0/public/Ticker?pair=XRPUSD,XMRUSD") else {
throw XRPError.network("Invalid price endpoint")
}
let (data, response) = try await URLSession.shared.data(from: url)
guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
throw XRPError.network("Kraken request failed")
}
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] ?? [:]
let result = json["result"] as? [String: Any] ?? [:]
func lastTrade(_ key: String) -> Double? {
(result[key] as? [String: Any])
.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"),
fetchedAt: Date())
}
}