SPB Git

Repository Public

DerivativesPrimitives.swift 14.3 KB 308 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SPWalletCore9// File             : Sources/SPWalletCore/Domains/Derivatives/DerivativesPrimitives.swift10// Description      : The three primitives the derivatives canonical objects11//                    need, each ported from the backend and vector-tested12//                    against it: exact decimal strings13//                    (packages/derivatives/src/decimal.ts: parse, canonical14//                    text, compare, multiply, truncate), Keccak-256 (the hash15//                    of the Hyperliquid client order id,16//                    packages/derivatives/src/venues/hyperliquid/trading.ts17//                    `hlCloid`), and the sorted-key JSON of the risk intents18//                    (services/api/src/derivatives/exec.ts `stableJson`). No19//                    floating point anywhere. Keccak lives here until the lead20//                    deduplicates it with Crypto/.21// Module           : SPWalletCore22// Repository       : https://git.spboucher.ai/sp-wallet-core23// Created          : 2026-11-1824// Last Modified    : 2026-11-1825//26// =============================================================================27// AUTHOR & PROFESSIONAL AFFILIATION28// =============================================================================29//30// Author           : Simon-Pierre Boucher31// Position         : Professor of Finance32// Institution      : Université du Québec en Outaouais (UQO)33// Department       : Département des sciences administratives34// Organization     : SP Boucher35//36// Website          : https://spboucher.ai37// Git              : https://git.spboucher.ai38//39// =============================================================================40// OFFICIAL CONTACT DIRECTORY41// =============================================================================42//43// General          : info@spboucher.ai44// Professional     : contact@spboucher.ai45// Direct           : simon@spboucher.ai46// Research         : research@spboucher.ai47// Development      : dev@spboucher.ai48// Support          : support@spboucher.ai49// Security/Admin   : admin@spboucher.ai50// Notifications    : notifications@spboucher.ai51//52// Preferred Contact: support@spboucher.ai53//54// =============================================================================55// COPYRIGHT & INTELLECTUAL PROPERTY56// =============================================================================57//58// Copyright (c) 202659// Simon-Pierre Boucher60//61// All rights reserved where applicable.62//63// This file is governed by the applicable project license,64// copyright notices, institutional agreements and relevant law.65//66// Unless expressly authorized by the applicable license or67// rights holder, copying, redistribution, sublicensing,68// publication and commercial exploitation are not permitted.69//70// Existing third-party rights and notices remain unaffected.71//72// =============================================================================73// CONFIDENTIALITY & SECURITY74// =============================================================================75//76// Classification   : Public77// Distribution     : Public repository; use is governed by the project license78// Security Contact : admin@spboucher.ai79//80// Access to this source does not independently grant permission81// to redistribute or disclose confidential materials.82//83// Do not embed credentials, private keys, access tokens,84// certificates or confidential personal information.85//86// =============================================================================87// LICENSE & MAINTENANCE88// =============================================================================89//90// License          : None specified (no license file in this repository)91// Maintainer       : Simon-Pierre Boucher92// Technical Contact: dev@spboucher.ai93//94// =============================================================================95// END OF SP BOUCHER SOURCE HEADER96// =============================================================================9798import Foundation99import CryptoKit100101/** A decimal the backend's `D.from` accepts: `-?(0|[1-9]\d*)(\.\d+)?`, at most 60 digits. Normalised exactly as `D` does. */102public struct VenueDecimal: Sendable, Hashable, Comparable, CustomStringConvertible {103    public static let maxDigits = 60104    /** Mantissa digits (0–9), most significant first, without a leading zero; empty = zero. */105    private let digits: [UInt8]106    /** Number of mantissa digits after the decimal point; no trailing zero is ever kept. */107    public let scale: Int108    public let isNegative: Bool109110    public static let zero = VenueDecimal(digits: [], scale: 0, negative: false)111112    /** The backend's `mk`: zero is {0, 0} without a sign, trailing zeros of the fraction are dropped. */113    private init(digits d: [UInt8], scale s: Int, negative: Bool) {114        var d = Array(d.drop(while: { $0 == 0 })), s = s115        if d.isEmpty { digits = []; scale = 0; isNegative = false; return }116        while s > 0, d.last == 0 { d.removeLast(); s -= 1 }117        digits = d; scale = s; isNegative = negative118    }119120    /** Nil when the text is not a decimal the backend would parse (exponent, "+", leading zero, ".5", more than 60 digits…). */121    public init?(_ text: String) {122        let u = Array(text.utf8)123        guard !u.isEmpty, u.count <= Self.maxDigits + 2 else { return nil }124        var i = 0125        let negative = u[0] == 45126        if negative { i = 1 }127        let intStart = i128        while i < u.count, u[i] >= 48, u[i] <= 57 { i += 1 }129        let intPart = u[intStart..<i]130        guard !intPart.isEmpty, intPart.count == 1 || intPart.first != 48 else { return nil }131        var frac: ArraySlice<UInt8> = []132        if i < u.count {133            guard u[i] == 46 else { return nil }134            frac = u[(i + 1)...]135            guard !frac.isEmpty, frac.allSatisfy({ $0 >= 48 && $0 <= 57 }) else { return nil }136        }137        guard intPart.count + frac.count <= Self.maxDigits else { return nil }138        self.init(digits: (Array(intPart) + Array(frac)).map { $0 - 48 }, scale: frac.count, negative: negative)139    }140141    public var isZero: Bool { digits.isEmpty }142    public var isPositive: Bool { !digits.isEmpty && !isNegative }143144    /** The backend's `D.str`: no exponent, no trailing zero, "0" for zero. */145    public var description: String {146        guard !digits.isEmpty else { return "0" }147        var s = digits.map { String($0) }.joined()148        if scale > 0 {149            if s.count <= scale { s = String(repeating: "0", count: scale - s.count + 1) + s }150            let cut = s.index(s.endIndex, offsetBy: -scale)151            s = s[..<cut] + "." + s[cut...]152        }153        return isNegative ? "-" + s : s154    }155156    private func magnitude(atScale s: Int) -> [UInt8] { digits + [UInt8](repeating: 0, count: s - scale) }157    private static func magnitudeLess(_ a: VenueDecimal, _ b: VenueDecimal) -> Bool {158        let s = Swift.max(a.scale, b.scale), x = a.magnitude(atScale: s), y = b.magnitude(atScale: s)159        if x.count != y.count { return x.count < y.count }160        return x.lexicographicallyPrecedes(y)161    }162    public static func < (a: VenueDecimal, b: VenueDecimal) -> Bool {163        if a.isNegative != b.isNegative { return a.isNegative }164        return a.isNegative ? magnitudeLess(b, a) : magnitudeLess(a, b)165    }166167    /** Exact product (`D.mul`). */168    public func multiplied(by o: VenueDecimal) -> VenueDecimal {169        guard !isZero, !o.isZero else { return .zero }170        var acc = [Int](repeating: 0, count: digits.count + o.digits.count)171        for (i, a) in digits.enumerated().reversed() {172            for (j, b) in o.digits.enumerated().reversed() { acc[i + j + 1] += Int(a) * Int(b) }173        }174        var carry = 0175        for k in stride(from: acc.count - 1, through: 0, by: -1) { let v = acc[k] + carry; acc[k] = v % 10; carry = v / 10 }176        return VenueDecimal(digits: acc.map { UInt8($0) }, scale: scale + o.scale, negative: isNegative != o.isNegative)177    }178179    /** Cut to `decimals` decimals towards zero (`D.quantize(x, 10^-decimals, 'down')` for a non-negative value). */180    public func truncated(toDecimals decimals: Int) -> VenueDecimal {181        precondition(decimals >= 0)182        guard scale > decimals else { return self }183        let drop = scale - decimals184        return VenueDecimal(digits: drop >= digits.count ? [] : Array(digits.dropLast(drop)), scale: decimals, negative: isNegative)185    }186187    /**188     The value × 10^decimals as an integer string (`scaleExact` of packages/derivatives/src/live/gmx.ts, `usdcUnits` of collateral.ts).189     Nil when the value is negative or carries more decimals than the unit has: an amount is never rounded.190     */191    public func units(decimals: Int) -> String? {192        guard !isNegative, scale <= decimals else { return nil }193        guard !digits.isEmpty else { return "0" }194        return (digits + [UInt8](repeating: 0, count: decimals - scale)).map { String($0) }.joined()195    }196197    /** True when both texts are decimals of the same value ("1.50" and "1.5"). */198    public static func same(_ a: String, _ b: String) -> Bool {199        guard let x = VenueDecimal(a), let y = VenueDecimal(b) else { return false }200        return x == y201    }202}203204/** Keccak-256 (the pre-NIST padding Ethereum and Hyperliquid use), FIPS 202 permutation. Vector-tested against @noble/hashes. */205public enum Keccak256 {206    private static let roundConstants: [UInt64] = [207        0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000, 0x000000000000808b, 0x0000000080000001,208        0x8000000080008081, 0x8000000000008009, 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a,209        0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080,210        0x000000000000800a, 0x800000008000000a, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,211    ]212    private static let rotations = [1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14, 27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44]213    private static let lanes = [10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4, 15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1]214    private static let rate = 136215216    private static func permute(_ st: inout [UInt64]) {217        var bc = [UInt64](repeating: 0, count: 5)218        for round in 0..<24 {219            for i in 0..<5 { bc[i] = st[i] ^ st[i + 5] ^ st[i + 10] ^ st[i + 15] ^ st[i + 20] }220            for i in 0..<5 {221                let t = bc[(i + 4) % 5] ^ ((bc[(i + 1) % 5] << 1) | (bc[(i + 1) % 5] >> 63))222                for j in stride(from: 0, to: 25, by: 5) { st[j + i] ^= t }223            }224            var t = st[1]225            for i in 0..<24 {226                let j = lanes[i], keep = st[j], r = UInt64(rotations[i])227                st[j] = (t << r) | (t >> (64 - r)); t = keep228            }229            for j in stride(from: 0, to: 25, by: 5) {230                for i in 0..<5 { bc[i] = st[j + i] }231                for i in 0..<5 { st[j + i] ^= ~bc[(i + 1) % 5] & bc[(i + 2) % 5] }232            }233            st[0] ^= roundConstants[round]234        }235    }236237    public static func hash(_ data: Data) -> Data {238        var bytes = [UInt8](data)239        bytes.append(0x01)240        while bytes.count % rate != 0 { bytes.append(0) }241        bytes[bytes.count - 1] |= 0x80242        var st = [UInt64](repeating: 0, count: 25)243        for block in stride(from: 0, to: bytes.count, by: rate) {244            for lane in 0..<(rate / 8) {245                var v: UInt64 = 0246                for b in 0..<8 { v |= UInt64(bytes[block + lane * 8 + b]) << UInt64(8 * b) }247                st[lane] ^= v248            }249            permute(&st)250        }251        var out = Data(capacity: 32)252        for lane in 0..<4 { for b in 0..<8 { out.append(UInt8((st[lane] >> UInt64(8 * b)) & 0xff)) } }253        return out254    }255}256257public enum HyperliquidClientOrderID {258    /**259     The venue's client order id of an Idempotency-Key (`hlCloid`): the key itself when it already is a 128-bit hex id, otherwise the260     first 16 bytes of Keccak-256("spw/hyperliquid/cloid/v1:" + key). Nil when the key is not 1–128 characters.261     */262    public static func derive(from key: String) -> String? {263        guard key.utf16.count >= 1, key.utf16.count <= 128 else { return nil }264        let u = Array(key.utf8)265        if u.count == 34, u[0] == 48, u[1] == 120, u[2...].allSatisfy({ ($0 >= 48 && $0 <= 57) || ($0 >= 97 && $0 <= 102) }) { return key }266        return "0x" + Keccak256.hash(Data("spw/hyperliquid/cloid/v1:\(key)".utf8)).prefix(16).hex267    }268}269270/** `stableJson` of the backend: keys in JavaScript's default sort order, `JSON.stringify` for strings, no whitespace. */271enum StableJSON {272    static func string(_ v: JSONValue) throws -> String {273        switch v {274        case .null: return "null"275        case .bool(let b): return b ? "true" : "false"276        case .int(let i): return String(i)277        case .double: throw ApprovalError.unsupported("a non-integer number cannot be serialized exactly")278        case .string(let s): return quote(s)279        case .array(let a): return "[" + (try a.map(string)).joined(separator: ",") + "]"280        case .object(let o):281            return "{" + (try o.keys.sorted { $0.utf16.lexicographicallyPrecedes($1.utf16) }.map { "\(quote($0)):\(try string(o[$0]!))" }).joined(separator: ",") + "}"282        }283    }284285    /** ECMAScript `QuoteJSONString`: only `"`, `\` and the code units below U+0020 are escaped. */286    static func quote(_ s: String) -> String {287        var out = "\""288        for u in s.unicodeScalars {289            switch u.value {290            case 0x22: out += "\\\""291            case 0x5c: out += "\\\\"292            case 0x08: out += "\\b"293            case 0x09: out += "\\t"294            case 0x0a: out += "\\n"295            case 0x0c: out += "\\f"296            case 0x0d: out += "\\r"297            case 0..<0x20: out += String(format: "\\u%04x", u.value)298            default: out.unicodeScalars.append(u)299            }300        }301        return out + "\""302    }303}304305enum DerivHash {306    static func sha256Hex(_ text: String) -> String { Data(SHA256.hash(data: Data(text.utf8))).hex }307}308
Files main
Menu

Theme