Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Foundation/BaseUnits.swift3// Description: Exact unsigned integer money arithmetic (base units, up to 2^256−1). No floating point is ever used for an amount.4// Mirrors packages/core/src/amounts.ts (parseUnits, formatUnits, baseUnits) of the SP Wallet backend.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910public enum AmountError: Error, Equatable, Sendable {11 case invalid, tooManyDecimals, overflow, badDecimals, negativeResult12}1314/** An unsigned integer of arbitrary size, stored as little-endian limbs in base 10^9. */15public struct BaseUnits: Sendable, Hashable, Comparable, CustomStringConvertible, Codable {16 private static let base: UInt64 = 1_000_000_00017 private var limbs: [UInt32] // little-endian, no trailing zero limb; empty = 01819 public static let zero = BaseUnits(limbs: [])20 /** 2^256 − 1: the largest amount the backend accepts. */21 public static let max256 = try! BaseUnits("115792089237316195423570985008687907853269984665640564039457584007913129639935")2223 private init(limbs: [UInt32]) { self.limbs = limbs }24 public init(_ v: UInt64) {25 var l: [UInt32] = [], x = v26 while x > 0 { l.append(UInt32(x % Self.base)); x /= Self.base }27 limbs = l28 }2930 /** Canonical base-unit string: "0" or digits without a leading zero, at most 78 digits. */31 public init(_ s: String) throws(AmountError) {32 guard !s.isEmpty, s.count <= 78, s.utf8.allSatisfy({ $0 >= 48 && $0 <= 57 }), s == "0" || s.first != "0" else { throw .invalid }33 self.limbs = Self.parseDigits(s)34 }3536 private static func parseDigits(_ s: String) -> [UInt32] {37 var l: [UInt32] = []38 let u = Array(s.utf8)39 var end = u.count40 while end > 0 {41 let start = Swift.max(0, end - 9)42 var v: UInt32 = 043 for k in start..<end { v = v * 10 + UInt32(u[k] - 48) }44 l.append(v); end = start45 }46 while let last = l.last, last == 0 { l.removeLast() }47 return l48 }4950 public var isZero: Bool { limbs.isEmpty }5152 public var description: String {53 guard let top = limbs.last else { return "0" }54 var s = String(top)55 for l in limbs.dropLast().reversed() { let p = String(l); s += String(repeating: "0", count: 9 - p.count) + p }56 return s57 }5859 public init(from decoder: Decoder) throws {60 let s = try decoder.singleValueContainer().decode(String.self)61 do { self = try BaseUnits(s) } catch { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "invalid base-unit integer")) }62 }63 public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(description) }6465 public static func < (a: BaseUnits, b: BaseUnits) -> Bool {66 if a.limbs.count != b.limbs.count { return a.limbs.count < b.limbs.count }67 for i in stride(from: a.limbs.count - 1, through: 0, by: -1) where a.limbs[i] != b.limbs[i] { return a.limbs[i] < b.limbs[i] }68 return false69 }7071 public static func + (a: BaseUnits, b: BaseUnits) -> BaseUnits {72 var out: [UInt32] = [], carry: UInt64 = 073 for i in 0..<Swift.max(a.limbs.count, b.limbs.count) {74 let s = UInt64(i < a.limbs.count ? a.limbs[i] : 0) + UInt64(i < b.limbs.count ? b.limbs[i] : 0) + carry75 out.append(UInt32(s % base)); carry = s / base76 }77 if carry > 0 { out.append(UInt32(carry)) }78 return BaseUnits(limbs: out)79 }8081 /** a − b; throws when b > a (an amount is never negative). */82 public func subtracting(_ b: BaseUnits) throws(AmountError) -> BaseUnits {83 guard b <= self else { throw .negativeResult }84 var out: [UInt32] = [], borrow: Int64 = 085 for i in 0..<limbs.count {86 var d = Int64(limbs[i]) - Int64(i < b.limbs.count ? b.limbs[i] : 0) - borrow87 if d < 0 { d += Int64(Self.base); borrow = 1 } else { borrow = 0 }88 out.append(UInt32(d))89 }90 while let last = out.last, last == 0 { out.removeLast() }91 return BaseUnits(limbs: out)92 }9394 public func multiplied(by m: UInt32) -> BaseUnits {95 guard m != 0, !isZero else { return .zero }96 var out: [UInt32] = [], carry: UInt64 = 097 for l in limbs { let p = UInt64(l) * UInt64(m) + carry; out.append(UInt32(p % Self.base)); carry = p / Self.base }98 while carry > 0 { out.append(UInt32(carry % Self.base)); carry /= Self.base }99 return BaseUnits(limbs: out)100 }101102 /** Integer division by a small divisor (rounds down). */103 public func divided(by d: UInt32) -> BaseUnits {104 precondition(d != 0)105 var out = [UInt32](repeating: 0, count: limbs.count), rem: UInt64 = 0106 for i in stride(from: limbs.count - 1, through: 0, by: -1) {107 let cur = rem * Self.base + UInt64(limbs[i])108 out[i] = UInt32(cur / UInt64(d)); rem = cur % UInt64(d)109 }110 while let last = out.last, last == 0 { out.removeLast() }111 return BaseUnits(limbs: out)112 }113114 // MARK: decimal text ↔ base units (parseUnits / formatUnits of the backend)115116 /**117 Parse what a person typed ("1.5", "1,5") into base units of an asset with `decimals` decimals.118 Refuses more significant decimals than the asset has (never rounds an amount silently) and anything above 2^256−1.119 */120 public static func parse(_ input: String, decimals: Int) throws(AmountError) -> BaseUnits {121 guard (0...36).contains(decimals) else { throw .badDecimals }122 var s = input.trimmingCharacters(in: .whitespaces)123 if let r = s.range(of: ",") { s.replaceSubrange(r, with: ".") } // first comma only, as the backend does124 let parts = s.split(separator: ".", omittingEmptySubsequences: false)125 guard parts.count <= 2, let intPart = parts.first, !intPart.isEmpty, intPart.count <= 60,126 intPart.utf8.allSatisfy({ $0 >= 48 && $0 <= 57 }) else { throw .invalid }127 let frac = parts.count == 2 ? parts[1] : ""128 guard frac.count <= 60, frac.utf8.allSatisfy({ $0 >= 48 && $0 <= 57 }) else { throw .invalid }129 if frac.count > decimals, frac.dropFirst(decimals).contains(where: { $0 != "0" }) { throw .tooManyDecimals }130 let kept = String(frac.prefix(decimals))131 var digits = String(intPart) + kept + String(repeating: "0", count: decimals - kept.count)132 while digits.count > 1, digits.first == "0" { digits.removeFirst() }133 guard digits.count <= 78 else { throw .overflow }134 let v = BaseUnits(limbs: parseDigits(digits))135 guard v <= max256 else { throw .overflow }136 return v137 }138139 /** Exact decimal text of the amount: no grouping, no trailing zero, "." as the separator (what the backend's `display` fields contain). */140 public func formatted(decimals: Int) -> String {141 precondition(decimals >= 0)142 var s = description143 if decimals == 0 { return s }144 if s.count <= decimals { s = String(repeating: "0", count: decimals - s.count + 1) + s }145 let cut = s.index(s.endIndex, offsetBy: -decimals)146 var frac = String(s[cut...])147 while frac.last == "0" { frac.removeLast() }148 return frac.isEmpty ? String(s[..<cut]) : String(s[..<cut]) + "." + frac149 }150151 /** Approximate value for charts and fiat estimates ONLY. Never used to build, compare or display an amount to approve. */152 public func approximate(decimals: Int) -> Double { Double(formatted(decimals: decimals)) ?? 0 }153}154