SPB Git

Repository Public

NFTCanonical.swift 20.1 KB 338 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/NFT/NFTCanonical.swift3// Description: The three objects the owner's passkey approves for NFTs, exactly as packages/core/src/nft-intent.ts defines them:4//              the NFT transfer intent (`SPW-NFT-INTENT-v1`), the change of the signer's NFT destination allow-list5//              (`SPW-NFT-ALLOW-v1`) and the change of the signer's Bitcoin outpoint lock list (`SPW-UTXO-LOCKS-v1`). Strict reading6//              of the served object (the same constraints as the backend's strict schemas), the same ordered field list, the7//              same bytes, the same SHA-256. None of them carries calldata, an instruction list or a "data" field: the signer8//              builds the transaction from these semantic fields, so what is not a field cannot be asked for.9//10// Author: Simon-Pierre Boucher11// Contact: contact@spboucher.ai12import Foundation1314/** Standards a transfer can be built for (`NFT_TRANSFER_STANDARDS`). Compressed NFTs, inscriptions and non-standard contracts have no builder. */15public enum NFTTransferStandard: String, Sendable, CaseIterable, Codable {16    case erc721, erc115517    case splToken2022 = "spl-token-2022"18    case metaplexTokenMetadata = "metaplex-token-metadata"19    case metaplexPNFT = "metaplex-pnft"20    case metaplexCore = "metaplex-core"2122    /** The one call each standard is transferred with (`NFT_TRANSFER_METHOD`): implied by the standard, never chosen by the API. */23    public var method: String {24        switch self {25        case .erc721: "safeTransferFrom(address,address,uint256)"26        case .erc1155: "safeTransferFrom(address,address,uint256,uint256,bytes) — data empty"27        case .splToken2022: "Token-2022 TransferChecked (amount 1, decimals 0)"28        case .metaplexTokenMetadata: "Token Metadata Transfer (TransferArgs::V1, amount 1, no authorization data)"29        case .metaplexPNFT: "Token Metadata Transfer (TransferArgs::V1, amount 1, no authorization data) with token records"30        case .metaplexCore: "Core TransferV1 (no compression proof)"31        }32    }33    public var isEVM: Bool { self == .erc721 || self == .erc1155 }34}3536/** The constraints of the backend's schemas that are not already carried by `StrictObject`. A value outside them is a refusal. */37enum NFTCanonicalRules {38    static func matches(_ s: String, _ pattern: String) -> Bool { s.range(of: "^(?:\(pattern))$", options: .regularExpression) != nil }39    /** JavaScript string length (UTF-16 code units), which is what the schemas' `min` / `max` count. */40    static func length(_ s: String, _ range: ClosedRange<Int>, _ path: String) throws {41        guard range.contains(s.utf16.count) else { throw ApprovalError.unsupported("\(path) has an unexpected length") }42    }43    static func uuid(_ s: String, _ path: String) throws {44        // zod 4 `z.uuid()`: RFC 9562 versions 1–8 with the RFC variant, or the nil / max UUID45        let hex = "[0-9a-fA-F]"46        guard matches(s, "\(hex){8}-\(hex){4}-[1-8]\(hex){3}-[89abAB]\(hex){3}-\(hex){12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff")47        else { throw ApprovalError.unsupported("\(path) is not a UUID") }48    }49    static func network(_ s: String, _ path: String) throws {50        guard matches(s, "[a-z0-9-]{2,24}") else { throw ApprovalError.unsupported("\(path) is not a network id") }51    }52    static func solanaAddress(_ s: String, _ path: String) throws {53        guard matches(s, "[1-9A-HJ-NP-Za-km-z]{32,44}") else { throw ApprovalError.unsupported("\(path) is not a Solana address") }54    }55    static func literal(_ s: String, _ expected: String, _ path: String) throws {56        guard s == expected else { throw ApprovalError.unsupported("\(path) is \(s), expected \(expected)") }57    }58    static func positive(_ i: Int, _ path: String) throws { guard i > 0 else { throw ApprovalError.unsupported("\(path) must be positive") } }59    static func nonNegative(_ i: Int, _ path: String) throws { guard i >= 0 else { throw ApprovalError.unsupported("\(path) must not be negative") } }60    static func optionalBool(_ o: inout StrictObject, _ k: String) throws -> Bool? {61        guard let v = o.raw(k) else { return nil }62        guard let b = v.boolValue else { throw ApprovalError.unsupported("\(o.path).\(k) is not a boolean") }63        return b64    }65    static func write(domain: String, _ fields: [(String, String)]) -> Data {66        var w = CanonicalWriter(domain: domain)67        for (k, v) in fields { w.field(k, v) }68        return w.data69    }70}7172// MARK: - NFT transfer intent7374/** ONE transfer of ONE NFT (or of `quantity` units of one ERC-1155 id) from the wallet's own address. */75public struct NFTIntent: PasskeyApprovable, Equatable {76    public static let domain = "SPW-NFT-INTENT-v1"7778    public struct EVM: Sendable, Equatable { public let nonce: Int; public let gasLimit, maxFeePerGas, maxPriorityFeePerGas: String }79    public struct SOL: Sendable, Equatable {80        public let recentBlockhash: String81        public let lastValidBlockHeight: Int82        public let computeUnitLimit: Int83        public let computeUnitPrice: String84        /** SPL / Token Metadata: which token program owns the mint (`token` or `token2022`). Absent for Core. */85        public let tokenProgram: String?86        /** Token-2022 plain transfer only: the transaction first creates the recipient's associated token account (rent is locked there). */87        public let createAta: Bool?88        /** pNFT only: the rule set account named by the metadata's programmable config. */89        public let ruleSet: String?90        /** Core only: the collection the asset belongs to. */91        public let collection: String?92    }9394    public let v: Int95    /** Always `nft-transfer`. */96    public let kind: String97    public let proposalId, keyId, network, chainRef: String98    public let standard: NFTTransferStandard99    /** EVM: the token contract (EIP-55). Solana: the mint (SPL, Token Metadata) or the asset address (Core). */100    public let asset: String101    /** EVM: the uint256 token id as a decimal string. Solana: absent (the mint / asset address IS the identity). */102    public let tokenId: String?103    /** Units moved: exactly 1 for every standard except ERC-1155. */104    public let quantity: String105    /** The contract / program the transaction calls. EVM: equal to `asset`. Solana: the pinned program of the standard. */106    public let program: String107    public let from, to: String108    /** Fee ceiling in base units of the network's native coin. */109    public let maxFee: String110    public let createdAt, expiresAt, policyVersion, nftPolicyVersion: Int111    public let evm: EVM?112    public let sol: SOL?113    /** The object as served. */114    public let served: JSONValue115116    public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt)) }117    public var maxFeeUnits: BaseUnits { (try? BaseUnits(maxFee)) ?? .zero }118119    /** Strict parse of the `intent` object of `POST /nfts/transfer/prepare`. */120    public init(served json: JSONValue) throws {121        typealias R = NFTCanonicalRules122        var o = try StrictObject(json, path: "nftIntent")123        v = try o.int("v")124        guard v == 1 else { throw ApprovalError.unsupported("NFT intent version \(v)") }125        kind = try o.string("kind"); try R.literal(kind, "nft-transfer", "nftIntent.kind")126        proposalId = try o.string("proposalId"); try R.uuid(proposalId, "nftIntent.proposalId")127        keyId = try o.string("keyId"); try R.length(keyId, 8...80, "nftIntent.keyId")128        network = try o.string("network"); try R.network(network, "nftIntent.network")129        chainRef = try o.string("chainRef"); try R.length(chainRef, 1...80, "nftIntent.chainRef")130        let std = try o.string("standard")131        guard let s = NFTTransferStandard(rawValue: std) else { throw ApprovalError.unsupported("NFT standard \(std) has no transfer") }132        standard = s133        asset = try o.string("asset"); try R.length(asset, 32...44, "nftIntent.asset")134        if o.has("tokenId") { tokenId = try o.units("tokenId") } else { tokenId = try o.optionalString("tokenId") }135        quantity = try o.units("quantity")136        program = try o.string("program"); try R.length(program, 32...44, "nftIntent.program")137        from = try o.string("from"); try R.length(from, 32...44, "nftIntent.from")138        to = try o.string("to"); try R.length(to, 32...44, "nftIntent.to")139        maxFee = try o.units("maxFee")140        createdAt = try o.int("createdAt"); try R.positive(createdAt, "nftIntent.createdAt")141        expiresAt = try o.int("expiresAt"); try R.positive(expiresAt, "nftIntent.expiresAt")142        policyVersion = try o.int("policyVersion"); try R.nonNegative(policyVersion, "nftIntent.policyVersion")143        nftPolicyVersion = try o.int("nftPolicyVersion"); try R.nonNegative(nftPolicyVersion, "nftIntent.nftPolicyVersion")144145        if var e = try o.child("evm") {146            let nonce = try e.int("nonce"); try R.nonNegative(nonce, "nftIntent.evm.nonce")147            evm = EVM(nonce: nonce, gasLimit: try e.units("gasLimit"), maxFeePerGas: try e.units("maxFeePerGas"), maxPriorityFeePerGas: try e.units("maxPriorityFeePerGas"))148            try e.finish()149        } else { evm = nil }150        if var s = try o.child("sol") {151            let blockhash = try s.string("recentBlockhash"); try R.length(blockhash, 32...44, "nftIntent.sol.recentBlockhash")152            let height = try s.int("lastValidBlockHeight"); try R.positive(height, "nftIntent.sol.lastValidBlockHeight")153            let limit = try s.int("computeUnitLimit")154            guard (1...400_000).contains(limit) else { throw ApprovalError.unsupported("nftIntent.sol.computeUnitLimit out of range") }155            let price = try s.units("computeUnitPrice")156            let tokenProgram = try s.optionalString("tokenProgram")157            if let tokenProgram, tokenProgram != "token", tokenProgram != "token2022" { throw ApprovalError.unsupported("nftIntent.sol.tokenProgram \(tokenProgram)") }158            let createAta = try R.optionalBool(&s, "createAta")159            let ruleSet = try s.optionalString("ruleSet"); if let ruleSet { try R.solanaAddress(ruleSet, "nftIntent.sol.ruleSet") }160            let collection = try s.optionalString("collection"); if let collection { try R.solanaAddress(collection, "nftIntent.sol.collection") }161            sol = SOL(recentBlockhash: blockhash, lastValidBlockHeight: height, computeUnitLimit: limit, computeUnitPrice: price, tokenProgram: tokenProgram, createAta: createAta, ruleSet: ruleSet, collection: collection)162            try s.finish()163        } else { sol = nil }164        try o.finish()165        served = json166167        // the backend's nftCanonicalBytes: "an NFT intent carries exactly one chain section"168        guard (evm != nil) != (sol != nil) else { throw ApprovalError.unsupported("an NFT intent carries exactly one chain section") }169    }170171    /** The ordered (name, value) pairs of `nftCanonicalBytes`. An absent optional field is absent from the bytes. */172    public func fields() -> [(String, String)] {173        var f: [(String, String)] = [174            ("v", String(v)), ("kind", kind), ("proposalId", proposalId), ("keyId", keyId), ("network", network), ("chainRef", chainRef),175            ("standard", standard.rawValue), ("asset", asset), ("quantity", quantity), ("program", program), ("from", from), ("to", to), ("maxFee", maxFee),176            ("createdAt", String(createdAt)), ("expiresAt", String(expiresAt)), ("policyVersion", String(policyVersion)), ("nftPolicyVersion", String(nftPolicyVersion)),177        ]178        if let tokenId { f.append(("tokenId", tokenId)) }179        if let e = evm { f += [("evm.nonce", String(e.nonce)), ("evm.gasLimit", e.gasLimit), ("evm.maxFeePerGas", e.maxFeePerGas), ("evm.maxPriorityFeePerGas", e.maxPriorityFeePerGas)] }180        if let s = sol {181            f += [("sol.recentBlockhash", s.recentBlockhash), ("sol.lastValidBlockHeight", String(s.lastValidBlockHeight)), ("sol.computeUnitLimit", String(s.computeUnitLimit)), ("sol.computeUnitPrice", s.computeUnitPrice)]182            if let p = s.tokenProgram { f.append(("sol.tokenProgram", p)) }183            if let c = s.createAta { f.append(("sol.createAta", c ? "1" : "0")) }184            if let r = s.ruleSet { f.append(("sol.ruleSet", r)) }185            if let c = s.collection { f.append(("sol.collection", c)) }186        }187        return f188    }189190    public func canonicalBytes() throws -> Data { NFTCanonicalRules.write(domain: Self.domain, fields()) }191}192193extension NFTIntent: Decodable {194    public init(from decoder: Decoder) throws {195        let json = try JSONValue(from: decoder)196        do { try self.init(served: json) }197        catch { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "NFT intent refused: \(error)")) }198    }199}200201// MARK: - NFT destination allow-list202203/** A change of the signer's own list of destinations allowed to receive NFTs (allow-list mode). */204public struct NFTAllowIntent: PasskeyApprovable, Equatable {205    public static let domain = "SPW-NFT-ALLOW-v1"206    public enum Action: String, Sendable, Codable, CaseIterable { case add, remove }207208    public let v: Int209    /** Always `nft-allow`. */210    public let kind: String211    public let requestId, keyId, network: String212    public let action: Action213    /** The destination, in the normalized form of its network. */214    public let address: String215    public let createdAt, expiresAt, policyVersion: Int216    /** The object as served: `POST /nfts/allow/approve` takes it back untouched. */217    public let served: JSONValue218219    public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt)) }220221    public init(served json: JSONValue) throws {222        typealias R = NFTCanonicalRules223        var o = try StrictObject(json, path: "nftAllow")224        v = try o.int("v")225        guard v == 1 else { throw ApprovalError.unsupported("NFT allow-list intent version \(v)") }226        kind = try o.string("kind"); try R.literal(kind, "nft-allow", "nftAllow.kind")227        requestId = try o.string("requestId"); try R.uuid(requestId, "nftAllow.requestId")228        keyId = try o.string("keyId"); try R.length(keyId, 8...80, "nftAllow.keyId")229        network = try o.string("network"); try R.network(network, "nftAllow.network")230        let a = try o.string("action")231        guard let act = Action(rawValue: a) else { throw ApprovalError.unsupported("nftAllow.action \(a)") }232        action = act233        address = try o.string("address"); try R.length(address, 32...44, "nftAllow.address")234        createdAt = try o.int("createdAt"); try R.positive(createdAt, "nftAllow.createdAt")235        expiresAt = try o.int("expiresAt"); try R.positive(expiresAt, "nftAllow.expiresAt")236        policyVersion = try o.int("policyVersion"); try R.nonNegative(policyVersion, "nftAllow.policyVersion")237        try o.finish()238        served = json239    }240241    /** The ordered (name, value) pairs of `nftAllowBytes`. */242    public func fields() -> [(String, String)] {243        [("v", String(v)), ("kind", kind), ("requestId", requestId), ("keyId", keyId), ("network", network), ("action", action.rawValue), ("address", address),244         ("createdAt", String(createdAt)), ("expiresAt", String(expiresAt)), ("policyVersion", String(policyVersion))]245    }246    public func canonicalBytes() throws -> Data { NFTCanonicalRules.write(domain: Self.domain, fields()) }247}248249extension NFTAllowIntent: Decodable {250    public init(from decoder: Decoder) throws {251        let json = try JSONValue(from: decoder)252        do { try self.init(served: json) }253        catch { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "NFT allow-list intent refused: \(error)")) }254    }255}256257// MARK: - Bitcoin-style outpoint lock list258259/** A change of the signer's own lock list of Bitcoin-style outpoints (inscription safety): a locked outpoint is refused as an input of any send. */260public struct UTXOLockIntent: PasskeyApprovable, Equatable {261    public static let domain = "SPW-UTXO-LOCKS-v1"262    public enum Action: String, Sendable, Codable, CaseIterable { case lock, unlock }263    /** Why an outpoint is locked. `ord`: an ord server reported an inscription or a rune on it; `heuristic`: flagged by size only. */264    public enum Reason: String, Sendable, Codable, CaseIterable { case owner, ord, heuristic }265    public struct Outpoint: Sendable, Equatable, Hashable {266        public let txid: String267        public let vout: Int268        /** `<txid>:<vout>` (`outpointKey`). */269        public var key: String { "\(txid):\(vout)" }270    }271272    public let v: Int273    /** Always `utxo-locks`. */274    public let kind: String275    public let requestId, keyId, network: String276    public let action: Action277    public let reason: Reason278    public let outpoints: [Outpoint]279    public let createdAt, expiresAt, policyVersion: Int280    /** The object as served: `POST /utxo-locks/approve` takes it back untouched. */281    public let served: JSONValue282283    public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt)) }284285    public init(served json: JSONValue) throws {286        typealias R = NFTCanonicalRules287        var o = try StrictObject(json, path: "utxoLocks")288        v = try o.int("v")289        guard v == 1 else { throw ApprovalError.unsupported("outpoint lock intent version \(v)") }290        kind = try o.string("kind"); try R.literal(kind, "utxo-locks", "utxoLocks.kind")291        requestId = try o.string("requestId"); try R.uuid(requestId, "utxoLocks.requestId")292        keyId = try o.string("keyId"); try R.length(keyId, 8...80, "utxoLocks.keyId")293        network = try o.string("network"); try R.network(network, "utxoLocks.network")294        let a = try o.string("action")295        guard let act = Action(rawValue: a) else { throw ApprovalError.unsupported("utxoLocks.action \(a)") }296        action = act297        let r = try o.string("reason")298        guard let why = Reason(rawValue: r) else { throw ApprovalError.unsupported("utxoLocks.reason \(r)") }299        reason = why300        let list = try o.array("outpoints")301        guard (1...100).contains(list.count) else { throw ApprovalError.unsupported("utxoLocks.outpoints must hold 1 to 100 outpoints") }302        outpoints = try list.enumerated().map { k, value in303            var p = try StrictObject(value, path: "utxoLocks.outpoints.\(k)")304            let txid = try p.string("txid"), vout = try p.int("vout")305            guard R.matches(txid, "[0-9a-f]{64}") else { throw ApprovalError.unsupported("utxoLocks.outpoints.\(k).txid is not a transaction id") }306            guard (0...0xffff_ffff).contains(vout) else { throw ApprovalError.unsupported("utxoLocks.outpoints.\(k).vout out of range") }307            try p.finish()308            return Outpoint(txid: txid, vout: vout)309        }310        createdAt = try o.int("createdAt"); try R.positive(createdAt, "utxoLocks.createdAt")311        expiresAt = try o.int("expiresAt"); try R.positive(expiresAt, "utxoLocks.expiresAt")312        policyVersion = try o.int("policyVersion"); try R.nonNegative(policyVersion, "utxoLocks.policyVersion")313        try o.finish()314        served = json315316        // the backend's utxoLockBytes: "duplicate outpoint"317        guard Set(outpoints.map(\.key)).count == outpoints.count else { throw ApprovalError.unsupported("duplicate outpoint") }318    }319320    /** The ordered (name, value) pairs of `utxoLockBytes`. */321    public func fields() -> [(String, String)] {322        var f: [(String, String)] = [("v", String(v)), ("kind", kind), ("requestId", requestId), ("keyId", keyId), ("network", network), ("action", action.rawValue), ("reason", reason.rawValue),323                                     ("outpoints.count", String(outpoints.count))]324        for (k, p) in outpoints.enumerated() { f += [("outpoints.\(k).txid", p.txid), ("outpoints.\(k).vout", String(p.vout))] }325        f += [("createdAt", String(createdAt)), ("expiresAt", String(expiresAt)), ("policyVersion", String(policyVersion))]326        return f327    }328    public func canonicalBytes() throws -> Data { NFTCanonicalRules.write(domain: Self.domain, fields()) }329}330331extension UTXOLockIntent: Decodable {332    public init(from decoder: Decoder) throws {333        let json = try JSONValue(from: decoder)334        do { try self.init(served: json) }335        catch { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "outpoint lock intent refused: \(error)")) }336    }337}338
Files main
Menu

Theme