SPB Git

Repository Public

ChainFormatting.swift 16.2 KB 316 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraUI/ChainFormatting.swift8// Module           : Qyvora UI9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation4243/// How many fraction digits an amount is shown with. The thirteen chains use 8 (Bitcoin family), 18 (EVM), 9 (Solana)44/// and 6 (TRON, most stablecoins) decimals: showing them all would fill a row with digits nobody reads, and a fixed45/// number would hide small balances. The rule keeps at least four significant digits and never rounds up.46public enum AssetPrecision {47    public enum Kind: Sendable, Equatable {48        /// The coin of a chain (BTC, ETH, SOL, TRX…).49        case native50        /// Any token.51        case token52        /// A token pegged to a currency: two fraction digits, always.53        case stable54    }5556    /// Fraction digits to show for `units` base units of an asset with `decimals` decimals.57    ///58    /// - one thousand or more: 2 digits; one or more: 4 digits;59    /// - below one: the leading zeros plus four significant digits, at most `cap` (8) and never more than `decimals`;60    /// - a stable token: 2 digits.61    public static func fractionDigits(units: String, decimals: Int, kind: Kind = .native, cap: Int = 8) -> Int {62        let decimals = max(0, decimals)63        let cap = max(0, min(cap, decimals))64        if kind == .stable { return min(2, decimals) }65        let digits = AmountFormat.normalizedUnits(units)66        let integerDigits = max(0, digits.count - decimals)67        if integerDigits >= 4 { return min(2, cap) }68        if integerDigits >= 1 { return min(4, cap) }69        if digits == "0" { return min(2, cap) }70        let leadingZeros = decimals - digits.count71        return min(cap, leadingZeros + 4)72    }7374    /// Digits accepted by an amount field for an asset: all of them up to 8 (nobody types the 18th decimal of ether).75    public static func entryFractionDigits(decimals: Int) -> Int { max(0, min(decimals, 8)) }76}7778public extension AmountFormat {79    /// The amount with the display precision of `AssetPrecision`. Stable tokens keep two fraction digits.80    /// From one million upwards, with `compactLarge`, the amount is written in compact notation ("1.23M").81    static func display(units: String, decimals: Int, kind: AssetPrecision.Kind = .native, compactLarge: Bool = false,82                        groupingSeparator: String = ",", decimalSeparator: String = ".") -> String {83        if compactLarge, let short = compact(units: units, decimals: decimals, decimalSeparator: decimalSeparator) { return short }84        let digits = AssetPrecision.fractionDigits(units: units, decimals: decimals, kind: kind)85        return format(units: units, decimals: decimals, maxFractionDigits: digits, minFractionDigits: kind == .stable ? min(2, max(0, decimals)) : 0,86                      groupingSeparator: groupingSeparator, decimalSeparator: decimalSeparator)87    }8889    /// Compact notation for a large amount: "1.23M", "45.6B", "7.89T", "12.3Q" (thousands of trillions and above keep90    /// the last suffix with a grouped figure). Returns nil below `threshold` whole units (one million by default).91    /// Three significant digits, truncated: a balance is never shown larger than it is.92    static func compact(units: String, decimals: Int, thresholdDigits: Int = 7, decimalSeparator: String = ".") -> String? {93        let digits = normalizedUnits(units)94        let decimals = max(0, decimals)95        guard digits.count > decimals else { return nil }96        let integerPart = String(digits.dropLast(decimals))97        guard integerPart.count >= max(4, thresholdDigits) else { return nil }98        let suffixes = ["K", "M", "B", "T", "Q"]99        let group = min((integerPart.count - 1) / 3, suffixes.count)100        let headCount = integerPart.count - group * 3101        let head = String(integerPart.prefix(headCount))102        let rest = integerPart.dropFirst(headCount)103        let fractionCount = max(0, 3 - headCount)104        var fraction = String(rest.prefix(fractionCount))105        while fraction.last == "0" { fraction.removeLast() }106        let figure = AmountFormat.group(head, separator: ",")107        return figure + (fraction.isEmpty ? "" : decimalSeparator + fraction) + suffixes[group - 1]108    }109}110111/// Fiat values, formatted for a currency code. The wallet never computes with these strings.112public enum FiatFormat {113    /// "$1,234.56", "1 234,56 €", "CA$12.00"… according to `locale`. Values below one cent (and above zero) are shown114    /// as "<$0.01"; non-finite values return nil (the caller then shows nothing rather than a wrong figure).115    public static func format(_ value: Double, currency: String, locale: Locale = .current, compactLarge: Bool = false) -> String? {116        guard value.isFinite else { return nil }117        let formatter = NumberFormatter()118        formatter.numberStyle = .currency119        formatter.locale = locale120        formatter.currencyCode = currency.uppercased()121        formatter.roundingMode = .down122        let magnitude = abs(value)123        if magnitude > 0, magnitude < 0.01 {124            guard let floor = formatter.string(from: 0.01) else { return nil }125            return (value < 0 ? "−" : "") + "<" + floor126        }127        if compactLarge, magnitude >= 1_000_000 {128            let steps: [(Double, String)] = [(1e12, "T"), (1e9, "B"), (1e6, "M")]129            for (scale, suffix) in steps where magnitude >= scale {130                formatter.maximumFractionDigits = 2131                formatter.minimumFractionDigits = 0132                guard let text = formatter.string(from: NSNumber(value: magnitude / scale)) else { return nil }133                return (value < 0 ? "−" : "") + insert(suffix, afterFigureIn: text)134            }135        }136        guard let text = formatter.string(from: NSNumber(value: magnitude)) else { return nil }137        return (value < 0 ? "−" : "") + text138    }139140    /// Puts a magnitude suffix right after the last digit ("$1.2" → "$1.2M", "1,2 €" → "1,2M €").141    static func insert(_ suffix: String, afterFigureIn text: String) -> String {142        guard let last = text.lastIndex(where: { $0.isNumber }) else { return text + suffix }143        var out = text144        out.insert(contentsOf: suffix, at: out.index(after: last))145        return out146    }147148    /// A signed percentage for a change given as a fraction: "+2.41%", "−0.80%", "0.00%". The sign is always written,149    /// so the direction never depends on colour.150    public static func percentChange(_ fraction: Double, fractionDigits: Int = 2, decimalSeparator: String = ".") -> String? {151        guard fraction.isFinite else { return nil }152        let scale = pow(10, Double(max(0, fractionDigits)))153        let rounded = (abs(fraction) * 100 * scale).rounded() / scale154        var text = String(format: "%.\(max(0, fractionDigits))f", rounded)155        if decimalSeparator != "." { text = text.replacingOccurrences(of: ".", with: decimalSeparator) }156        if rounded == 0 { return text + "%" }157        return (fraction < 0 ? "−" : "+") + text + "%"158    }159}160161/// Short relative times for rows and sync states: "just now", "4 min ago", "3 h ago", "yesterday", "5 d ago", then162/// a date. Deterministic (no locale-dependent wording), so the same text is read everywhere.163public enum RelativeTime {164    public static func text(for date: Date, now: Date = Date(), calendar: Calendar = .current, locale: Locale = .current) -> String {165        let seconds = now.timeIntervalSince(date)166        if seconds < 0 { return "just now" }167        if seconds < 60 { return "just now" }168        if seconds < 3600 { return "\(Int(seconds / 60)) min ago" }169        if seconds < 86_400 { return "\(Int(seconds / 3600)) h ago" }170        let days = Int(seconds / 86_400)171        if days == 1 { return "yesterday" }172        if days < 7 { return "\(days) d ago" }173        let formatter = DateFormatter()174        formatter.calendar = calendar175        formatter.locale = locale176        formatter.timeZone = calendar.timeZone177        let sameYear = calendar.component(.year, from: date) == calendar.component(.year, from: now)178        formatter.setLocalizedDateFormatFromTemplate(sameYear ? "dMMM" : "dMMMy")179        return formatter.string(from: date)180    }181182    /// The same value in words for VoiceOver ("4 minutes ago").183    public static func spoken(for date: Date, now: Date = Date()) -> String {184        let seconds = now.timeIntervalSince(date)185        if seconds < 60 { return "just now" }186        if seconds < 3600 { let m = Int(seconds / 60); return "\(m) minute\(m == 1 ? "" : "s") ago" }187        if seconds < 86_400 { let h = Int(seconds / 3600); return "\(h) hour\(h == 1 ? "" : "s") ago" }188        let days = Int(seconds / 86_400)189        if days == 1 { return "yesterday" }190        if days < 7 { return "\(days) days ago" }191        return text(for: date, now: now)192    }193}194195/// WCAG 2 contrast arithmetic on sRGB values, used by the unit tests that audit the palette.196public enum QContrast {197    /// Relative luminance of an sRGB colour (0xRRGGBB).198    public static func luminance(_ rgb: UInt32) -> Double {199        func channel(_ shift: UInt32) -> Double {200            let c = Double((rgb >> shift) & 0xff) / 255201            return c <= 0.03928 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4)202        }203        return 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0)204    }205206    /// Contrast ratio between two colours, from 1 to 21.207    public static func ratio(_ a: UInt32, _ b: UInt32) -> Double {208        let la = luminance(a), lb = luminance(b)209        return (max(la, lb) + 0.05) / (min(la, lb) + 0.05)210    }211212    /// `foreground` at `opacity` over `background`, as an opaque sRGB value (tinted pills and wells).213    public static func composite(_ foreground: UInt32, opacity: Double, over background: UInt32) -> UInt32 {214        let a = min(1, max(0, opacity))215        func mix(_ shift: UInt32) -> UInt32 {216            let f = Double((foreground >> shift) & 0xff), b = Double((background >> shift) & 0xff)217            return UInt32((f * a + b * (1 - a)).rounded()) << shift218        }219        return mix(16) | mix(8) | mix(0)220    }221222    /// Minimum ratio for body text.223    public static let text = 4.5224    /// Minimum ratio for large text, glyphs and the boundary of a control.225    public static let graphic = 3.0226}227228/// An address cut into groups for comparison by eye. Chains whose addresses carry no checksum (or whose checksum229/// the user cannot see) leave the comparison to the person: the groups make it possible, and the first and last230/// ones are emphasised because that is where a substituted address is designed to look alike — eight characters on231/// each side, more than a look-alike address can cheaply match.232public enum AddressChunks {233    public struct Chunk: Sendable, Equatable, Identifiable {234        public enum Role: Sendable, Equatable { case prefix, emphasized, plain }235        public let id: Int236        public let text: String237        public let role: Role238    }239240    /// The scheme part that is identical for every address of a network and carries no information to compare:241    /// "0x", or everything up to and including a colon ("bitcoincash:").242    public static func prefix(of address: String) -> String {243        if let colon = address.firstIndex(of: ":") { return String(address[...colon]) }244        if address.hasPrefix("0x") || address.hasPrefix("0X") { return String(address.prefix(2)) }245        return ""246    }247248    /// Splits `address` into its prefix (if any) and groups of `size` characters; the first and last249    /// `emphasizedGroups` groups are marked. Concatenating the chunks gives back the address exactly.250    public static func chunks(_ address: String, size: Int = 4, emphasizedGroups: Int = 2) -> [Chunk] {251        let size = max(1, size)252        let lead = prefix(of: address)253        let body = Array(address.dropFirst(lead.count))254        var groups: [String] = []255        var index = 0256        while index < body.count {257            groups.append(String(body[index..<min(index + size, body.count)]))258            index += size259        }260        let marked = max(0, emphasizedGroups)261        // a short value is not worth emphasising: every group would be marked262        let emphasise = groups.count > marked * 2263        var out: [Chunk] = []264        if !lead.isEmpty { out.append(Chunk(id: 0, text: lead, role: .prefix)) }265        for (i, group) in groups.enumerated() {266            let edge = i < marked || i >= groups.count - marked267            out.append(Chunk(id: out.count, text: group, role: emphasise && edge ? .emphasized : .plain))268        }269        return out270    }271272    /// What VoiceOver reads: the groups separated by spaces, so that the address is spelt group by group.273    public static func spoken(_ address: String, size: Int = 4) -> String {274        chunks(address, size: size).map(\.text).joined(separator: " ")275    }276}277278/// Shares of a portfolio, per chain or per asset.279public enum AllocationMath {280    /// One fraction per value (negative and non-finite values count as zero); all zeros when nothing is positive.281    public static func shares(_ values: [Double]) -> [Double] { Proportions.fractions(values) }282283    /// Whole percentages that add up to exactly 100 (largest-remainder method), so that a legend never sums to 99284    /// or 101. All zeros when the shares are all zero.285    public static func wholePercents(_ shares: [Double]) -> [Int] {286        let clean = Proportions.fractions(shares)287        guard clean.contains(where: { $0 > 0 }) else { return clean.map { _ in 0 } }288        let exact = clean.map { $0 * 100 }289        var floors = exact.map { Int($0.rounded(.down)) }290        let missing = 100 - floors.reduce(0, +)291        let order = exact.enumerated().sorted { a, b in292            let ra = a.element - a.element.rounded(.down), rb = b.element - b.element.rounded(.down)293            return ra == rb ? a.offset < b.offset : ra > rb294        }295        for i in 0..<max(0, min(missing, order.count)) { floors[order[i].offset] += 1 }296        return floors297    }298299    /// "42%", "<1%" for a positive share that rounds to zero, "0%" for none.300    public static func percentText(share: Double, wholePercent: Int) -> String {301        if share > 0, wholePercent == 0 { return "<1%" }302        return "\(wholePercent)%"303    }304305    /// Indices of the entries kept as their own segment, largest first, and the indices folded into "Other".306    /// At most `maxSegments` segments are drawn in total (the "Other" one included); entries of zero are dropped.307    public static func grouping(_ values: [Double], maxSegments: Int) -> (kept: [Int], other: [Int]) {308        let positive = values.enumerated().filter { $0.element.isFinite && $0.element > 0 }309            .sorted { $0.element == $1.element ? $0.offset < $1.offset : $0.element > $1.element }310            .map(\.offset)311        let limit = max(1, maxSegments)312        guard positive.count > limit else { return (positive, []) }313        return (Array(positive.prefix(limit - 1)), Array(positive.dropFirst(limit - 1)))314    }315}316
Files main
Menu

Theme