Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Persistence/SnapshotStore.swift3// Description: Offline snapshots: the last answers of read-only endpoints, kept as files in the app's sandbox container so that balances, addresses, history and NFT lists can be consulted without a connection — always shown with their date. Nothing secret is stored (no session, no key); files are excluded from backups.4import Foundation5import SPWalletCore67struct Snapshot<T: Sendable>: Sendable { let value: T; let savedAt: Date }89actor SnapshotStore {10 static let shared = SnapshotStore(directory: AppEnvironment.supportDirectory.appendingPathComponent("snapshots", isDirectory: true))11 private let directory: URL12 private struct Envelope<T: Codable>: Codable { let savedAt: Date; let value: T }1314 init(directory: URL) {15 self.directory = directory16 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)17 var d = directory; var v = URLResourceValues(); v.isExcludedFromBackup = true; try? d.setResourceValues(v)18 }1920 private func url(_ key: String) -> URL { directory.appendingPathComponent(key.replacingOccurrences(of: "/", with: "_") + ".json") }2122 func save<T: Codable & Sendable>(_ value: T, as key: String, at date: Date = Date()) {23 guard let data = try? APICoding.encoder().encode(Envelope(savedAt: date, value: value)) else { return }24 try? data.write(to: url(key), options: [.atomic, .completeFileProtection])25 }26 func load<T: Codable & Sendable>(_ key: String, as type: T.Type = T.self) -> Snapshot<T>? {27 guard let data = try? Data(contentsOf: url(key)), let e = try? APICoding.decoder().decode(Envelope<T>.self, from: data) else { return nil }28 return Snapshot(value: e.value, savedAt: e.savedAt)29 }30 /// Sign-out and "erase local data": everything this Mac remembered about the wallet goes.31 func eraseAll() {32 try? FileManager.default.removeItem(at: directory)33 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)34 }35}36