Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/NFT/NFTModels.swift3// Description: Models of the NFT read API (services/api/src/nft/routes.ts, service.ts; canonical model v1 of packages/nft/src/model.ts):4// capability matrix, inventory, item page, events, collections, receive addresses, media proxy answers. Every integer5// that comes from a chain is a decimal string; "unknown", "not applicable", "none" and a value are four different6// states (`NFTKnown`); every external value carries the stamp of its source. Creator metadata is UNTRUSTED remote7// content: it is kept as data, shown as text, and nothing here fetches or executes any of it.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213/**14 A value whose absence has a meaning (`Known<T>`). `unknown`: could not be established. `unsupported`: the standard has no such15 notion. `none`: established as absent. Zero and `false` are values. A state this version does not know stays `unrecognized` and16 is never read as a value.17 */18public enum NFTKnown<Value: Codable & Sendable & Hashable>: Codable, Sendable, Hashable {19 case known(Value)20 case none21 case unknown(reason: String?)22 case unsupported23 case unrecognized(String)2425 private enum CodingKeys: String, CodingKey { case state, value, reason }2627 public init(from decoder: Decoder) throws {28 let c = try decoder.container(keyedBy: CodingKeys.self)29 let state = try c.decode(String.self, forKey: .state)30 switch state {31 case "known": self = .known(try c.decode(Value.self, forKey: .value))32 case "none": self = .none33 case "unknown": self = .unknown(reason: try c.decodeIfPresent(String.self, forKey: .reason))34 case "unsupported": self = .unsupported35 default: self = .unrecognized(state)36 }37 }38 public func encode(to encoder: Encoder) throws {39 var c = encoder.container(keyedBy: CodingKeys.self)40 switch self {41 case .known(let v): try c.encode("known", forKey: .state); try c.encode(v, forKey: .value)42 case .none: try c.encode("none", forKey: .state)43 case .unknown(let reason): try c.encode("unknown", forKey: .state); try c.encodeIfPresent(reason, forKey: .reason)44 case .unsupported: try c.encode("unsupported", forKey: .state)45 case .unrecognized(let s): try c.encode(s, forKey: .state)46 }47 }48 /** The value when it is known; nil in every other state (never a default). */49 public var value: Value? { if case .known(let v) = self { return v } else { return nil } }50 public var isKnown: Bool { value != nil }51}5253/** A token standard as the server names it. Unknown names are kept verbatim. */54public struct NFTStandard: RawRepresentable, Codable, Sendable, Hashable, CustomStringConvertible {55 public let rawValue: String56 public init(rawValue: String) { self.rawValue = rawValue }57 public init(from decoder: Decoder) throws { rawValue = try decoder.singleValueContainer().decode(String.self) }58 public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }59 public var description: String { rawValue }6061 public static let erc721 = NFTStandard(rawValue: "erc721")62 public static let erc1155 = NFTStandard(rawValue: "erc1155")63 /** Answers some NFT calls but does not declare / satisfy ERC-721 or ERC-1155: listed, never transferable. */64 public static let evmNonstandard = NFTStandard(rawValue: "evm-nonstandard")65 public static let metaplexTokenMetadata = NFTStandard(rawValue: "metaplex-token-metadata")66 /** Programmable NFT: moved only through the Token Metadata program. */67 public static let metaplexPNFT = NFTStandard(rawValue: "metaplex-pnft")68 public static let metaplexCore = NFTStandard(rawValue: "metaplex-core")69 /** Compressed NFT: listed through an indexer only, not transferable by this wallet. */70 public static let metaplexBubblegum = NFTStandard(rawValue: "metaplex-bubblegum")71 public static let splToken2022 = NFTStandard(rawValue: "spl-token-2022")72 /** SPL mint with supply 1 and no Metaplex metadata: listed, not transferable as an NFT. */73 public static let splToken = NFTStandard(rawValue: "spl-token")74 /** Bitcoin inscription: not listed and not transferable in this version. */75 public static let ordinalsInscription = NFTStandard(rawValue: "ordinals-inscription")76 public static let unknown = NFTStandard(rawValue: "unknown")7778 /** The standard a transfer can be built for, or nil (compressed, inscriptions, non-standard contracts, plain SPL, unknown names). */79 public var transferStandard: NFTTransferStandard? { NFTTransferStandard(rawValue: rawValue) }80}8182public struct NFTBlockRef: Codable, Sendable, Hashable {83 public let number: String?84 public let hash: String?85 public let slot: String?86 public let commitment: String?87}8889/** Where a value comes from. The five categories are never merged: a value has exactly one. */90public struct NFTSourceStamp: Codable, Sendable, Hashable {91 /** `onchain`, `creator_metadata`, `indexed`, `market`, `computed`. */92 public let category: String93 /** Stable identifier of the source: `solana-rpc`, `solana-das`, `evm-rpc`, `metadata-uri`, `magiceden`, `opensea`, `spw`… */94 public let source: String95 /** What the source is, for a reader (a host or a name; never a URL with a key). */96 public let detail: String97 /** When the server obtained the value. */98 public let fetchedAt: Date99 public let blockRef: NFTBlockRef?100 /** `chain_verified`, `chain_single_source`, `indexer_reported`, `creator_declared`, `market_reported`, `computed`. */101 public let confidence: String102 /** `fresh`, `stale`, `unknown` — decided by the server when the asset is read. */103 public let freshness: String104 public let covers: [String]105106 public var isStale: Bool { freshness == "stale" }107 /** True only for what this server read from the chain on every endpoint. */108 public var isChainVerified: Bool { category == "onchain" && confidence == "chain_verified" }109}110111public struct NFTCurrency: Codable, Sendable, Hashable {112 public let network: String113 /** `native` or the exact mint / contract. A symbol proves nothing: the currency is identified by network + asset. */114 public let asset: String115 public let symbol: String116 public let decimals: Int117 /** `network:asset` with EVM contracts lower-cased (`currencyId`): the key of the `rates` maps. */118 public var id: String { "\(network):\(asset.hasPrefix("0x") ? asset.lowercased() : asset)" }119}120121/** An amount in base units of an exactly identified currency, as a market source or the chain reported it. */122public struct NFTAmount: Codable, Sendable, Hashable {123 public let amount: String124 public let currency: NFTCurrency125 /** Only on a reported last sale: the time the source gives, as it gives it. */126 public let at: String?127 public var units: BaseUnits? { try? BaseUnits(amount) }128 /** Exact decimal text of the amount in its own currency. */129 public var display: String? { units.map { $0.formatted(decimals: currency.decimals) } }130}131132public struct NFTCollectionRef: Codable, Sendable, Hashable {133 /** `family:chainId:collectionId`. */134 public let key: String135 public let id: String136 /** Solana: the `verified` flag of the on-chain collection field. EVM: unsupported (a contract is its own collection). */137 public let verifiedOnChain: NFTKnown<Bool>138 /** Name declared by the collection's own metadata (creator-declared, UNTRUSTED text); never copied from an item. */139 public let name: String?140 public let source: NFTSourceStamp?141}142143/** One entry of the creator's `attributes`. UNTRUSTED: text to display, never markup, never a link to follow. */144public struct NFTAttribute: Codable, Sendable, Hashable {145 /** Exactly what the metadata contained for this entry. */146 public let raw: JSONValue?147 public let traitType: String?148 /** The value as given: a string, a number, a boolean or null. */149 public let value: JSONValue?150 public let valueText: String151 public let displayType: String?152 public let maxValue: String?153 /** True when the entry was not an object with a value (kept and shown, flagged). */154 public let malformed: Bool155}156157public struct NFTTraitStatistics: Codable, Sendable, Hashable {158 /** Always false here: no rarity is computed without a denominator (see `NFTAPI.traitFrequency`). */159 public let computed: Bool160 public let reason: String161}162163/**164 What the CREATOR declared (plus the on-chain name / symbol). Everything creator-declared is UNTRUSTED remote content: `name`,165 `description`, `externalUrl`, `attributes` and `raw` are data to display as plain text. No URL found here is ever requested by the166 client: media goes through `NFTAPI.media(id:)` (the server's proxy), and `externalUrl` may only be offered as a link the owner167 opens deliberately, outside the app (`safeExternalURL`).168 */169public struct NFTMetadata: Codable, Sendable, Hashable {170 /** `ok`, `missing`, `no_uri`, `blocked`, `unreachable`, `malformed`, `too_large`, `not_loaded`. */171 public let status: String172 /** Code of the refusal / failure when the status is not `ok` (`scheme_not_allowed`, `private_address`, …). */173 public let errorCode: String?174 /** UNTRUSTED. The URI exactly as the chain / contract gives it. Shown as text; never fetched by the client. */175 public let sourceUri: String?176 /** UNTRUSTED. What the server actually requested (gateway applied). Shown as text; never fetched by the client. */177 public let resolvedUri: String?178 /** Chain data (Solana metadata account / Core asset), not creator JSON. */179 public let onchainName: String?180 public let onchainSymbol: String?181 public let name: String?182 public let description: String?183 /** UNTRUSTED link declared by the creator. */184 public let externalUrl: String?185 public let attributes: [NFTAttribute]186 /** UNTRUSTED. The JSON document as fetched (bounded in size and depth). Fields such as `animation_url` stay inert strings here. */187 public let raw: JSONValue?188 /** SHA-256 of the bytes fetched, hex. */189 public let contentHash: String?190 public let mutable: NFTKnown<Bool>191 public let traitStatistics: NFTTraitStatistics?192 public let source: NFTSourceStamp?193194 /** The creator's link when it is a plain http(s) URL without credentials (`safeLink` of the web client); nil for javascript:, data:, … */195 public var safeExternalURL: URL? { NFTLinks.safe(externalUrl) }196}197198/**199 One media file named by the metadata (`image`, `animation_url`, `properties.files`). The client never loads `sourceUri` or200 `resolvedUri`: the bytes come from the server's proxy by the opaque `id` (`NFTAPI.media(id:)`), sniffed and type-checked there.201 */202public struct NFTMedia: Codable, Sendable, Hashable, Identifiable {203 /** `image`, `animation`, `file`. */204 public let role: String205 /** Opaque id of the media proxy (`m` + 40 hex digits). */206 public let id: String207 /** UNTRUSTED. The creator's URI (e.g. the document's `animation_url`), kept as text. Never fetched by the client, never executed. */208 public let sourceUri: String209 /** UNTRUSTED. Shown as text only. */210 public let resolvedUri: String?211 /** The type the metadata announced: a hint, never trusted for rendering. */212 public let declaredMime: String?213 /** Sniffed from the bytes by the server once fetched. */214 public let mime: String?215 /** `image`, `video`, `audio`, `html`, `model`, `unknown`. */216 public let kind: String217 /** `available`, `not_fetched`, `blocked`, `unreachable`, `unsupported_type`, `too_large`. */218 public let status: String219 public let errorCode: String?220 public let bytes: String?221222 /** HTML and SVG are documents that can carry script: a native client shows them as inert placeholders or rasterizes SVG without scripting, never in a JavaScript-enabled web view. */223 public var isActiveContent: Bool { kind == "html" || mime == "text/html" || mime == "image/svg+xml" }224}225226public struct NFTOwnership: Codable, Sendable, Hashable {227 /** `in_wallet`, `not_in_wallet`, `escrow_or_delegated`, `burned`, `unknown`. */228 public let state: String229 /** The address the chain names as holder. */230 public let owner: NFTKnown<String>231 public let tokenAccount: NFTKnown<String>232 public let frozen: NFTKnown<Bool>233 public let delegate: NFTKnown<String>234 /** pNFT token record state: `unlocked`, `locked`, `listed`. */235 public let tokenRecordState: NFTKnown<String>236 /** True when the chain's holder is one of the wallet's own addresses on this chain. */237 public let heldByWallet: Bool238 public let source: NFTSourceStamp239}240241/** The at-most-one market snapshot stored with the item (delivery 1). A marketplace's statement, never chain truth. */242public struct NFTMarketSnapshot: Codable, Sendable, Hashable {243 public let source: NFTSourceStamp244 /** The item's page on the marketplace: only ever opened outside the app. */245 public let url: String?246 public let listed: NFTKnown<Bool>247 /** The address the MARKETPLACE names as seller (with an escrow marketplace this is not the on-chain holder). */248 public let seller: NFTKnown<String>249 public let marketCollection: String?250 public let listingPrice: NFTKnown<NFTAmount>251 public let bestOffer: NFTKnown<NFTAmount>252 public let lastSale: NFTKnown<NFTAmount>253 /** A statistic of the collection — never the value of this item. */254 public let collectionFloor: NFTKnown<NFTAmount>255}256257/** What can be done with one asset, derived by the server from the stored facts each time the asset is read. */258public struct NFTAssetCapabilities: Codable, Sendable, Hashable {259 public let viewable: Bool260 /** True when no block reason applies. The signer's policy and the re-verification at preparation time still decide. */261 public let transferable: Bool262 /** Every reason that applies, the most specific first (`not_in_wallet`, `frozen`, `pnft_locked`, `soulbound`, `compressed_transfer_not_supported`, …). */263 public let transferBlockedBy: [String]264 /** Facts the review must show (`pnft_rule_set`, `mutable_metadata`, `semi_fungible`, …); never a block. */265 public let transferWarnings: [String]?266 /** Market WRITE actions: `false` as served — none is built. */267 public let marketActions: Bool268 public let marketBlockedBy: String?269}270271/** The per-asset transfer verdict of the item page: stored facts + the signer's NFT policy. A display, not an authorization. */272public struct NFTTransferVerdict: Codable, Sendable, Hashable {273 public let transferable: Bool274 public let blockedBy: [String]275 public let warnings: [String]276 public let standard: NFTStandard277 /** The one call the standard is transferred with; nil when no transfer is built for it. */278 public let route: String?279}280281public struct NFTCreator: Codable, Sendable, Hashable { public let address: String; public let verified: Bool; public let share: Int }282/** What the discovery indexer SIGNALS about the item — that indexer's statement; an item is never dropped because of it. */283public struct NFTIndexerFlags: Codable, Sendable, Hashable { public let spam: Bool; public let by: String; public let classifications: [String] }284public struct NFTExternalLink: Codable, Sendable, Hashable {285 public let name: String286 /** A marketplace page built by the server from on-chain identifiers; opened outside the app only. */287 public let url: String288}289public struct NFTMarketSourceState: Codable, Sendable, Hashable {290 public let provider: String291 public let name: String292 /** `on`, `needs_key`, `off`. */293 public let state: String294 /** NAME of the server variable that would turn the source on — never a value. */295 public let unlockedBy: String?296}297298/** One asset: the answer of the item page, of a lookup, of a metadata refresh and of a manual addition. */299public struct NFTAsset: Codable, Sendable, Hashable, Identifiable {300 public let modelVersion: Int?301 /** `family:chainId:assetId` — the only identity of an asset (never a name, an image or a symbol). */302 public let key: String303 public let family: String304 /** The network id (`ethereum`, `base`, `solana`, …). */305 public let chainId: String306 /** The wallet address the inventory was read for; nil for an asset opened by explicit lookup. */307 public let ownerAddress: String?308 /** EVM: `<contract lower-case>/<token id decimal>`. Solana: the mint / asset address. */309 public let assetId: String310 public let standard: NFTStandard311 /** EVM: the uint256 token id, decimal. */312 public let tokenId: String?313 public let contractAddress: String?314 public let mintAddress: String?315 /** Units held by the wallet (or by the on-chain owner for a lookup); "0" is a value. */316 public let quantity: String317 public let supply: NFTKnown<String>318 public let collection: NFTCollectionRef?319 public let updateAuthority: NFTKnown<String>320 public let creators: NFTKnown<[NFTCreator]>321 public let tokenProgram: String?322 public let royaltyBps: NFTKnown<Int>323 public let ruleSet: NFTKnown<String>324 /** Token-2022 extensions / Core plugins present, by name. */325 public let extensions: [String]326 public let metadata: NFTMetadata327 public let media: [NFTMedia]328 public let ownership: NFTOwnership329 public let market: NFTMarketSnapshot?330 public let capabilities: NFTAssetCapabilities331 public let sources: [NFTSourceStamp]332 public let fetchedAt: Date?333 public let blockRef: NFTBlockRef?334 /** How the asset entered the inventory: `discovered`, `manual`, `lookup`. */335 public let origin: String336 public let indexerFlags: NFTIndexerFlags?337 public let explorerUrl: String?338 public let firstSeen: Date?339 public let lastSeen: Date?340 /** When the ownership was last re-read on-chain. */341 public let verifiedAt: Date?342 /** When the asset was seen to have left the wallet. */343 public let goneAt: Date?344 public let externalMarkets: [NFTExternalLink]?345 public let marketSources: [NFTMarketSourceState]?346 /** Only on `GET /nfts/item`. */347 public let transfer: NFTTransferVerdict?348349 public var id: String { key }350 /** The creator's name, else the on-chain name, else nothing (the screen then shows the identifier). Never a guess. */351 public var displayName: String? { metadata.name ?? metadata.onchainName }352 /** The contract (EVM) or the mint / asset address (Solana): what an NFT intent names as `asset`. */353 public var assetAddress: String { contractAddress ?? mintAddress ?? assetId }354 /** The indexer's spam signal, named; nil when no indexer flagged the item. */355 public var spamFlaggedBy: String? { indexerFlags.flatMap { $0.spam ? $0.by : nil } }356 public var quantityUnits: BaseUnits? { try? BaseUnits(quantity) }357}358359/** One row of the inventory (`summary` in routes.ts). */360public struct NFTSummary: Codable, Sendable, Hashable, Identifiable {361 public struct Collection: Codable, Sendable, Hashable { public let key: String; public let name: String?; public let verifiedOnChain: NFTKnown<Bool> }362 public struct Image: Codable, Sendable, Hashable { public let id: String; public let kind: String; public let status: String }363 public struct Spam: Codable, Sendable, Hashable { public let by: String }364365 public let key: String366 public let chain: String367 public let family: String368 public let standard: NFTStandard369 public let assetId: String370 public let tokenId: String?371 /** Creator-declared (UNTRUSTED text). */372 public let name: String?373 public let onchainName: String?374 public let collection: Collection?375 public let quantity: String376 /** Ownership state: `in_wallet`, `not_in_wallet`, `escrow_or_delegated`, `burned`, `unknown`. */377 public let state: String378 public let inWallet: Bool379 public let origin: String380 public let metadataStatus: String381 /** The media proxy id of the thumbnail, when the metadata names one. */382 public let image: Image?383 public let transferable: Bool?384 /** The first block reason, when the asset cannot be sent. */385 public let transferBlockedBy: String?386 public let firstSeen: Date?387 public let verifiedAt: Date?388 public let goneAt: Date?389 /** True when the ownership was not re-read recently. */390 public let stale: Bool391 /** An indexer's spam signal, as that indexer's statement. */392 public let spam: Spam?393394 public var id: String { key }395 public var displayName: String? { name ?? onchainName }396}397398public struct NFTSyncState: Codable, Sendable, Hashable {399 public let running: [String]400 public let lastSyncedAt: [String: Date]?401}402403/** Why no fiat value is shown: `state` is `unavailable` as served. The clients never substitute a floor or a zero. */404public struct NFTValuationState: Codable, Sendable, Hashable { public let state: String; public let reason: String }405406public struct NFTList: Codable, Sendable, Hashable {407 public let items: [NFTSummary]408 public let total: Int409 /** Items an indexer flagged as spam and that the `hide` filter left out. */410 public let hiddenSpam: Int?411 /** Offset of the next page; nil at the end. */412 public let cursor: Int?413 public let sync: NFTSyncState?414 public let valuation: NFTValuationState?415 public let asOf: Date?416}417418/** Filters of `GET /nfts`. Absent fields take the server's defaults (sort `recent`, spam `hide`, limit 48). */419public struct NFTListQuery: Sendable, Equatable {420 public enum Status: String, Sendable { case inWallet = "in_wallet", left, tracked }421 public enum Sort: String, Sendable { case recent, name }422 public enum Spam: String, Sendable { case hide, show, only }423 public var chain: String?424 /** A collection key. */425 public var collection: String?426 public var status: Status?427 /** Free text, at most 80 characters. */428 public var search: String?429 public var sort: Sort?430 public var spam: Spam?431 public var cursor: Int?432 /** 1…100. */433 public var limit: Int?434 public init(chain: String? = nil, collection: String? = nil, status: Status? = nil, search: String? = nil, sort: Sort? = nil, spam: Spam? = nil, cursor: Int? = nil, limit: Int? = nil) {435 self.chain = chain; self.collection = collection; self.status = status; self.search = search; self.sort = sort; self.spam = spam; self.cursor = cursor; self.limit = limit436 }437}438439// MARK: - capability matrix440441public struct NFTInventorySection: Codable, Sendable, Hashable {442 public let section: String443 /** `ok`, `blocked_by_provider`, `error`, `not_configured`. */444 public let status: String445 public let code: String?446 public let unlockedBy: String?447 public let source: String?448 public let count: Int449 public let truncated: Bool450 public let syncedAt: Date?451}452453/** What the server can really do for NFTs on one network, and why not. Nothing here is assumed by the client. */454public struct NFTChainCapability: Codable, Sendable, Hashable, Identifiable {455 public let network: String456 public let name: String457 public let family: String458 /** `supported`, `partial`, `blocked_by_provider`, `unsupported`. */459 public let inventory: String460 /** Why, as a code (`onchain_and_das`, `no_keyless_discovery`, `ordinals_need_ord_indexer`, `no_adapter`, …). */461 public let reason: String462 public let unlockedBy: String?463 public let standards: [NFTStandard]464 public let lookup: Bool465 public let manualAdd: Bool466 public let receive: Bool467 /** `supported` or `not_supported`. `supported` = a transfer can be PREPARED for `transferStandards`; the asset's own state and the signer's policy still decide. */468 public let transfer: String469 public let transferStandards: [NFTStandard]?470 public let transferReason: String?471 public let marketRead: Bool472 /** `false` as served: no market write is built. */473 public let marketWrite: Bool474 public let sections: [NFTInventorySection]475476 public var id: String { network }477 public var canPrepareTransfers: Bool { transfer == "supported" }478 public func canPrepareTransfer(of standard: NFTStandard) -> Bool { canPrepareTransfers && (transferStandards ?? []).contains(standard) }479}480481public struct NFTCapabilities: Codable, Sendable, Hashable {482 public struct Provider: Codable, Sendable, Hashable, Identifiable {483 public let id: String484 public let on: Bool485 public let unlockedBy: String?486 /** What leaves the server when the provider is asked (`wallet_address_to_rpc`, `mint_only`, `nothing_until_enabled`, `not_built`, …). */487 public let sends: String488 }489 public struct Budget: Codable, Sendable, Hashable { public let source: String; public let requests: Int; public let bytes: String }490491 public let chains: [NFTChainCapability]492 public let providers: [Provider]493 public let budget: [Budget]?494 /** `inventoryMax`, `mediaMaxBytes`, `dailyRequests`, `dailyBytes`. */495 public let limits: [String: Int]?496497 public func chain(_ network: String) -> NFTChainCapability? { chains.first { $0.network == network } }498 /** The largest media file the proxy serves (the server's `NFT_MEDIA_MAX_BYTES`, 25 MiB by default, at most 200 MiB). */499 public var mediaMaxBytes: Int? { limits?["mediaMaxBytes"] }500 /** True only if the server says some network can write to a market. No version of the backend does. */501 public var anyMarketWrite: Bool { chains.contains { $0.marketWrite } }502}503504// MARK: - events505506/** One on-chain event of an asset (or a market statement attached to it). A transfer never carries a price. */507public struct NFTEvent: Codable, Sendable, Hashable, Identifiable {508 public struct Interpretation: Codable, Sendable, Hashable { public let by: String; public let note: String? }509 public struct MarketProgram: Codable, Sendable, Hashable { public let id: String; public let name: String; public let source: String }510 public struct Market: Codable, Sendable, Hashable {511 public let provider: String512 public let venue: String?513 public let orderId: String?514 /** Wash / self trade as the SOURCE reports it. */515 public let washTrade: NFTKnown<Bool>?516 public let fees: [NFTMarketFee]?517 }518519 /** `<assetKey>|<tx>|<index>`. */520 public let id: String521 public let assetKey: String?522 /** `mint`, `transfer-in`, `transfer-out`, `transfer`, `sale`, `list`, `delist`, `offer`, `cancel-offer`, `accept-offer`, `burn`, `escrow`, `unknown`. */523 public let type: String524 /** `type` is what the server decoded from the raw trace; this names the decoder. */525 public let interpretation: Interpretation?526 public let tx: String527 public let index: String528 public let blockRef: NFTBlockRef?529 /** ISO time, UTC; nil when the chain source gives none. */530 public let at: String?531 public let from: String?532 public let to: String?533 public let quantity: String534 /** Only with a payment linked by a market source. */535 public let price: NFTAmount?536 /** `finalized`, `confirmed`, `pending`, `reorged`. */537 public let finality: String538 public let source: NFTSourceStamp539 public let marketProgram: MarketProgram?540 public let market: Market?541542 public var date: Date? { at.flatMap(ISO8601.parse) }543 /** Only a finalized event is settled. */544 public var isFinal: Bool { finality == "finalized" }545}546547public struct NFTActivity: Codable, Sendable, Hashable {548 public let events: [NFTEvent]549 public let cursor: String?550 /** `full`, `partial`, `recent_window`, `unavailable`: how much of the history the chain source could give. */551 public let completeness: String552 public let note: String?553 public let scannedAt: Date?554 public let canLoadOlder: Bool555 /** A provider code when the refresh failed; the stored events are still answered. */556 public let error: String?557}558559/** The event types `GET /nfts/activity` filters on. */560public enum NFTEventType: String, Sendable, CaseIterable {561 case mint, transfer, transferIn = "transfer-in", transferOut = "transfer-out", burn, sale, list, delist, offer562 case cancelOffer = "cancel-offer", acceptOffer = "accept-offer", escrow, unknown563}564565// MARK: - collections, receive566567public struct NFTCollectionCount: Codable, Sendable, Hashable, Identifiable {568 public let collectionKey: String569 public let chain: String570 /** Items of the collection held by the wallet. */571 public let count: Int572 public let name: String?573 enum CodingKeys: String, CodingKey { case collectionKey = "collection_key", chain, count = "n", name }574 public var id: String { collectionKey }575}576577public struct NFTCollectionDetail: Codable, Sendable, Hashable {578 public struct Info: Codable, Sendable, Hashable {579 public let key: String580 public let id: String581 public let chain: String582 public let standard: NFTStandard583 public let onchainName: String?584 /** UNTRUSTED. The collection's metadata URI as the chain gives it; never fetched by the client. */585 public let uri: String?586 public let size: NFTKnown<String>587 public let updateAuthority: NFTKnown<String>588 public let features: [String]589 public let source: NFTSourceStamp590 }591 /** The collection's own creator metadata, resolved by the server (UNTRUSTED text). */592 public struct Metadata: Codable, Sendable, Hashable {593 public let name: String?594 public let description: String?595 /** Media proxy id of the collection image. */596 public let imageId: String?597 public let status: String598 }599 public let info: Info?600 public let error: String?601 public let metadata: Metadata?602 public let held: Int603 public let fetchedAt: Date?604}605606/** Where an NFT can be received: the wallet's address on a network an adapter reads, with the warnings that apply. */607public struct NFTReceiveAddress: Codable, Sendable, Hashable, Identifiable {608 public let network: String609 public let name: String610 public let family: String611 public let address: String612 public let standards: [NFTStandard]613 /** Codes the interface translates (`ordinals_no_transfer`, `evm_same_address_check_network`, `sol_compressed_needs_indexer`, `arrival_after_confirmation`, …). */614 public let warnings: [String]615 /** How arrivals are detected there: `supported`, `partial`, `blocked_by_provider`, `unsupported`. */616 public let detection: String617 public var id: String { network }618}619620public struct NFTSyncStarted: Codable, Sendable, Hashable { public let running: [String] }621public struct NFTUntracked: Codable, Sendable, Hashable { public let ok: Bool; public let removed: Bool }622623/** Chain identifier of an asset the owner typed (`POST /nfts/lookup`, `POST /nfts/manual`). */624public struct NFTReference: Codable, Sendable, Equatable {625 public let chain: String626 /** EVM: the contract. Solana: the mint / asset address. 26–64 characters. */627 public let address: String628 /** EVM only: decimal or 0x-hex token id. */629 public let tokenId: String?630 public init(chain: String, address: String, tokenId: String? = nil) { self.chain = chain; self.address = address; self.tokenId = tokenId }631}632633// MARK: - media proxy634635/** `GET /nfts/media/<id>?info=1`: what the file IS (decided by the server from its bytes), without the bytes. */636public struct NFTMediaInfo: Codable, Sendable, Hashable {637 /** `available`, or the refusal (`media_blocked`, `media_unreachable`, `not_found`). */638 public let status: String639 public let mime: String?640 public let kind: String?641 public let bytes: Int?642 /** The reason of a refusal (`scheme_not_allowed`, `mime_mismatch`, `too_large`, …). */643 public let code: String?644 public var isAvailable: Bool { status == "available" }645}646647/** The bytes of one media file as the server's proxy served them. */648public struct NFTMediaContent: Sendable, Equatable {649 public let data: Data650 /** The `Content-Type` header as served. */651 public let contentType: String652 /** The MIME type without its parameters, lower-cased. Always one of `NFTMediaContent.servedTypes`. */653 public let mime: String654 /** `image`, `video`, `audio`, `html`, `model`. */655 public let kind: String656657 /** The proxy's allow-list (`SERVED_MIME` of packages/nft/src/sniff.ts): every type it can serve, decided from the bytes. */658 public static let servedTypes: [String: String] = [659 "image/png": "image", "image/jpeg": "image", "image/gif": "image", "image/webp": "image", "image/avif": "image", "image/svg+xml": "image",660 "video/mp4": "video", "video/webm": "video", "audio/mpeg": "audio", "audio/wav": "audio", "audio/ogg": "audio", "audio/mp4": "audio",661 "text/html": "html", "model/gltf-binary": "model",662 ]663 /**664 HTML and SVG can carry script. The web client shows them inside a sandboxed iframe under the proxy's Content-Security-Policy;665 a native view has no such header-enforced sandbox, so these bytes must be shown inert (placeholder, source text, or an SVG666 rasterizer without scripting / network) and never handed to a JavaScript-enabled web view.667 */668 public var isActiveContent: Bool { mime == "text/html" || mime == "image/svg+xml" }669}670671/** Link hygiene shared by the NFT models (`safeLink` of apps/web/src/nft.ts). */672public enum NFTLinks {673 /** Only a plain http(s) URL without credentials is a link; anything else (javascript:, data:, ipfs:, …) is text. */674 public static func safe(_ raw: String?) -> URL? {675 guard let raw, let c = URLComponents(string: raw), let scheme = c.scheme?.lowercased(), scheme == "https" || scheme == "http",676 c.user == nil, c.password == nil, let host = c.host, !host.isEmpty else { return nil }677 return c.url678 }679}680681/** An asset key (`family:chainId:assetId`) taken apart (`parseNftKey`). */682public struct NFTKey: Sendable, Equatable {683 public let family: String684 public let chainId: String685 public let assetId: String686687 public init?(_ key: String) {688 guard key.utf16.count >= 5, key.utf16.count <= 260 else { return nil }689 let parts = key.split(separator: ":", maxSplits: 2, omittingEmptySubsequences: false)690 guard parts.count == 3 else { return nil }691 let seg = "^[a-z0-9-]{1,24}$"692 let f = String(parts[0]), c = String(parts[1]), a = String(parts[2])693 guard f.range(of: seg, options: .regularExpression) != nil, c.range(of: seg, options: .regularExpression) != nil,694 !a.isEmpty, a.utf16.count <= 200, a.range(of: "[\\s:?#%]", options: .regularExpression) == nil else { return nil }695 family = f; chainId = c; assetId = a696 }697 /** EVM: the contract (lower-case) and the decimal token id of `<contract>/<tokenId>`. */698 public var evm: (contract: String, tokenId: String)? {699 guard family == "evm" else { return nil }700 let p = assetId.split(separator: "/", omittingEmptySubsequences: false)701 guard p.count == 2, !p[0].isEmpty, !p[1].isEmpty else { return nil }702 return (String(p[0]), String(p[1]))703 }704}705