Repository Public
1// SP Wallet iOS2// File: Features/NFTs/NFTStore.swift3// Description: State of the NFT section: the context shared by its screens (the domain API, the media cache, the snapshots) and4// the gallery model (inventory as the server stores it, capability matrix, collections, filters, synchronisation).5// The gallery shows what the server's inventory says — an item appears or leaves only when that inventory does.6// Offline, the last synchronized inventory is shown, dated, and nothing can be started.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Observation12import SPWalletCore1314@MainActor @Observable15final class NFTContext {16 let api: NFTAPI17 let media: NFTMediaStore18 let cache: AppCache19 /** DEBUG fixture mode only: the screens are fed by bundled test answers and say so on every screen. Always false in release. */20 let isFixture: Bool21 /** Bumped when the server's inventory may have changed (finalized transfer, tracking, synchronisation): the gallery reloads. */22 var revision = 02324 init(api: NFTAPI, media: NFTMediaStore, cache: AppCache, isFixture: Bool = false) {25 self.api = api; self.media = media; self.cache = cache; self.isFixture = isFixture26 }2728 static func make(_ env: AppEnvironment) -> NFTContext {29 #if DEBUG30 if ProcessInfo.processInfo.environment["SPWALLET_NFT_FIXTURES"] == "1" { return NFTFixtures.context(configuration: env.configuration.api) }31 #endif32 let api = NFTAPI(env.client)33 let directory: URL34 if env.configuration.ephemeral {35 directory = FileManager.default.temporaryDirectory.appendingPathComponent("nft-media-ephemeral", isDirectory: true)36 try? FileManager.default.removeItem(at: directory)37 } else {38 // inside the app's offline directory: the sign-out wipe of `AppCache.removeAll()` erases it with the snapshots39 directory = AppCache.defaultDirectory().appendingPathComponent(env.configuration.isProduction ? "prod" : "dev", isDirectory: true)40 .appendingPathComponent("nft-media", isDirectory: true)41 }42 return NFTContext(api: api, media: mediaStore(api, directory: directory), cache: env.cache)43 }4445 static func mediaStore(_ api: NFTAPI, directory: URL) -> NFTMediaStore {46 NFTMediaStore(directory: directory, fetch: { id, max in try await api.media(id: id, maxBytes: max) }, info: { try await api.mediaInfo(id: $0) })47 }48}4950/** The filters of the gallery. Chain, collection, state, search and spam are the server's; the standard is applied on what is loaded. */51struct NFTGalleryFilter: Hashable, Sendable {52 enum Status: String, CaseIterable, Sendable, Identifiable { case inWallet, tracked, left53 var id: String { rawValue }54 var query: NFTListQuery.Status { switch self { case .inWallet: .inWallet; case .tracked: .tracked; case .left: .left } }55 }56 var status: Status = .inWallet57 var chain: String?58 var collection: String?59 var standard: NFTStandard?60 var search = ""61 var showSpam = false6263 var trimmedSearch: String { String(search.trimmingCharacters(in: .whitespacesAndNewlines).prefix(80)) }64 /** The unfiltered inventory: the only answer kept as the offline snapshot. */65 var isDefault: Bool { status == .inWallet && chain == nil && collection == nil && trimmedSearch.isEmpty && !showSpam }66 var hasNarrowing: Bool { chain != nil || collection != nil || standard != nil || !trimmedSearch.isEmpty }6768 func query(cursor: Int? = nil, limit: Int = 60) -> NFTListQuery {69 NFTListQuery(chain: chain, collection: collection, status: status.query, search: trimmedSearch.isEmpty ? nil : trimmedSearch,70 sort: .recent, spam: showSpam ? .show : .hide, cursor: cursor, limit: limit)71 }7273 /**74 Local application. `serverFiltered`: the items are the server's answer to `query()` — only the standard remains to apply.75 Otherwise (offline snapshot of the default inventory) chain, collection and search are applied here too.76 */77 func apply(_ items: [NFTSummary], serverFiltered: Bool) -> [NFTSummary] {78 let needle = trimmedSearch.lowercased()79 return items.filter { i in80 if let standard, i.standard != standard { return false }81 if serverFiltered { return true }82 if let chain, i.chain != chain { return false }83 if let collection, i.collection?.key != collection { return false }84 if !showSpam, i.spam != nil { return false }85 if needle.isEmpty { return true }86 return [i.name, i.onchainName, i.collection?.name, i.assetId, i.tokenId, i.key].contains { $0?.lowercased().contains(needle) == true }87 }88 }89}9091@MainActor @Observable92final class NFTGalleryModel {93 var filter = NFTGalleryFilter()94 /** Items of the server's answer(s) to the current filter, pages appended. */95 var items: [NFTSummary] = []96 /** The last page's envelope: total, hidden spam, cursor, sync state, valuation state. */97 var page: NFTList?98 var savedAt: Date?99 /** True when `items` is the server's answer to the current filter from this session. */100 var live = false101 var caps = Loaded<NFTCapabilities>()102 var collections = Loaded<[NFTCollectionCount]>()103 var loading = false104 var loadingMore = false105 var error: Error?106 var syncing = false107 var syncError: Error?108 private var generation = 0109110 var visible: [NFTSummary] { filter.apply(items, serverFiltered: live) }111 var standards: [NFTStandard] { Array(Set(items.map(\.standard))).sorted { $0.rawValue < $1.rawValue } }112 var chains: [String] { Array(Set((caps.value?.chains.filter { $0.inventory != "unsupported" }.map(\.network) ?? []) + items.map(\.chain))).sorted() }113 var isSyncRunning: Bool { syncing || !(page?.sync?.running.isEmpty ?? true) }114 /** Networks whose inventory is not fully read: said on the gallery, so that "empty" is never read as "owns nothing". */115 var unreadChains: [NFTChainCapability] { (caps.value?.chains ?? []).filter { $0.inventory == "partial" || $0.inventory == "blocked_by_provider" } }116117 func load(_ ctx: NFTContext, online: Bool) async {118 generation += 1119 let mine = generation, f = filter120 if items.isEmpty, caps.value == nil { await loadSnapshots(ctx) }121 guard online else { live = false; return }122 loading = true; error = nil123 defer { if mine == generation { loading = false } }124 async let c = Result.catching { try await ctx.api.capabilities() }125 async let cols = Result.catching { try await ctx.api.collections() }126 async let l = Result.catching { try await ctx.api.list(f.query()) }127 let (rc, rcols, rl) = await (c, cols, l)128 guard mine == generation else { return }129 if case .success(let v) = rc { caps.set(live: v); await ctx.cache.save(v, key: "nft.capabilities") } else if case .failure(let e as APIError) = rc { caps.fail(e) }130 if case .success(let v) = rcols { collections.set(live: v); await ctx.cache.save(v, key: "nft.collections") } else if case .failure(let e as APIError) = rcols { collections.fail(e) }131 switch rl {132 case .success(let v):133 items = v.items; page = v; live = true; savedAt = Date()134 if f.isDefault { await ctx.cache.save(v, key: "nft.list") }135 case .failure(let e):136 if e is CancellationError { return }137 error = e138 // the server did not answer: what is shown is the dated snapshot, never presented as the answer to this filter139 if live { live = false; await loadSnapshots(ctx, force: true) }140 }141 }142143 private func loadSnapshots(_ ctx: NFTContext, force: Bool = false) async {144 if let c = await ctx.cache.load(NFTCapabilities.self, key: "nft.capabilities"), caps.value == nil || force { caps.set(cached: c) }145 if let c = await ctx.cache.load([NFTCollectionCount].self, key: "nft.collections"), collections.value == nil || force { collections.set(cached: c) }146 if let c = await ctx.cache.load(NFTList.self, key: "nft.list"), items.isEmpty || force { items = c.value.items; page = c.value; savedAt = c.savedAt; live = false }147 }148149 func loadMore(_ ctx: NFTContext) async {150 guard live, !loadingMore, let cursor = page?.cursor else { return }151 loadingMore = true152 defer { loadingMore = false }153 let mine = generation154 do {155 let next = try await ctx.api.list(filter.query(cursor: cursor))156 guard mine == generation else { return }157 let known = Set(items.map(\.key))158 items += next.items.filter { !known.contains($0.key) }159 page = next160 } catch { self.error = error }161 }162163 /** Ask the server to re-read the chains, then follow its own `sync.running` until it is done. Never infers an arrival. */164 func sync(_ ctx: NFTContext, chain: String? = nil) async {165 guard !syncing else { return }166 syncing = true; syncError = nil167 defer { syncing = false }168 do {169 _ = try await ctx.api.sync(chain: chain)170 for _ in 0..<20 {171 try await Task.sleep(for: .seconds(ctx.isFixture ? 0.2 : 3))172 await load(ctx, online: true)173 if page?.sync?.running.isEmpty ?? true { break }174 }175 } catch is CancellationError {176 } catch { syncError = error }177 }178}179180extension Result where Failure == Error {181 static func catching(_ body: @Sendable () async throws -> Success) async -> Result<Success, Error> {182 do { return .success(try await body()) } catch { return .failure(error) }183 }184}185