SPB Git

Repository Public

SwapCanonical.swift 17.9 KB 328 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SPWalletCore9// File             : Sources/SPWalletCore/Domains/Swap/SwapCanonical.swift10// Description      : What the swap domain recomputes byte for byte: the asset11//                    key (packages/swap/src/types.ts `assetKey`), the quote12//                    fingerprint and the quote reference sent back when a route13//                    is prepared (services/api/src/prepare-common.ts), and the14//                    three passkey-approved objects of the CCTP bridge that are15//                    not intents: the re-signature of a mint16//                    (`SPW-BRIDGE-MINT-v1`, `SPW-BRIDGE-MINT-SOL-v1`), the17//                    reclaim of a Solana event-account deposit18//                    (`SPW-BRIDGE-RECLAIM-v1`) and the creation of the wallet's19//                    USDC token account (`SPW-SOL-TOKEN-ACCOUNT-v1`).20// Module           : SPWalletCore21// Repository       : https://git.spboucher.ai/sp-wallet-core22// 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// =============================================================================9697import Foundation98import CryptoKit99100/** An asset is a network + a contract / mint (`native` for the chain coin). A symbol is never an identifier. */101public struct AssetRef: Codable, Sendable, Hashable {102    public let network: String103    public let asset: String104    public init(network: String, asset: String) { self.network = network; self.asset = asset }105106    /**107     `<network>:<asset>` as the API writes it: the contract address in lower case on an EVM network, verbatim elsewhere108     (a Solana mint is case-sensitive). `family` is `Network.family` of the wallet registry.109     */110    public func key(family: String) -> String { "\(network):\(asset == "native" ? "native" : family == "evm" ? AssetRef.asciiLowercased(asset) : asset)" }111112    /** JavaScript's `toLowerCase()` restricted to what an address contains: only A–Z change. */113    static func asciiLowercased(_ s: String) -> String {114        String(decoding: s.utf8.map { $0 >= 65 && $0 <= 90 ? $0 + 32 : $0 }, as: UTF8.self)115    }116    /** Same asset id: identical text, or two `0x` addresses that differ only by their checksum case. */117    static func sameAssetId(_ a: String, _ b: String) -> Bool {118        a == b || (a.hasPrefix("0x") && b.hasPrefix("0x") && asciiLowercased(a) == asciiLowercased(b))119    }120}121122/** What a route promises: who, which pair, how much in, which tolerance, how much out (`QuoteFacts` of prepare-common.ts). */123public struct QuoteFacts: Sendable, Hashable {124    /** The provider, or the providers of a composed route joined by `+`. */125    public let provider: String126    public let fromKey: String127    public let toKey: String128    public let amountIn: String129    public let slippageBps: Int130    public let amountOut: String131    public let minAmountOut: String132133    public init(provider: String, fromKey: String, toKey: String, amountIn: String, slippageBps: Int, amountOut: String, minAmountOut: String) {134        self.provider = provider; self.fromKey = fromKey; self.toKey = toKey; self.amountIn = amountIn; self.slippageBps = slippageBps135        self.amountOut = amountOut; self.minAmountOut = minAmountOut136    }137138    /** The exact text the backend hashes: the seven facts joined by `|`. */139    public var canonicalText: String { [provider, fromKey, toKey, amountIn, String(slippageBps), amountOut, minAmountOut].joined(separator: "|") }140    /** `quoteFingerprint`: the first 32 hexadecimal characters of SHA-256 of `canonicalText`. */141    public var fingerprint: String { String(Data(SHA256.hash(data: Data(canonicalText.utf8))).hex.prefix(32)) }142}143144/** The reference of the quote the owner was looking at, sent with a preparation (`QuoteRef` of prepare-common.ts). */145public struct QuoteRef: Codable, Sendable, Hashable {146    /** Route id of the quote response (1–300 characters). */147    public let id: String148    public let provider: String149    /** 32 lower-case hexadecimal characters. */150    public let fingerprint: String151    /** Base units of the destination asset, as displayed. */152    public let amountOut: String153    public let minAmountOut: String154    /** Unix milliseconds. */155    public let quotedAt: Int156157    public init(id: String, provider: String, fingerprint: String, amountOut: String, minAmountOut: String, quotedAt: Int) {158        self.id = id; self.provider = provider; self.fingerprint = fingerprint; self.amountOut = amountOut; self.minAmountOut = minAmountOut; self.quotedAt = quotedAt159    }160161    /** True when the reference has the shape the server's strict schema accepts (it would answer 400 otherwise). */162    public var isWellFormed: Bool {163        !id.isEmpty && id.count <= 300 && !provider.isEmpty && provider.count <= 40 && quotedAt > 0164            && fingerprint.utf8.count == 32 && fingerprint.utf8.allSatisfy { ($0 >= 48 && $0 <= 57) || ($0 >= 97 && $0 <= 102) }165            && (try? BaseUnits(amountOut)) != nil && (try? BaseUnits(minAmountOut)) != nil166    }167}168169// MARK: - passkey-approved objects of the bridge that are not intents170171/** EIP-1559 parameters of a mint transaction on an EVM destination (`CctpMintGas`). */172public struct EVMGasParameters: Sendable, Hashable {173    public let nonce: Int174    public let gasLimit, maxFeePerGas, maxPriorityFeePerGas: String175    public init(nonce: Int, gasLimit: String, maxFeePerGas: String, maxPriorityFeePerGas: String) {176        self.nonce = nonce; self.gasLimit = gasLimit; self.maxFeePerGas = maxFeePerGas; self.maxPriorityFeePerGas = maxPriorityFeePerGas177    }178    init(strict v: JSONValue?, path: String) throws {179        var o = try StrictObject(v, path: path)180        nonce = try o.int("nonce"); gasLimit = try o.units("gasLimit"); maxFeePerGas = try o.units("maxFeePerGas"); maxPriorityFeePerGas = try o.units("maxPriorityFeePerGas")181        try o.finish()182        guard nonce >= 0 else { throw ApprovalError.unsupported("\(path).nonce is negative") }183    }184    /** gasLimit × maxFeePerGas: the most the transaction can cost, in base units of the destination's coin. */185    public var maxNetworkFee: String { DecimalDigits.multiply(gasLimit, maxFeePerGas) }186}187188/** Lifetime and compute budget of a Solana transaction (`SolBudget`). */189public struct SolanaBudget: Sendable, Hashable {190    public let recentBlockhash: String191    public let lastValidBlockHeight: Int192    public let computeUnitLimit: Int193    /** Micro-lamports per compute unit. */194    public let computeUnitPrice: String195    public init(recentBlockhash: String, lastValidBlockHeight: Int, computeUnitLimit: Int, computeUnitPrice: String) {196        self.recentBlockhash = recentBlockhash; self.lastValidBlockHeight = lastValidBlockHeight; self.computeUnitLimit = computeUnitLimit; self.computeUnitPrice = computeUnitPrice197    }198    init(strict v: JSONValue?, path: String) throws {199        var o = try StrictObject(v, path: path)200        recentBlockhash = try o.string("recentBlockhash"); lastValidBlockHeight = try o.int("lastValidBlockHeight")201        computeUnitLimit = try o.int("computeUnitLimit"); computeUnitPrice = try o.units("computeUnitPrice")202        try o.finish()203        guard lastValidBlockHeight >= 0, computeUnitLimit >= 0 else { throw ApprovalError.unsupported("\(path) carries a negative number") }204    }205    /** ⌈limit × price ÷ 10⁶⌉ lamports: the priority fee the budget pays (`priorityOf` of bridge-sol.ts). */206    public var priorityFee: BaseUnits? {207        guard let p = try? BaseUnits(DecimalDigits.multiply(String(computeUnitLimit), computeUnitPrice)) else { return nil }208        return (p + BaseUnits(999_999)).divided(by: 1_000_000)209    }210    /** One signature (5 000 lamports) + the priority fee: the network fee of a one-signer transaction with this budget. */211    public var singleSignerNetworkFee: BaseUnits? { priorityFee.map { $0 + BaseUnits(5000) } }212}213214/** Lines joined by `\n`, the domain first: the serialization of the bridge's follow-up approvals. */215private func lineBytes(_ parts: [String]) -> Data { Data(parts.joined(separator: "\n").utf8) }216217/**218 A passkey-approved RE-SIGNATURE of a CCTP mint (the first signature is covered by the burn approval). Binds the transfer,219 the attested message and the exact fee parameters (`cctpMintRetryBytes` / `cctpSolMintRetryBytes`).220 */221public struct BridgeMintRetry: PasskeyApprovable, Hashable {222    public enum Parameters: Sendable, Hashable { case evm(EVMGasParameters), solana(SolanaBudget) }223    public let proposalId: String224    /** `0x` + 64 hexadecimal characters: the hash of Circle's attested message. */225    public let messageHash: String226    public let parameters: Parameters227228    public init(proposalId: String, messageHash: String, parameters: Parameters) { self.proposalId = proposalId; self.messageHash = messageHash; self.parameters = parameters }229230    /** Strict parse of `{ proposalId, messageHash, gas }` (EVM destination) or `{ proposalId, messageHash, sol }` (Solana destination). */231    public init(served json: JSONValue) throws {232        var o = try StrictObject(json, path: "mintRetry")233        proposalId = try o.string("proposalId"); messageHash = try o.string("messageHash")234        let gas = o.raw("gas"), sol = o.raw("sol")235        try o.finish()236        switch (gas, sol) {237        case (let g?, nil): parameters = .evm(try EVMGasParameters(strict: g, path: "mintRetry.gas"))238        case (nil, let s?): parameters = .solana(try SolanaBudget(strict: s, path: "mintRetry.sol"))239        default: throw ApprovalError.unsupported("mintRetry must carry exactly one of gas / sol")240        }241        try Self.checkLine(proposalId, "proposalId"); try Self.checkLine(messageHash, "messageHash")242    }243    static func checkLine(_ s: String, _ name: String) throws {244        guard !s.isEmpty, !s.utf8.contains(10) else { throw ApprovalError.unsupported("\(name) is empty or carries a line break") }245    }246247    public func canonicalBytes() throws -> Data {248        try Self.checkLine(proposalId, "proposalId"); try Self.checkLine(messageHash, "messageHash")249        switch parameters {250        case .evm(let g):251            return lineBytes(["SPW-BRIDGE-MINT-v1", proposalId, messageHash, String(g.nonce), g.gasLimit, g.maxFeePerGas, g.maxPriorityFeePerGas])252        case .solana(let s):253            try Self.checkLine(s.recentBlockhash, "recentBlockhash")254            return lineBytes(["SPW-BRIDGE-MINT-SOL-v1", proposalId, messageHash, s.recentBlockhash, String(s.lastValidBlockHeight), String(s.computeUnitLimit), s.computeUnitPrice])255        }256    }257}258259/** The reclaim of the refundable event-account deposit of a burn made on Solana (`cctpSolReclaimBytes`). Every reclaim needs the owner. */260public struct BridgeDepositReclaim: PasskeyApprovable, Hashable {261    public let proposalId: String262    public let eventAccount: String263    public let messageHash: String264    public let budget: SolanaBudget265266    public init(proposalId: String, eventAccount: String, messageHash: String, budget: SolanaBudget) {267        self.proposalId = proposalId; self.eventAccount = eventAccount; self.messageHash = messageHash; self.budget = budget268    }269    /** Strict parse of `{ proposalId, eventAccount, messageHash, sol }`. */270    public init(served json: JSONValue) throws {271        var o = try StrictObject(json, path: "reclaim")272        proposalId = try o.string("proposalId"); eventAccount = try o.string("eventAccount"); messageHash = try o.string("messageHash")273        budget = try SolanaBudget(strict: o.raw("sol"), path: "reclaim.sol")274        try o.finish()275    }276    public func canonicalBytes() throws -> Data {277        for (s, n) in [(proposalId, "proposalId"), (eventAccount, "eventAccount"), (messageHash, "messageHash"), (budget.recentBlockhash, "recentBlockhash")] { try BridgeMintRetry.checkLine(s, n) }278        return lineBytes(["SPW-BRIDGE-RECLAIM-v1", proposalId, eventAccount, messageHash, budget.recentBlockhash, String(budget.lastValidBlockHeight), String(budget.computeUnitLimit), budget.computeUnitPrice])279    }280}281282/** What the owner approves to open the wallet's own USDC token account on Solana (`SolTokenAccountSchema`, `solTokenAccountHash`). */283public struct SolanaTokenAccountRequest: PasskeyApprovable, Hashable {284    public let v: Int285    public let requestId, keyId, network, chainRef, owner, mint, tokenAccount, maxFee: String286    public let createdAt, expiresAt, policyVersion: Int287    public let budget: SolanaBudget288    public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt)) }289290    /** Strict parse of the request object: an unknown key is a refusal. */291    public init(served json: JSONValue) throws {292        var o = try StrictObject(json, path: "tokenAccountRequest")293        v = try o.int("v")294        guard v == 1 else { throw ApprovalError.unsupported("token-account request version \(v)") }295        requestId = try o.string("requestId"); keyId = try o.string("keyId"); network = try o.string("network"); chainRef = try o.string("chainRef")296        owner = try o.string("owner"); mint = try o.string("mint"); tokenAccount = try o.string("tokenAccount"); maxFee = try o.units("maxFee")297        createdAt = try o.int("createdAt"); expiresAt = try o.int("expiresAt"); policyVersion = try o.int("policyVersion")298        budget = try SolanaBudget(strict: o.raw("sol"), path: "tokenAccountRequest.sol")299        try o.finish()300    }301    public func canonicalBytes() throws -> Data {302        var w = CanonicalWriter(domain: "SPW-SOL-TOKEN-ACCOUNT-v1")303        w.field("v", "1"); w.field("requestId", requestId); w.field("keyId", keyId); w.field("network", network); w.field("chainRef", chainRef)304        w.field("owner", owner); w.field("mint", mint); w.field("tokenAccount", tokenAccount); w.field("maxFee", maxFee)305        w.field("createdAt", createdAt); w.field("expiresAt", expiresAt); w.field("policyVersion", policyVersion)306        w.field("sol.recentBlockhash", budget.recentBlockhash); w.field("sol.lastValidBlockHeight", budget.lastValidBlockHeight)307        w.field("sol.computeUnitLimit", budget.computeUnitLimit); w.field("sol.computeUnitPrice", budget.computeUnitPrice)308        return w.data309    }310}311312/** Exact product of two base-unit integers given as decimal text (schoolbook; `BaseUnits` multiplies by a 32-bit factor only). */313enum DecimalDigits {314    static func multiply(_ a: String, _ b: String) -> String {315        let x = a.utf8.reversed().map { Int($0) - 48 }, y = b.utf8.reversed().map { Int($0) - 48 }316        guard !x.isEmpty, !y.isEmpty, (x + y).allSatisfy({ (0...9).contains($0) }) else { return "0" }317        var out = [Int](repeating: 0, count: x.count + y.count)318        for (i, dx) in x.enumerated() where dx != 0 {319            var carry = 0320            for (j, dy) in y.enumerated() { let t = out[i + j] + dx * dy + carry; out[i + j] = t % 10; carry = t / 10 }321            var k = i + y.count322            while carry > 0 { let t = out[k] + carry; out[k] = t % 10; carry = t / 10; k += 1 }323        }324        while out.count > 1, out.last == 0 { out.removeLast() }325        return String(out.reversed().map { Character(UnicodeScalar(UInt8($0 + 48))) })326    }327}328
Files main
Menu

Theme