Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/DeFi/MarketsSnapshot.swift10// Description : One read with its offline fallback, for the Markets and11// Risk screens: the server's answer is decoded into the Core12// model AND kept as a dated snapshot (the JSON exactly as13// served) under a `markets-` / `risk-` cache key. Offline,14// or when the read fails, the last snapshot is shown —15// marked as such, never as live. Secrets never pass through16// here.17// Module : Features18// Repository : https://git.spboucher.ai/sp-wallet-ios19// Created : 2026-11-1820// Last Modified : 2026-11-1821//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import Foundation95import SPWalletCore9697enum SnapshotRead {98 /**99 GET `path` (a route on which the Core API performs no check beyond decoding), decode it as `T`, save the served JSON under `key`.100 - Returns: the slot to display: live, or the last snapshot with the error of this attempt.101 */102 @MainActor103 static func read<T: Decodable & Sendable>(_ type: T.Type = T.self, path: String, query: [String: String?] = [:], key: String?, app: AppModel, current: Loaded<T>) async -> Loaded<T> {104 precondition(key.map { $0.hasPrefix("markets-") || $0.hasPrefix("risk-") } ?? true)105 var slot = current106 func fallBack() async {107 guard slot.value == nil, let key, let c = await app.env.cache.load(JSONValue.self, key: key), let v = try? c.value.decode(T.self) else { return }108 slot.set(cached: Cached(value: v, savedAt: c.savedAt))109 }110 if app.offlineBrowsing { await fallBack(); slot.live = false; return slot }111 do {112 let json: JSONValue = try await app.env.client.get(path, query: query)113 let value: T114 do { value = try json.decode(T.self) } catch { throw APIError(status: 200, code: "decoding", message: "unexpected answer from the server for \(path)") }115 slot.set(live: value)116 if let key { await app.env.cache.save(json, key: key) }117 } catch let e as APIError {118 slot.fail(e)119 await fallBack()120 } catch {121 slot.fail(APIError(status: 0, code: "client", message: error.localizedDescription))122 await fallBack()123 }124 return slot125 }126}127128/** Display helpers shared by the Markets and Risk screens. Formatting never changes a value sent to the server. */129enum Fmt {130 /** A USD decimal string as served, grouped for reading; nil reads « indisponible ». */131 static func usd(_ s: String?) -> String { s.map { Money.exact($0) + " USD" } ?? String(localized: "indisponible") }132 /** Large USD figures in lists (volume, open interest): compact, from a decimal string. */133 static func usdCompact(_ s: String?) -> String? {134 guard let s, let v = Double(s) else { return nil }135 return v.formatted(.currency(code: "USD").notation(.compactName).precision(.fractionLength(0...2)))136 }137 /** A price in USD from the source's decimal string; the digits shown depend on the magnitude. */138 static func price(_ s: String?) -> String? {139 guard let s, let v = Double(s) else { return nil }140 return Money.price(v, .usd)141 }142 /** A FRACTION as served (0.0123 = 1.23 %) as a signed percentage with its arrow. */143 static func fractionChange(_ s: String?) -> (text: String, up: Bool)? {144 guard let s, let v = Double(s), let t = Money.change(v * 100) else { return nil }145 return (t, v >= 0)146 }147 /** A rate fraction as a percentage with enough digits for funding rates. */148 static func ratePercent(_ s: String?, digits: Int = 4) -> String? {149 guard let s, let v = Double(s) else { return nil }150 return (v * 100).formatted(.number.precision(.fractionLength(digits))) + " %"151 }152 static func age(ms: Int?) -> String? {153 guard let ms else { return nil }154 let s = max(0, ms) / 1000155 if s < 60 { return "\(s) s" }156 if s < 3600 { return "\(s / 60) min" }157 if s < 172_800 { return "\(s / 3600) h" }158 return String(localized: "\(s / 86_400) j")159 }160 static func date(ms: Int?) -> String? { ms.map { Date(timeIntervalSince1970: TimeInterval($0) / 1000).formatted(date: .abbreviated, time: .standard) } }161}162