SPB Git

Repository Public

UInt256.swift 10.1 KB 250 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraCore/UInt256.swift8// Module           : Qyvora Core9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//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 Foundation42import QyvoraMath4344/// Unsigned 256-bit integer for amounts (wei, token base units). Money is never a floating-point value.45public struct UInt256: Equatable, Hashable, Comparable, Sendable, CustomStringConvertible, Codable {46    /// Four 64-bit limbs, least significant first.47    public private(set) var limbs: [UInt64]4849    public static let zero = UInt256(0)50    public static let max = UInt256(limbs: [.max, .max, .max, .max])5152    public init(_ value: UInt64) { limbs = [value, 0, 0, 0] }53    init(limbs: [UInt64]) { self.limbs = limbs }5455    public var isZero: Bool { limbs.allSatisfy { $0 == 0 } }5657    /// Big-endian bytes, at most 32; shorter input is zero-extended.58    public init?(bigEndian bytes: Bytes) {59        guard bytes.count <= 32 else { return nil }60        let padded = Bytes(repeating: 0, count: 32 - bytes.count) + bytes61        var l = [UInt64](repeating: 0, count: 4)62        for i in 0..<4 {63            var v: UInt64 = 064            for j in 0..<8 { v = v << 8 | UInt64(padded[(3 - i) * 8 + j]) }65            l[i] = v66        }67        limbs = l68    }6970    /// 32 bytes, big endian.71    public var bytes32: Bytes {72        var out = Bytes()73        for i in (0..<4).reversed() { out += Endian.be64(limbs[i]) }74        return out75    }7677    /// Big-endian bytes without leading zeros (empty for zero), as RLP expects.78    public var minimalBytes: Bytes { Bytes(bytes32.drop(while: { $0 == 0 })) }7980    public init?(hex: String) {81        var h = hex.hasPrefix("0x") || hex.hasPrefix("0X") ? String(hex.dropFirst(2)) : hex82        guard !h.isEmpty, h.count <= 64 else { return nil }83        if h.count % 2 == 1 { h = "0" + h }84        guard let b = Hex.decode(h) else { return nil }85        self.init(bigEndian: b)86    }8788    /// Minimal hexadecimal with 0x prefix ("0x0" for zero), as JSON-RPC quantities.89    public var hexQuantity: String {90        let h = Hex.encode(minimalBytes)91        let trimmed = h.drop(while: { $0 == "0" })92        return "0x" + (trimmed.isEmpty ? "0" : String(trimmed))93    }9495    /// Decimal digits only; nil on any other character or on overflow.96    public init?(decimal: String) {97        guard !decimal.isEmpty, decimal.utf8.allSatisfy({ $0 >= 0x30 && $0 <= 0x39 }) else { return nil }98        var v = UInt256.zero99        for c in decimal.utf8 {100            let (m, o1) = v.multipliedReportingOverflow(by: 10)101            let (s, o2) = m.addingReportingOverflow(UInt256(UInt64(c - 0x30)))102            if o1 || o2 { return nil }103            v = s104        }105        self = v106    }107108    public var description: String {109        if isZero { return "0" }110        var digits = [UInt8]()111        var v = self112        while !v.isZero {113            let (q, r) = v.quotientAndRemainder(dividingBy: 10)114            digits.append(UInt8(r) + 0x30)115            v = q116        }117        return String(decoding: digits.reversed(), as: UTF8.self)118    }119120    public var uint64: UInt64? { limbs[1] == 0 && limbs[2] == 0 && limbs[3] == 0 ? limbs[0] : nil }121122    public func addingReportingOverflow(_ other: UInt256) -> (UInt256, Bool) {123        var out = [UInt64](repeating: 0, count: 4)124        var carry = false125        for i in 0..<4 {126            let (s1, o1) = limbs[i].addingReportingOverflow(other.limbs[i])127            let (s2, o2) = s1.addingReportingOverflow(carry ? 1 : 0)128            out[i] = s2129            carry = o1 || o2130        }131        return (UInt256(limbs: out), carry)132    }133134    public func subtractingReportingOverflow(_ other: UInt256) -> (UInt256, Bool) {135        var out = [UInt64](repeating: 0, count: 4)136        var borrow = false137        for i in 0..<4 {138            let (s1, o1) = limbs[i].subtractingReportingOverflow(other.limbs[i])139            let (s2, o2) = s1.subtractingReportingOverflow(borrow ? 1 : 0)140            out[i] = s2141            borrow = o1 || o2142        }143        return (UInt256(limbs: out), borrow)144    }145146    public func multipliedReportingOverflow(by m: UInt64) -> (UInt256, Bool) {147        var out = [UInt64](repeating: 0, count: 4)148        var carry: UInt64 = 0149        for i in 0..<4 {150            let p = limbs[i].multipliedFullWidth(by: m)151            let (lo, o) = p.low.addingReportingOverflow(carry)152            out[i] = lo153            carry = p.high &+ (o ? 1 : 0)154        }155        return (UInt256(limbs: out), carry != 0)156    }157158    public func multipliedReportingOverflow(by other: UInt256) -> (UInt256, Bool) {159        var acc = [UInt64](repeating: 0, count: 8)160        for i in 0..<4 {161            var carry: UInt64 = 0162            for j in 0..<4 {163                let p = limbs[i].multipliedFullWidth(by: other.limbs[j])164                let (s1, o1) = acc[i + j].addingReportingOverflow(p.low)165                let (s2, o2) = s1.addingReportingOverflow(carry)166                acc[i + j] = s2167                carry = p.high &+ (o1 ? 1 : 0) &+ (o2 ? 1 : 0)168            }169            acc[i + 4] = carry170        }171        return (UInt256(limbs: Array(acc[0..<4])), acc[4...].contains { $0 != 0 })172    }173174    public func quotientAndRemainder(dividingBy d: UInt64) -> (UInt256, UInt64) {175        precondition(d != 0)176        var out = [UInt64](repeating: 0, count: 4)177        var rem: UInt64 = 0178        for i in (0..<4).reversed() {179            let (q, r) = d.dividingFullWidth((rem, limbs[i]))180            out[i] = q181            rem = r182        }183        return (UInt256(limbs: out), rem)184    }185186    public static func < (a: UInt256, b: UInt256) -> Bool {187        for i in (0..<4).reversed() where a.limbs[i] != b.limbs[i] { return a.limbs[i] < b.limbs[i] }188        return false189    }190191    /// Trapping operators for values known to be in range; use the reporting forms on external input.192    public static func + (a: UInt256, b: UInt256) -> UInt256 {193        let (s, o) = a.addingReportingOverflow(b)194        precondition(!o, "UInt256 overflow")195        return s196    }197198    public static func - (a: UInt256, b: UInt256) -> UInt256 {199        let (s, o) = a.subtractingReportingOverflow(b)200        precondition(!o, "UInt256 underflow")201        return s202    }203204    public init(from decoder: Decoder) throws {205        let s = try decoder.singleValueContainer().decode(String.self)206        guard let v = UInt256(decimal: s) else {207            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "not a decimal integer"))208        }209        self = v210    }211212    public func encode(to encoder: Encoder) throws {213        var c = encoder.singleValueContainer()214        try c.encode(description)215    }216}217218/// Conversion between base units and decimal strings ("1.5" ETH ⇄ 1500000000000000000 wei).219public enum BaseUnits {220    /// Largest number of decimals handled (ERC-20 `decimals()` is a uint8).221    public static let maximumDecimals = 255222223    /// Parses a non-negative decimal amount with at most `decimals` fractional digits. Accepts "." only.224    public static func parse(_ text: String, decimals: Int) -> UInt256? {225        // a 256-bit value has 78 digits: anything outside this range cannot be an amount, and a hostile `decimals`226        // (negative, or huge) must neither trap nor allocate227        guard (0...maximumDecimals).contains(decimals), text.utf8.count <= 2 * maximumDecimals + 1 else { return nil }228        let parts = text.split(separator: ".", omittingEmptySubsequences: false)229        guard parts.count == 1 || parts.count == 2 else { return nil }230        let whole = String(parts[0]), frac = parts.count == 2 ? String(parts[1]) : ""231        guard !(whole.isEmpty && frac.isEmpty), frac.count <= decimals else { return nil }232        let digits = (whole.isEmpty ? "0" : whole) + frac + String(repeating: "0", count: decimals - frac.count)233        return UInt256(decimal: digits)234    }235236    /// Exact decimal string, trailing zeros removed; `maxFractionDigits` truncates (never rounds up) for display.237    public static func format(_ value: UInt256, decimals: Int, maxFractionDigits: Int? = nil) -> String {238        var s = value.description239        // out-of-range `decimals` (a corrupted token entry) is clamped instead of trapping in `dropLast` or allocating240        let decimals = min(max(decimals, 0), maximumDecimals)241        if decimals == 0 { return s }242        if s.count <= decimals { s = String(repeating: "0", count: decimals - s.count + 1) + s }243        let whole = String(s.dropLast(decimals))244        var frac = String(s.suffix(decimals))245        if let m = maxFractionDigits, frac.count > max(0, m) { frac = String(frac.prefix(max(0, m))) }246        while frac.hasSuffix("0") { frac.removeLast() }247        return frac.isEmpty ? whole : whole + "." + frac248    }249}250
Files main
Menu

Theme