Repository Public
1// SP Wallet iOS2// File: Tests/NFTFlowTests.swift3// Description: Logic of the NFT section, through the REAL `NFTAPI` of SPWalletCore over the scripted fixture transport: media4// gating (active content is refused, a type that lies is refused), downsampling and the offline media cache,5// transfer request validation, the prepare → review → passkey → tracking flow and its refusals (an intent that6// is not the request, a challenge that is not the intent's hash, a lost answer, a cancelled passkey), the transfer7// verdict as served, the gallery model and its filters from fixtures, the protections.8// The fixtures are the Core's own (../SPWalletCore/Tests/SPWalletCoreTests/Fixtures/nft-*.json).9//10// Author: Simon-Pierre Boucher11// Contact: contact@spboucher.ai12import Foundation13import SwiftUI14import Testing15import UIKit16import SPWalletCore17@testable import SPWallet1819private final class StubPasskey: PasskeyAuthenticator, @unchecked Sendable {20 private let lock = NSLock()21 private var _asked: [PasskeyRequestOptions] = []22 var cancel = false23 var asked: [PasskeyRequestOptions] { lock.withLock { _asked } }24 func assert(_ options: PasskeyRequestOptions, rpId: String) async throws -> PasskeyAssertion {25 if cancel { throw PasskeyError.cancelled }26 lock.withLock { _asked.append(options) }27 return PasskeyAssertion(credentialId: Data("cred".utf8), clientDataJSON: Data("{}".utf8), authenticatorData: Data([1, 2, 3]), signature: Data([4, 5, 6]), userHandle: nil)28 }29 func register(_ options: PasskeyCreationOptions, rpId: String) async throws -> PasskeyRegistration { throw PasskeyError.notAvailable("stub") }30}3132@MainActor private func world() -> (NFTContext, NFTFixtureTransport) {33 let cfg = APIConfiguration(origin: URL(string: "https://wallet.example.test")!, rpId: "wallet.example.test", userAgent: "SPWalletTests")34 let t = NFTFixtureTransport(rpId: cfg.rpId)35 return (NFTFixtures.context(configuration: cfg, transport: t), t)36}3738private let destination = "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC"3940// MARK: - media4142@Suite struct NFTMediaGateTests {43 @Test func activeContentIsNeverAnImageOrAVideo() {44 #expect(NFTMediaGate.kind(mime: "text/html", kind: "html") == .activeContent)45 #expect(NFTMediaGate.kind(mime: "image/svg+xml", kind: "image") == .activeContent)46 #expect(NFTMediaGate.kind(mime: nil, kind: "html") == .activeContent)47 #expect(NFTMediaGate.kind(mime: "IMAGE/SVG+XML", kind: "image") == .activeContent)48 #expect(NFTMediaGate.kind(mime: "application/xhtml+xml", kind: "unknown") == .activeContent)49 }5051 @Test func onlyTheServedRasterAndMP4TypesAreShown() {52 for m in ["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"] { #expect(NFTMediaGate.kind(mime: m, kind: "image") == .image) }53 #expect(NFTMediaGate.kind(mime: "video/mp4", kind: "video") == .video)54 #expect(NFTMediaGate.kind(mime: "video/webm", kind: "video") == .unplayableVideo)55 #expect(NFTMediaGate.kind(mime: "audio/mpeg", kind: "audio") == .audio)56 #expect(NFTMediaGate.kind(mime: "model/gltf-binary", kind: "model") == .model)57 #expect(NFTMediaGate.kind(mime: "application/pdf", kind: "image") == .unknown)58 #expect(NFTMediaGate.kind(mime: nil, kind: "image") == .image)59 #expect(NFTMediaGate.kind(mime: nil, kind: "something-new") == .unknown)60 // every kind that is not an image or a playable video has a tile that says so61 for k in [NFTMediaKind.unplayableVideo, .audio, .activeContent, .model, .unknown] { #expect(NFTMediaText.tile(for: k) != nil) }62 #expect(NFTMediaText.tile(for: .activeContent)?.text == "Contenu actif non affiché")63 }6465 @Test func bytesAreRecognisedBySignatureAndMarkupIsFlagged() {66 #expect(NFTMediaGate.sniff(NFTFixtures.png(seed: "a", side: 32)) == "image/png")67 #expect(NFTMediaGate.sniff(Data([0xFF, 0xD8, 0xFF, 0xE0, 0, 0])) == "image/jpeg")68 #expect(NFTMediaGate.sniff(Data("GIF89a....".utf8)) == "image/gif")69 #expect(NFTMediaGate.sniff(Data("RIFF\u{0}\u{0}\u{0}\u{0}WEBPVP8 ".utf8)) == "image/webp")70 #expect(NFTMediaGate.sniff(Data([0, 0, 0, 0x1C]) + Data("ftypavif\u{0}\u{0}\u{0}\u{0}avifmif1".utf8)) == "image/avif")71 #expect(NFTMediaGate.sniff(Data([0, 0, 0, 0x18]) + Data("ftypisom\u{0}\u{0}\u{0}\u{0}isommp42".utf8)) == "video/mp4")72 #expect(NFTMediaGate.sniff(Data("<svg xmlns='http://www.w3.org/2000/svg'><script/></svg>".utf8)) == "text/html")73 #expect(NFTMediaGate.sniff(Data([0xEF, 0xBB, 0xBF]) + Data(" \n<!doctype html>".utf8)) == "text/html")74 #expect(NFTMediaGate.sniff(Data("plain text".utf8)) == nil)75 #expect(NFTMediaGate.looksLikeMarkup(Data("\n\t <html>".utf8)))76 #expect(!NFTMediaGate.looksLikeMarkup(NFTFixtures.png(seed: "a", side: 16)))77 }7879 @Test @MainActor func servedContentIsCheckedAgainstItsBytes() async throws {80 let (ctx, t) = world()81 // a real PNG, announced as PNG82 #expect(NFTMediaGate.refuseAsImage(try await ctx.api.media(id: NFTFixtures.apeImage)) == nil)83 // an SVG with a script, served as SVG by the proxy: active content, whatever its role84 let svg = try await ctx.api.media(id: NFTFixtures.svgImage)85 #expect(svg.isActiveContent && NFTMediaGate.refuseAsImage(svg) == .activeContent && NFTMediaGate.refuseAsVideo(svg) == .activeContent)86 // markup announced as a PNG: refused as active content, never handed to a decoder87 t.mediaOverride[NFTFixtures.passImage] = (Data("<svg onload=alert(1)>".utf8), "image/png")88 #expect(NFTMediaGate.refuseAsImage(try await ctx.api.media(id: NFTFixtures.passImage)) == .activeContent)89 // a JPEG announced as a PNG: the type lies90 t.mediaOverride[NFTFixtures.passImage] = (Data([0xFF, 0xD8, 0xFF, 0xE0, 0, 0, 0, 0]), "image/png")91 #expect(NFTMediaGate.refuseAsImage(try await ctx.api.media(id: NFTFixtures.passImage)) == .typeMismatch)92 // HTML is in the proxy's list (the web shows it sandboxed); here it is refused both ways93 t.mediaOverride[NFTFixtures.passImage] = (Data("<html><script>1</script></html>".utf8), "text/html; charset=utf-8")94 let html = try await ctx.api.media(id: NFTFixtures.passImage)95 #expect(NFTMediaGate.refuseAsImage(html) == .activeContent && NFTMediaGate.refuseAsVideo(html) == .activeContent)96 // an image is not a video; bytes that are not an MP4 are not played97 #expect(NFTMediaGate.refuseAsVideo(try await ctx.api.media(id: NFTFixtures.apeImage)) == .notAPlayableVideo)98 t.mediaOverride[NFTFixtures.passImage] = (NFTFixtures.png(seed: "x", side: 16), "video/mp4")99 #expect(NFTMediaGate.refuseAsVideo(try await ctx.api.media(id: NFTFixtures.passImage)) == .typeMismatch)100 t.mediaOverride[NFTFixtures.passImage] = (Data([0, 0, 0, 0x18]) + Data("ftypisom\u{0}\u{0}\u{0}\u{0}isommp42".utf8), "video/mp4")101 #expect(NFTMediaGate.refuseAsVideo(try await ctx.api.media(id: NFTFixtures.passImage)) == nil)102 // a type outside the proxy's allow-list never reaches the gate: the Core refuses it103 t.mediaOverride[NFTFixtures.passImage] = (Data("%PDF-1.7".utf8), "application/pdf")104 await #expect(throws: APIError.self) { _ = try await ctx.api.media(id: NFTFixtures.passImage) }105 // and a URL is never a media id106 await #expect(throws: APIError.self) { _ = try await ctx.api.media(id: "https://evil.example/x.png") }107 }108109 @Test func imagesAreDownsampledAndReencoded() throws {110 let big = NFTFixtures.png(seed: "big", side: 1200)111 let out = try NFTImageCodec.downsample(big, maxPixel: 300).get()112 #expect(max(out.pixelWidth, out.pixelHeight) == 300)113 #expect(out.encoded.count < big.count)114 // what is cached is this app's own re-encoding (opaque → JPEG), and it decodes back115 #expect(NFTMediaGate.sniff(out.encoded) == "image/jpeg")116 #expect(NFTImageCodec.decodeCached(out.encoded) != nil)117 // never upscaled beyond the request, never fed markup or garbage118 let small = try NFTImageCodec.downsample(NFTFixtures.png(seed: "s", side: 64), maxPixel: 480).get()119 #expect(small.pixelWidth <= 480)120 #expect(throws: NFTMediaRefusal.activeContent) { _ = try NFTImageCodec.downsample(Data("<svg/>".utf8), maxPixel: 300).get() }121 #expect(throws: NFTMediaRefusal.undecodable) { _ = try NFTImageCodec.downsample(Data([1, 2, 3, 4, 5, 6, 7, 8]), maxPixel: 300).get() }122 }123124 @Test @MainActor func theMediaCacheServesOfflineWhatWasSeenOnlineAndNothingElse() async throws {125 let (ctx, t) = world()126 let proxied = { t.requests.filter { $0.path.hasPrefix("/nfts/media/") }.count }127 guard case .success(let first) = await ctx.media.image(id: NFTFixtures.apeImage, size: .thumb, online: true) else { Issue.record("image not loaded"); return }128 #expect(max(first.size.width, first.size.height) <= 480)129 #expect(proxied() == 1)130 _ = await ctx.media.image(id: NFTFixtures.apeImage, size: .thumb, online: true)131 #expect(proxied() == 1, "a cached image is not requested again")132 #expect(await ctx.media.cachedBytes() > 0)133134 // offline: what was seen is still there, what was not is said as such — and no request leaves135 t.offline = true136 if case .failure = await ctx.media.image(id: NFTFixtures.apeImage, size: .thumb, online: false) { Issue.record("cached image lost offline") }137 #expect(await ctx.media.image(id: NFTFixtures.passImage, size: .thumb, online: false).failureValue == .notCachedOffline)138 #expect(proxied() == 1)139 t.offline = false140141 // a later launch (a new store over the same directory, no memory) still finds it on disk, without network142 let dir2 = FileManager.default.temporaryDirectory.appendingPathComponent("nft-media-test-\(UUID().uuidString)")143 _ = await NFTContext.mediaStore(ctx.api, directory: dir2).image(id: NFTFixtures.passImage, size: .full, online: true)144 t.offline = true145 let relaunched = NFTContext.mediaStore(ctx.api, directory: dir2)146 if case .failure = await relaunched.image(id: NFTFixtures.passImage, size: .full, online: false) { Issue.record("image not found on disk after relaunch") }147 #expect(await relaunched.image(id: NFTFixtures.passImage, size: .thumb, online: false).failureValue == .notCachedOffline, "another size was never cached")148 t.offline = false149 await relaunched.wipe()150151 // active content and refusals are never cached152 #expect(await ctx.media.image(id: NFTFixtures.svgImage, size: .thumb, online: true).failureValue == .refused(.activeContent))153 #expect(await ctx.media.image(id: NFTFixtures.svgImage, size: .thumb, online: false).failureValue == .notCachedOffline)154 #expect(await ctx.media.image(id: NFTFixtures.unreachableImage, size: .thumb, online: true).failureValue == .server(code: "media_unreachable", reason: "timeout"))155156 // a video larger than the cap is not downloaded for playback; a temporary video file is removed after use157 #expect(await ctx.media.videoFile(id: NFTFixtures.bigVideo).failureValue == .tooLarge(bytes: nil))158 guard case .success(let info) = await ctx.media.describe(id: NFTFixtures.bigVideo) else { Issue.record("no media info"); return }159 #expect(info.mime == "video/mp4" && (info.bytes ?? 0) > NFTMediaGate.maxVideoBytes)160 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nft-video-test-\(UUID().uuidString)")161 let file = try NFTMediaStore.writeVideo(Data([0, 0, 0, 0x18]) + Data("ftypisom".utf8), in: dir)162 #expect(FileManager.default.fileExists(atPath: file.path) && file.pathExtension == "mp4")163 NFTMediaStore.removeVideo(file)164 #expect(!FileManager.default.fileExists(atPath: file.path))165 try? FileManager.default.removeItem(at: dir)166167 await ctx.media.wipe()168 #expect(await ctx.media.cachedBytes() == 0)169 #expect(await ctx.media.image(id: NFTFixtures.apeImage, size: .thumb, online: false).failureValue == .notCachedOffline)170 }171172 @Test func aLinkIsOnlyEverAPlainWebURL() {173 #expect(NFTLinks.safe("javascript:alert(1)") == nil)174 #expect(NFTLinks.safe("data:text/html,<script>1</script>") == nil)175 #expect(NFTLinks.safe("ipfs://QmImage") == nil)176 #expect(NFTLinks.safe("https://user:pass@evil.example/") == nil)177 #expect(NFTLinks.safe("https://pass.example.org/saison-2?ref=nft")?.host == "pass.example.org")178 }179}180181private extension Result {182 var failureValue: Failure? { if case .failure(let f) = self { return f } else { return nil } }183}184185// MARK: - transfer186187@Suite @MainActor struct NFTTransferFlowTests {188 private func item(_ key: String, _ ctx: NFTContext) async throws -> NFTAsset { try await ctx.api.item(key: key) }189190 @Test func quantityIsValidatedBeforeAnyRequest() {191 typealias M = NFTTransferModel192 #expect(M.quantityProblem("5", held: "12", multi: true) == nil)193 #expect(M.quantityProblem("12", held: "12", multi: true) == nil)194 #expect(M.quantityProblem("13", held: "12", multi: true) == .aboveHeld)195 #expect(M.quantityProblem("0", held: "12", multi: true) == .zero)196 #expect(M.quantityProblem("007", held: "12", multi: true) == .zero)197 for bad in ["", "1.5", "-1", "1e3", "abc", "12"] { #expect(M.quantityProblem(bad, held: "12", multi: true) == .notAWholeNumber, "\(bad)") }198 // beyond 64 bits: compared exactly, never through a float199 #expect(M.quantityProblem("340282366920938463463374607431768211457", held: "340282366920938463463374607431768211456", multi: true) == .aboveHeld)200 #expect(M.quantityProblem("340282366920938463463374607431768211456", held: "340282366920938463463374607431768211456", multi: true) == nil)201 // every other standard moves exactly one unit, whatever was typed202 #expect(M.quantityProblem("99", held: "1", multi: false) == nil)203 }204205 @Test func theRequestIsBuiltFromTheItemAndRefusedForAStandardWithoutTransfer() async throws {206 let (ctx, _) = world()207 let ape = NFTTransferModel(item: try await item(NFTFixtures.apeKey, ctx))208 #expect(try ape.request() == nil, "no destination yet")209 ape.to = " \(destination)\n"; ape.quantity = "40"210 let r = try #require(try ape.request())211 #expect(r.key == NFTFixtures.apeKey && r.standard == .erc721 && r.to == destination && r.quantity == "1" && r.from == NFTFixtures.owner)212213 let pass = NFTTransferModel(item: try await item(NFTFixtures.passKey, ctx))214 pass.to = destination; pass.quantity = "5"215 #expect(try pass.request()?.quantity == "5" && pass.isMulti)216 pass.quantity = "13"217 #expect(try pass.request() == nil && pass.quantityProblem == .aboveHeld)218219 // a compressed NFT has no transfer: no request can exist for it220 let spam = NFTTransferModel(item: try await item(NFTFixtures.spamKey, ctx))221 spam.to = destination222 #expect(throws: ApprovalError.self) { _ = try spam.request() }223 }224225 @Test func fromTheFormToTheChainThroughTheVerifiedIntentAndThePasskey() async throws {226 let (ctx, t) = world(), passkey = StubPasskey()227 let m = NFTTransferModel(item: try await item(NFTFixtures.passKey, ctx))228 m.to = destination; m.quantity = "5"229 await m.prepare(ctx.api)230 #expect(m.error == nil && m.step == .review)231 let a = try #require(m.approval)232 // what is reviewed is the intent the Core verified: it is the request, and the challenge is its hash233 #expect(a.intent.network == "base" && a.intent.standard == .erc1155 && a.intent.tokenId == "42" && a.intent.quantity == "5")234 #expect(a.intent.asset.lowercased() == "0x495f947276749ce646f68ac8c248420045cb7b5e" && a.intent.to == destination && a.intent.from == NFTFixtures.owner)235 #expect(a.approval.digest == (try a.intent.approvalDigest()) && a.approval.options.challengeData == a.approval.digest)236 #expect(a.review?.simulation.ok == true && a.review?.fee.max == a.intent.maxFee && a.review?.warnings.contains("semi_fungible") == true)237238 // nothing is asked of the passkey before the owner confirmed the destination239 await m.approve(ctx.api, passkeys: passkey)240 #expect(m.step == .review && passkey.asked.isEmpty)241 // a dismissed passkey sheet is not an error and signs nothing242 m.acknowledged = true; passkey.cancel = true243 await m.approve(ctx.api, passkeys: passkey)244 #expect(m.step == .review && m.error == nil && m.submitted == nil)245246 passkey.cancel = false247 await m.approve(ctx.api, passkeys: passkey)248 #expect(m.step == .tracking && passkey.asked.count == 1 && passkey.asked[0].challengeData == a.approval.digest)249 // approved is not sent: only the chain's finality is a success250 #expect(m.submitted?.state == .broadcast && m.submitted?.state.isSuccess == false)251 #expect(await m.refreshStatus(ctx.api) == false && m.submitted?.state == .confirming)252 // the inventory still holds every unit until the chain finalized253 #expect(try await ctx.api.list().items.first { $0.key == NFTFixtures.passKey }?.quantity == "12")254 #expect(await m.refreshStatus(ctx.api) == true && m.submitted?.state == .finalized)255 // …and then it is the SERVER's inventory that says what is left256 #expect(try await ctx.api.list().items.first { $0.key == NFTFixtures.passKey }?.quantity == "7")257 #expect(t.requests.filter { $0.path.hasSuffix("/approve") }.count == 1)258 }259260 @Test func anERC721LeavesTheGalleryOnlyWhenTheServerInventorySaysSo() async throws {261 let (ctx, _) = world(), passkey = StubPasskey()262 let gallery = NFTGalleryModel()263 await gallery.load(ctx, online: true)264 #expect(gallery.items.contains { $0.key == NFTFixtures.apeKey })265 let m = NFTTransferModel(item: try await item(NFTFixtures.apeKey, ctx))266 m.to = destination267 await m.prepare(ctx.api); m.acknowledged = true268 await m.approve(ctx.api, passkeys: passkey)269 #expect(m.step == .tracking)270 await gallery.load(ctx, online: true)271 #expect(gallery.items.contains { $0.key == NFTFixtures.apeKey }, "broadcast: still in the inventory")272 _ = await m.refreshStatus(ctx.api)273 #expect(await m.refreshStatus(ctx.api))274 await gallery.load(ctx, online: true)275 #expect(!gallery.items.contains { $0.key == NFTFixtures.apeKey })276 #expect(try await ctx.api.item(key: NFTFixtures.apeKey).transfer?.blockedBy == ["not_in_wallet"])277 }278279 @Test func aServerRefusalStopsBeforeAnyReviewAndIsSaidWithItsCode() async throws {280 let (ctx, _) = world()281 let m = NFTTransferModel(item: try await item(NFTFixtures.apeKey, ctx))282 m.to = NFTFixtures.refusedDestination283 await m.prepare(ctx.api)284 #expect(m.step == .form && m.approval == nil)285 let e = try #require(m.error as? APIError)286 #expect(e.code == "nft_transfer_policy_not_allowlisted")287 #expect(NFTText.transferRefusal(e)?.contains("liste blanche") == true)288 #expect(NFTText.errorMessage(e).detail.contains("nft_transfer_policy_not_allowlisted"))289 // a code this version does not know is not paraphrased: the server's sentence and code are shown290 let unknown = APIError(status: 422, code: "nft_transfer_something_new", message: "a new rule of the server")291 #expect(NFTText.transferRefusal(unknown) == nil)292 #expect(NFTText.errorMessage(unknown).detail == "a new rule of the server (nft_transfer_something_new)")293 }294295 @Test func anIntentThatIsNotTheRequestOrAChallengeThatIsNotItsHashCanNeverBeApproved() async throws {296 let cases: [(String, @Sendable (JSONValue) -> JSONValue)] = [297 ("destination", { $0.setting(["intent", "to"], "0x90F79bf6EB2c4f870365E785982E1f101E93b906") }),298 ("quantity", { $0.setting(["intent", "quantity"], "12") }),299 ("token id", { $0.setting(["intent", "tokenId"], "43") }),300 ("contract", { $0.setting(["intent", "asset"], "0x90F79bf6EB2c4f870365E785982E1f101E93b906").setting(["intent", "program"], "0x90F79bf6EB2c4f870365E785982E1f101E93b906") }),301 ("challenge", { $0.setting(["options", "challenge"], .string(Data(repeating: 7, count: 32).base64URL)) }),302 ("relying party", { $0.setting(["options", "rpId"], "evil.example") }),303 ("review", { $0.setting(["review", "to"], "0x90F79bf6EB2c4f870365E785982E1f101E93b906") }),304 ("unknown field", { $0.setting(["intent", "extra"], "1") }),305 ]306 for (name, tamper) in cases {307 let (ctx, t) = world(), passkey = StubPasskey()308 t.mutateAnswer = { r, j in r.path == "/nfts/transfer/prepare" ? tamper(j) : j }309 let m = NFTTransferModel(item: try await ctx.api.item(key: NFTFixtures.passKey))310 m.to = destination; m.quantity = "5"311 await m.prepare(ctx.api)312 #expect(m.step == .form && m.approval == nil && m.error != nil, "\(name): nothing to review")313 #expect(!(m.error is PasskeyError), "\(name)")314 m.acknowledged = true315 await m.approve(ctx.api, passkeys: passkey)316 #expect(passkey.asked.isEmpty && t.requests.allSatisfy { !$0.path.hasSuffix("/approve") }, "\(name): nothing reaches the passkey or the signer")317 }318 }319320 @Test func aLostAnswerIsFollowedByReadingTheStateNeverByASecondSignature() async throws {321 let (ctx, t) = world(), passkey = StubPasskey()322 let m = NFTTransferModel(item: try await item(NFTFixtures.apeKey, ctx))323 m.to = destination324 await m.prepare(ctx.api); m.acknowledged = true325 t.loseNextApproveAnswer = true326 await m.approve(ctx.api, passkeys: passkey)327 #expect(m.step == .tracking && m.submitted?.state.isInFlight == true, "the server had accepted it: the app follows it")328 #expect(passkey.asked.count == 1)329330 // the preparation's own answer lost: the same key is reused, so the server answers the same proposal331 let (ctx2, t2) = world()332 let m2 = NFTTransferModel(item: try await ctx2.api.item(key: NFTFixtures.apeKey))333 m2.to = destination334 await m2.prepare(ctx2.api)335 let firstId = try #require(m2.approval?.transfer.id)336 m2.step = .form; m2.approval = nil337 await m2.prepare(ctx2.api)338 #expect(m2.approval?.transfer.id == firstId && m2.approval?.replayed == true)339 #expect(t2.requests.filter { $0.path == "/nfts/transfer/prepare" }.count == 2)340341 // refusing gives the proposal back to the server and clears the review342 await m2.reject(ctx2.api)343 #expect(m2.step == .form && m2.approval == nil)344 #expect(try await ctx2.api.transfer(id: firstId).state == .rejected)345 }346347 @Test func theVerdictIsShownAsServedWithItsExactReasons() async throws {348 let (ctx, _) = world()349 let ape = try await ctx.api.transferVerdict(key: NFTFixtures.apeKey)350 #expect(ape.transferable && ape.blockedBy.isEmpty && ape.route == NFTTransferStandard.erc721.method && ape.signer.supportsNft == true)351 let pnft = try await item(NFTFixtures.pnftKey, ctx)352 #expect(pnft.transfer?.transferable == false && pnft.transfer?.blockedBy == ["pnft_locked"] && pnft.collection?.verifiedOnChain == .known(false))353 #expect(NFTText.transferBlock("pnft_locked").contains("VERROUILLÉ"))354 let spam = try await item(NFTFixtures.spamKey, ctx)355 #expect(spam.transfer?.blockedBy == ["compressed_transfer_not_supported"] && spam.standard.transferStandard == nil && spam.spamFlaggedBy == "solana-das")356 // every block reason the backend documents has its own sentence; an unknown one is shown verbatim357 for code in ["not_in_wallet", "burned", "frozen", "pnft_locked", "pnft_listed", "delegated", "soulbound", "compressed_transfer_not_supported", "escrow", "unsupported_standard",358 "ownership_unknown", "ownership_single_source", "ordinals_transfer_not_supported", "token2022_extension_unsupported", "source_not_associated_account", "network_disabled_by_policy"] {359 #expect(!NFTText.transferBlock(code).contains(code), "\(code) has a sentence")360 }361 #expect(NFTText.transferBlock("brand_new_reason") == "Motif : brand_new_reason")362 // a collection is qualified by the chain only — never by its name363 #expect(NFTText.collectionVerification(.known(true)).1 == .ok)364 #expect(NFTText.collectionVerification(.known(false)).1 == .warn && NFTText.collectionVerification(pnft.collection?.verifiedOnChain).0.contains("NON vérifiée"))365 #expect(NFTText.collectionVerification(.unsupported).1 == .neutral && NFTText.collectionVerification(nil).0 == "Sans collection déclarée")366 }367}368369// MARK: - gallery, lookup, market, protections370371@Suite @MainActor struct NFTGalleryModelTests {372 @Test func theGalleryIsTheServerInventoryWithItsCapabilityMatrix() async throws {373 let (ctx, _) = world()374 let g = NFTGalleryModel()375 await g.load(ctx, online: true)376 #expect(g.live && g.error == nil)377 #expect(Set(g.visible.map(\.key)) == [NFTFixtures.apeKey, NFTFixtures.passKey, NFTFixtures.svgKey, NFTFixtures.pnftKey])378 #expect(g.page?.hiddenSpam == 1 && g.page?.valuation?.state == "unavailable")379 // what is not read is known: Ethereum has no automatic discovery, Solana is partial — never "nothing there"380 #expect(g.unreadChains.map(\.network).sorted() == ["bitcoin", "ethereum", "solana"])381 #expect(g.caps.value?.chain("ethereum")?.reason == "no_keyless_discovery" && g.caps.value?.chain("ethereum")?.manualAdd == true)382 #expect(g.caps.value?.anyMarketWrite == false)383 #expect(g.collections.value?.count == 4)384385 g.filter.showSpam = true386 await g.load(ctx, online: true)387 #expect(g.visible.count == 5 && g.visible.first { $0.key == NFTFixtures.spamKey }?.spam?.by == "solana-das")388 g.filter.showSpam = false; g.filter.chain = "solana"389 await g.load(ctx, online: true)390 #expect(g.visible.map(\.key) == [NFTFixtures.pnftKey])391 g.filter.chain = nil; g.filter.search = "pass"392 await g.load(ctx, online: true)393 #expect(g.visible.map(\.key) == [NFTFixtures.passKey])394 // the standard filter is local: it narrows what is loaded without a request395 g.filter.search = ""; await g.load(ctx, online: true)396 g.filter.standard = .erc1155397 #expect(g.visible.map(\.key) == [NFTFixtures.passKey])398 g.filter.standard = .metaplexCore399 #expect(g.visible.isEmpty && g.filter.hasNarrowing)400 }401402 @Test func offlineTheDatedSnapshotIsShownAndFilteredLocally() async throws {403 let (ctx, t) = world()404 let online = NFTGalleryModel()405 await online.load(ctx, online: true)406 let before = t.requests.count407408 t.offline = true409 let g = NFTGalleryModel()410 await g.load(ctx, online: false)411 #expect(!g.live && g.savedAt != nil && g.items.count == 4 && g.caps.isCached && g.caps.value != nil)412 #expect(t.requests.count == before, "no request leaves offline")413 g.filter.chain = "ethereum"414 #expect(Set(g.visible.map(\.key)) == [NFTFixtures.apeKey, NFTFixtures.svgKey])415 g.filter.chain = nil; g.filter.search = "LAD"416 #expect(g.visible.map(\.key) == [NFTFixtures.pnftKey])417418 // the server stops answering mid-session: the error is kept, the items become the dated snapshot again419 let h = NFTGalleryModel()420 t.offline = false; await h.load(ctx, online: true)421 t.offline = true; await h.load(ctx, online: true)422 #expect(!h.live && (h.error as? APIError)?.isOffline == true && h.items.count == 4)423424 // a filtered answer is never kept as the offline inventory425 t.offline = false426 let f = NFTGalleryModel(); f.filter.chain = "solana"427 await f.load(ctx, online: true)428 let again = NFTGalleryModel()429 await again.load(ctx, online: false)430 #expect(again.items.count == 4)431 }432433 @Test func aFilterNeverDropsOrInventsItems() throws {434 let list = try NFTFixtures.decode(NFTList.self, NFTFixtureData.list)435 var f = NFTGalleryFilter()436 #expect(f.isDefault && !f.hasNarrowing)437 // the offline snapshot: spam hidden unless asked, search on names and identifiers438 #expect(f.apply(list.items, serverFiltered: false).map(\.name) == ["Ape #8520"])439 f.showSpam = true440 #expect(f.apply(list.items, serverFiltered: false).count == 2)441 f.search = "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d"442 #expect(f.apply(list.items, serverFiltered: false).count == 1)443 f.search = "nothing-matches"444 #expect(f.apply(list.items, serverFiltered: false).isEmpty)445 // the server already answered the query: only the standard is applied locally446 #expect(f.apply(list.items, serverFiltered: true).count == 2)447 f.standard = .metaplexBubblegum448 #expect(f.apply(list.items, serverFiltered: true).map(\.onchainName) == ["FREE AIRDROP"])449 #expect(f.query().search == "nothing-matches" && f.query().spam == .show && f.query().status == .inWallet)450 f.search = String(repeating: "a", count: 200)451 #expect(f.query().search?.count == 80)452 }453454 @Test func aLookupReferenceIsCheckedBeforeAnyRequest() async throws {455 typealias F = NFTLookupForm456 let contract = "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D"457 #expect(try F.reference(chain: "ethereum", family: "evm", address: " \(contract) ", tokenId: "8520").get() == NFTReference(chain: "ethereum", address: contract, tokenId: "8520"))458 #expect(try F.reference(chain: "ethereum", family: "evm", address: contract, tokenId: "0x2148").get().tokenId == "0x2148")459 #expect(F.reference(chain: "ethereum", family: "evm", address: contract, tokenId: "").failureValue == .tokenIdRequired)460 #expect(F.reference(chain: "ethereum", family: "evm", address: contract, tokenId: "12.5").failureValue == .tokenId)461 #expect(F.reference(chain: "ethereum", family: "evm", address: "https://opensea.io/item/1", tokenId: "1").failureValue == .address)462 #expect(F.reference(chain: "ethereum", family: "evm", address: "CMhGwGHMbVaBmxebfU3t5eViSf6FKHnvFCBNiA1D659j", tokenId: "1").failureValue == .address)463 #expect(try F.reference(chain: "solana", family: "sol", address: "CMhGwGHMbVaBmxebfU3t5eViSf6FKHnvFCBNiA1D659j", tokenId: "ignored").get().tokenId == nil)464465 // a lookup is a READ: the asset is shown as the chain says, including "not in this wallet"466 let (ctx, _) = world()467 let found = try await ctx.api.lookup(NFTReference(chain: "solana", address: "CMhGwGHMbVaBmxebfU3t5eViSf6FKHnvFCBNiA1D659j"))468 #expect(found.origin == "lookup" && found.ownership.state == "not_in_wallet" && found.capabilities.transferBlockedBy == ["not_in_wallet"])469 do { _ = try await ctx.api.lookup(NFTReference(chain: "ethereum", address: "0x2222222222222222222222222222222222222222", tokenId: "1")); Issue.record("expected a refusal") }470 catch let e as APIError { #expect(NFTText.readError(e) == "Introuvable sur ce réseau — aucun contrat à cette adresse") }471 }472473 @Test func marketDataIsReadOnlyAndNeverAValue() async throws {474 let (ctx, _) = world()475 let m = try await ctx.api.market(key: NFTFixtures.apeKey)476 #expect(!m.anyActionAvailable && m.actions.count == 7 && m.value?.state == "unavailable")477 #expect(m.actions.allSatisfy { !NFTText.marketAction($0.id).isEmpty && $0.reason == "market_writes_not_built" })478 let ok = try #require(m.sources.first { $0.status.isOK })479 // each figure keeps its source and its date; a stale row says so480 #expect(ok.status.fetchedAt != nil && ok.status.stale && NFTMarketText.stamp(ok.status) != nil)481 #expect(NFTMarketText.known(ok.ask) { NFTMarketText.price($0.price) }.contains("ETH"))482 let off = try #require(m.sources.first { !$0.status.isOK })483 #expect(NFTMarketText.known(off.ask) { NFTMarketText.price($0.price) } == "non établi par la source")484 // the floor estimate is off until the owner turns it on, and stays out of the wallet total either way485 let before = try await ctx.api.floorEstimate()486 #expect(!before.enabled && before.estimate == nil && before.excludedFromWalletTotal)487 _ = try await ctx.api.setFloorEstimate(enabled: true)488 let after = try await ctx.api.floorEstimate()489 #expect(after.enabled && after.state == "unavailable" && after.excludedFromWalletTotal && after.estimate?.indicativeUsd == "378.90")490 }491492 @Test func protectionsArePreparedVerifiedAndApprovedByThePasskey() async throws {493 let (ctx, t) = world(), passkey = StubPasskey()494 #expect(try await ctx.api.allowList().entries.count == 1)495 let add = try await ctx.api.prepareAllowChange(NFTAllowRequest(network: "base", address: destination, action: .add))496 #expect(add.intent.action == .add && add.intent.network == "base" && add.intent.address == destination)497 let pending = NFTProtectionPending.allow(add)498 #expect(pending.digest == (try add.intent.approvalDigest()) && pending.id == pending.digest.hex)499 let r = try await ctx.api.approveAllowChange(add, with: passkey)500 #expect(r.entries == 2 && r.hash == pending.digest.hex && passkey.asked.last?.challengeData == pending.digest)501502 // an allow-list intent for another address than the one asked is refused before any passkey prompt503 t.mutateAnswer = { rec, j in rec.path == "/nfts/allow/prepare" ? j.setting(["intent", "address"], "0x90F79bf6EB2c4f870365E785982E1f101E93b906") : j }504 await #expect(throws: ApprovalError.self) { _ = try await ctx.api.prepareAllowChange(NFTAllowRequest(network: "base", address: destination, action: .remove)) }505 t.mutateAnswer = nil506507 let view = try await ctx.api.utxoLocks(network: "bitcoin")508 let small = try #require(view.utxos.first { $0.signerLock != nil }), big = try #require(view.utxos.first { $0.signerLock == nil })509 #expect(!small.spendable && big.spendable && NFTProtections.unprotectedByOrd(view).isEmpty)510 #expect(NFTProtections.lockReason(for: small) == .heuristic && NFTProtections.lockReason(for: big) == .owner)511 #expect(!NFTProtections.canDeclareOrdinary(small) && !NFTProtections.canDeclareOrdinary(big))512 let unlock = try await ctx.api.prepareUTXOLocks(UTXOLockRequest(network: "bitcoin", action: .unlock, reason: .owner, outpoints: [small.outpoint]))513 #expect(unlock.intent.outpoints.map(\.key) == [small.outpoint])514 let done = try await ctx.api.approveUTXOLocks(unlock, with: passkey)515 #expect(done.changed == 1 && passkey.asked.count == 2)516 // unlocked, the small output is still held back by the heuristic — and only now can it be declared ordinary (no passkey)517 let after = try #require(try await ctx.api.utxoLocks(network: "bitcoin").utxos.first { $0.outpoint == small.outpoint })518 #expect(after.signerLock == nil && !after.spendable && NFTProtections.canDeclareOrdinary(after))519 _ = try await ctx.api.reviewUTXO(network: "bitcoin", outpoint: small.outpoint, ordinary: true)520 #expect(try await ctx.api.utxoLocks(network: "bitcoin").utxos.first { $0.outpoint == small.outpoint }?.spendable == true)521 #expect(passkey.asked.count == 2)522 }523524 @Test func wordsForCodesNeverHideAnUnknownCode() {525 #expect(NFTText.standard(.erc1155) == "ERC-1155" && NFTText.standard(NFTStandard(rawValue: "future-standard")) == "Standard : future-standard")526 #expect(NFTText.inventoryReason("sections_blocked:compressed").contains("points d’accès publics"))527 #expect(NFTText.inventoryReason("no_keyless_discovery").contains("Découverte automatique non configurée"))528 #expect(NFTText.inventoryReason("new_reason") == "État : new_reason")529 #expect(NFTText.known(NFTKnown<String>.unknown(reason: nil)) { $0 } == "non établi" && NFTText.known(NFTKnown<String>.none) { $0 } == "aucun")530 #expect(NFTText.known(NFTKnown<String>.unsupported) { $0 } == "sans objet pour ce standard" && NFTText.known(NFTKnown<String>.known("0")) { $0 } == "0")531 #expect(NFTText.ownership("held_by_aliens").0 == "État : held_by_aliens")532 #expect(NFTText.marketWhy("market_writes_not_built").contains("ne signe") && NFTText.marketWhy("zzz") == "Indisponible (code : zzz).")533 #expect(NFTMediaText.tile(status: "blocked", errorCode: "private_address")?.text.contains("réseau privé") == true && NFTMediaText.tile(status: "available", errorCode: nil) == nil)534 }535}536537// MARK: - layout (rendered off-screen at tablet size: the assigned simulator is a phone)538539@Suite @MainActor struct NFTLayoutTests {540 @Test func theRegularWidthLayoutPutsTheGridAndTheItemSideBySide() async throws {541 let (ctx, _) = world()542 let cfg = AppConfiguration(api: APIConfiguration(origin: URL(string: "http://localhost:1")!, rpId: "localhost", userAgent: "SPWalletTests"), appGroup: "group.test", devStackDirectory: nil, ephemeral: true)543 let model = AppModel(env: AppEnvironment(configuration: cfg))544 model.phase = .ready545 #expect(model.canOperate)546 let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)547 for (name, dark) in [("light", false), ("dark", true)] {548 let root = NavigationStack { NFTGalleryScreen(ctx: ctx, initialSelection: NFTFixtures.passKey).navigationTitle("NFT") }549 .environment(\.horizontalSizeClass, .regular).wallet(model)550 let host = UIHostingController(rootView: root)551 let window = UIWindow(windowScene: scene)552 window.frame = CGRect(x: 0, y: 0, width: 1024, height: 768)553 window.overrideUserInterfaceStyle = dark ? .dark : .light554 window.rootViewController = host555 window.isHidden = false556 try await Task.sleep(for: .seconds(3))557 let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) }558 let url = URL(fileURLWithPath: "/tmp/nft-layout-regular-\(name).png")559 try image.pngData()?.write(to: url)560 #expect(FileManager.default.fileExists(atPath: url.path))561 window.isHidden = true562 }563 }564}565