Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraSolana/SolanaJSON.swift8// Module : Qyvora Solana9// 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 Foundation42import QyvoraMath4344/// JSON value that keeps numbers as their literal text.45///46/// `JSONValue` of the networking module stores numbers as `Double`, which is exact only up to 2^53: a lamport amount47/// is a 64-bit integer, so the Solana client parses answers with this type instead and reads integers exactly48/// (`uint64`). The parser is strict (RFC 8259, no trailing data, no duplicate key, valid UTF-8) and bounded in depth,49/// so that a hostile endpoint cannot exhaust the stack.50public enum SolanaJSON: Equatable, Sendable {51 case null52 case bool(Bool)53 /// The literal as it appears in the document, e.g. "18446744073709551615" or "-1.5e3".54 case number(String)55 case string(String)56 case array([SolanaJSON])57 case object([String: SolanaJSON])5859 public static let defaultMaximumDepth = 646061 public static func integer(_ v: UInt64) -> SolanaJSON { .number(String(v)) }62 public static func integer(_ v: Int) -> SolanaJSON { .number(String(v)) }6364 public var string: String? { if case .string(let s) = self { return s }; return nil }65 public var bool: Bool? { if case .bool(let b) = self { return b }; return nil }66 public var array: [SolanaJSON]? { if case .array(let a) = self { return a }; return nil }67 public var object: [String: SolanaJSON]? { if case .object(let o) = self { return o }; return nil }68 public var isNull: Bool { self == .null }69 public subscript(key: String) -> SolanaJSON? { object?[key] }7071 /// The number when it is written as a plain non-negative integer that fits in 64 bits (no sign, fraction or exponent).72 public var uint64: UInt64? {73 guard case .number(let text) = self, !text.isEmpty, text.utf8.allSatisfy({ $0 >= 0x30 && $0 <= 0x39 }) else { return nil }74 return UInt64(text)75 }7677 /// The number when it is written as a plain integer that fits in a signed 64-bit integer.78 public var int64: Int64? {79 guard case .number(let text) = self else { return nil }80 let digits = text.hasPrefix("-") ? text.dropFirst() : Substring(text)81 guard !digits.isEmpty, digits.utf8.allSatisfy({ $0 >= 0x30 && $0 <= 0x39 }) else { return nil }82 return Int64(text)83 }8485 /// Parses a complete JSON document; nil when it is not valid JSON, nests deeper than `maximumDepth`, repeats a key86 /// inside an object or is followed by anything but white space.87 public static func parse(_ data: Data, maximumDepth: Int = defaultMaximumDepth) -> SolanaJSON? {88 parse(Bytes(data), maximumDepth: maximumDepth)89 }9091 public static func parse(_ bytes: Bytes, maximumDepth: Int = defaultMaximumDepth) -> SolanaJSON? {92 var parser = Parser(bytes: bytes, depthLeft: maximumDepth)93 parser.skipWhiteSpace()94 guard let value = parser.value() else { return nil }95 parser.skipWhiteSpace()96 return parser.position == bytes.count ? value : nil97 }9899 /// Compact serialization with sorted keys (deterministic).100 public func serialized() -> String {101 var out = ""102 write(to: &out)103 return out104 }105106 private func write(to out: inout String) {107 switch self {108 case .null: out += "null"109 case .bool(let b): out += b ? "true" : "false"110 case .number(let n): out += n111 case .string(let s): Self.write(string: s, to: &out)112 case .array(let a):113 out += "["114 for (i, v) in a.enumerated() {115 if i > 0 { out += "," }116 v.write(to: &out)117 }118 out += "]"119 case .object(let o):120 out += "{"121 for (i, key) in o.keys.sorted().enumerated() {122 if i > 0 { out += "," }123 Self.write(string: key, to: &out)124 out += ":"125 o[key]!.write(to: &out)126 }127 out += "}"128 }129 }130131 private static func write(string: String, to out: inout String) {132 out += "\""133 for scalar in string.unicodeScalars {134 switch scalar {135 case "\"": out += "\\\""136 case "\\": out += "\\\\"137 case "\n": out += "\\n"138 case "\r": out += "\\r"139 case "\t": out += "\\t"140 default:141 if scalar.value < 0x20 {142 let digits = Array("0123456789abcdef")143 out += "\\u00"144 out.append(digits[Int(scalar.value >> 4)])145 out.append(digits[Int(scalar.value & 15)])146 } else {147 out.unicodeScalars.append(scalar)148 }149 }150 }151 out += "\""152 }153154 private struct Parser {155 let bytes: Bytes156 var position = 0157 var depthLeft: Int158159 init(bytes: Bytes, depthLeft: Int) {160 self.bytes = bytes161 self.depthLeft = depthLeft162 }163164 var peek: UInt8? { position < bytes.count ? bytes[position] : nil }165166 mutating func skipWhiteSpace() {167 while let c = peek, c == 0x20 || c == 0x0a || c == 0x0d || c == 0x09 { position += 1 }168 }169170 mutating func literal(_ text: String) -> Bool {171 let u = Array(text.utf8)172 guard position + u.count <= bytes.count, Array(bytes[position..<position + u.count]) == u else { return false }173 position += u.count174 return true175 }176177 mutating func value() -> SolanaJSON? {178 guard let c = peek else { return nil }179 switch c {180 case UInt8(ascii: "n"): return literal("null") ? .null : nil181 case UInt8(ascii: "t"): return literal("true") ? .bool(true) : nil182 case UInt8(ascii: "f"): return literal("false") ? .bool(false) : nil183 case UInt8(ascii: "\""): return string().map { .string($0) }184 case UInt8(ascii: "["): return array()185 case UInt8(ascii: "{"): return object()186 default: return number()187 }188 }189190 mutating func number() -> SolanaJSON? {191 let start = position192 func isDigit(_ c: UInt8?) -> Bool { c.map { $0 >= 0x30 && $0 <= 0x39 } ?? false }193 if peek == UInt8(ascii: "-") { position += 1 }194 guard isDigit(peek) else { return nil }195 if peek == UInt8(ascii: "0") {196 position += 1197 } else {198 while isDigit(peek) { position += 1 }199 }200 if peek == UInt8(ascii: ".") {201 position += 1202 guard isDigit(peek) else { return nil }203 while isDigit(peek) { position += 1 }204 }205 if peek == UInt8(ascii: "e") || peek == UInt8(ascii: "E") {206 position += 1207 if peek == UInt8(ascii: "+") || peek == UInt8(ascii: "-") { position += 1 }208 guard isDigit(peek) else { return nil }209 while isDigit(peek) { position += 1 }210 }211 return .number(String(decoding: bytes[start..<position], as: UTF8.self))212 }213214 mutating func hex4() -> UInt32? {215 guard position + 4 <= bytes.count else { return nil }216 var v: UInt32 = 0217 for _ in 0..<4 {218 let c = bytes[position]219 let digit: UInt32220 switch c {221 case 0x30...0x39: digit = UInt32(c - 0x30)222 case 0x61...0x66: digit = UInt32(c - 0x61 + 10)223 case 0x41...0x46: digit = UInt32(c - 0x41 + 10)224 default: return nil225 }226 v = v << 4 | digit227 position += 1228 }229 return v230 }231232 mutating func string() -> String? {233 position += 1 // opening quote234 var out = Bytes()235 while let c = peek {236 position += 1237 switch c {238 case UInt8(ascii: "\""):239 return String(bytes: out, encoding: .utf8)240 case UInt8(ascii: "\\"):241 guard let e = peek else { return nil }242 position += 1243 switch e {244 case UInt8(ascii: "\""), UInt8(ascii: "\\"), UInt8(ascii: "/"): out.append(e)245 case UInt8(ascii: "b"): out.append(0x08)246 case UInt8(ascii: "f"): out.append(0x0c)247 case UInt8(ascii: "n"): out.append(0x0a)248 case UInt8(ascii: "r"): out.append(0x0d)249 case UInt8(ascii: "t"): out.append(0x09)250 case UInt8(ascii: "u"):251 guard var code = hex4() else { return nil }252 if (0xd800...0xdbff).contains(code) {253 // high surrogate: a low surrogate must follow254 guard literal("\\u"), let low = hex4(), (0xdc00...0xdfff).contains(low) else { return nil }255 code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00)256 }257 guard let scalar = Unicode.Scalar(code) else { return nil }258 out.append(contentsOf: Array(String(Character(scalar)).utf8))259 default: return nil260 }261 default:262 guard c >= 0x20 else { return nil }263 out.append(c)264 }265 }266 return nil267 }268269 mutating func array() -> SolanaJSON? {270 guard depthLeft > 0 else { return nil }271 depthLeft -= 1272 defer { depthLeft += 1 }273 position += 1274 var items = [SolanaJSON]()275 skipWhiteSpace()276 if peek == UInt8(ascii: "]") {277 position += 1278 return .array(items)279 }280 while true {281 skipWhiteSpace()282 guard let v = value() else { return nil }283 items.append(v)284 skipWhiteSpace()285 guard let c = peek else { return nil }286 position += 1287 if c == UInt8(ascii: "]") { return .array(items) }288 guard c == UInt8(ascii: ",") else { return nil }289 }290 }291292 mutating func object() -> SolanaJSON? {293 guard depthLeft > 0 else { return nil }294 depthLeft -= 1295 defer { depthLeft += 1 }296 position += 1297 var items = [String: SolanaJSON]()298 skipWhiteSpace()299 if peek == UInt8(ascii: "}") {300 position += 1301 return .object(items)302 }303 while true {304 skipWhiteSpace()305 guard peek == UInt8(ascii: "\""), let key = string() else { return nil }306 skipWhiteSpace()307 guard peek == UInt8(ascii: ":") else { return nil }308 position += 1309 skipWhiteSpace()310 guard let v = value() else { return nil }311 guard items.updateValue(v, forKey: key) == nil else { return nil }312 skipWhiteSpace()313 guard let c = peek else { return nil }314 position += 1315 if c == UInt8(ascii: "}") { return .object(items) }316 guard c == UInt8(ascii: ",") else { return nil }317 }318 }319 }320}321