Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraNetworkingTests/PriceCheckTests.swift8// Module : Tests9// 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 Testing43import QyvoraCore44@testable import QyvoraNetworking4546// The second price source (QYV-SVC-087): bounded parsing of its answer, its place in the endpoint configuration, and47// an opt-in live check of every pair of `PriceClient.checkPairs`.4849@Suite struct PriceCheckParsingTests {50 static func ticker(ask: String, bid: String, last: String, pair: String = "SOLUSD") -> Data {51 Data("{\"error\":[],\"result\":{\"\(pair)\":{\"a\":[\"\(ask)\",\"1\",\"1.000\"],\"b\":[\"\(bid)\",\"1\",\"1.000\"],\"c\":[\"\(last)\",\"0.5\"]}}}".utf8)52 }5354 @Test func oneUsableTickerGivesTheMiddleOfBidAndAsk() {55 #expect(PriceClient.parseCheckTicker(Self.ticker(ask: "56.62000", bid: "56.60000", last: "56.59000")) == 56.61)56 // the key of the entry is the source's own name of the pair (XETHZUSD for ETHUSD): any single entry is read57 #expect(PriceClient.parseCheckTicker(Self.ticker(ask: "10", bid: "10", last: "10", pair: "XETHZUSD")) == 10)58 #expect(PriceClient.parseCheckTicker(Self.ticker(ask: "0.0000029770", bid: "0.0000029740", last: "0.0000029740")) != nil)59 }6061 @Test func anythingElseIsNoPrice() {62 let refused: [Data] = [63 Data(), Data("[]".utf8), Data("{}".utf8), Data("{\"error\":[\"EQuery:Unknown asset pair\"]}".utf8),64 Data("{\"error\":[\"EGeneral:Temporary\"],\"result\":{\"SOLUSD\":{\"a\":[\"10\"],\"b\":[\"10\"],\"c\":[\"10\"]}}}".utf8),65 Data("{\"error\":[],\"result\":{}}".utf8),66 // two entries: the wallet asked for one pair67 Data("{\"error\":[],\"result\":{\"A\":{\"a\":[\"10\"],\"b\":[\"10\"],\"c\":[\"10\"]},\"B\":{\"a\":[\"10\"],\"b\":[\"10\"],\"c\":[\"10\"]}}}".utf8),68 // numbers instead of decimal texts, exponents, signs, spaces, empty, very long69 Data("{\"error\":[],\"result\":{\"SOLUSD\":{\"a\":[10],\"b\":[10],\"c\":[10]}}}".utf8),70 Self.ticker(ask: "1e1", bid: "10", last: "10"), Self.ticker(ask: "-10", bid: "-10", last: "-10"),71 Self.ticker(ask: " 10", bid: "10", last: "10"), Self.ticker(ask: "", bid: "10", last: "10"),72 Self.ticker(ask: String(repeating: "9", count: 33), bid: "10", last: "10"),73 Self.ticker(ask: "0", bid: "0", last: "0"), Self.ticker(ask: "1000000000000", bid: "10", last: "10"),74 Self.ticker(ask: "inf", bid: "10", last: "10"), Self.ticker(ask: "nan", bid: "nan", last: "nan"),75 // a crossed book, and a last trade far from the book (a pair nobody trades)76 Self.ticker(ask: "10", bid: "11", last: "10"), Self.ticker(ask: "10", bid: "10", last: "8.9"), Self.ticker(ask: "10", bid: "10", last: "11.1"),77 // missing members78 Data("{\"error\":[],\"result\":{\"SOLUSD\":{\"a\":[\"10\"],\"b\":[\"10\"]}}}".utf8),79 Data("{\"error\":[],\"result\":{\"SOLUSD\":{\"a\":[],\"b\":[],\"c\":[]}}}".utf8),80 Data("{\"error\":[],\"result\":[]}".utf8),81 // larger than the bound82 Data(String(repeating: " ", count: PriceClient.checkAnswerLimit).utf8) + Self.ticker(ask: "10", bid: "10", last: "10"),83 ]84 for (index, data) in refused.enumerated() { #expect(PriceClient.parseCheckTicker(data) == nil, "case \(index)") }85 }8687 @Test func theSecondSourceHasItsPlaceInTheConfiguration() throws {88 #expect(EndpointConfiguration.default.priceCheckAPI == "https://api.kraken.com/0/public")89 #expect(EndpointConfiguration.isAcceptable(EndpointConfiguration.default.priceCheckAPI))90 // a configuration written out by hand talks to the listed hosts only91 #expect(EndpointConfiguration(esplora: [:], ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "").priceCheckAPI.isEmpty)92 // stored before the field existed: the default, without which no dollar ceiling could be verified93 let legacy = try JSONDecoder().decode(EndpointConfiguration.self, from: Data(#"{"schema":2,"esplora":{},"blockbook":{},"bitcore":{},"ethereumRPC":{},"ethereumIndexer":{},"priceAPI":"https://p.example"}"#.utf8))94 #expect(legacy.priceCheckAPI == EndpointConfiguration.defaultPriceCheckAPI && legacy.priceAPI == "https://p.example")95 // stored since: kept as it is, an empty value included (the user disabled it)96 var custom = EndpointConfiguration.default97 custom.priceCheckAPI = ""98 #expect(try JSONDecoder().decode(EndpointConfiguration.self, from: JSONEncoder().encode(custom)).priceCheckAPI.isEmpty)99 custom.priceCheckAPI = "https://check.example/0/public"100 #expect(try JSONDecoder().decode(EndpointConfiguration.self, from: JSONEncoder().encode(custom)) == custom)101 #expect(throws: (any Error).self) {102 try JSONDecoder().decode(EndpointConfiguration.self, from: Data(#"{"schema":2,"priceCheckAPI":1}"#.utf8))103 }104 // pairs are plain upper-case names: nothing of the request can be steered by an identifier105 for (id, pair) in PriceClient.checkPairs {106 #expect(pair.utf8.allSatisfy { ($0 >= 0x41 && $0 <= 0x5a) } && pair.hasSuffix("USD") && pair.count <= 12, "\(id)")107 }108 }109}110111/// Opt-in: asks the default second source for every pair. `QYVORA_LIVE=1 swift test --filter PriceCheckLiveTests`.112/// Read-only, public data, no key. Run on 2026-12-05: every pair answered a price.113@Suite(.enabled(if: ProcessInfo.processInfo.environment["QYVORA_LIVE"] == "1"), .serialized)114struct PriceCheckLiveTests {115 @Test func everyPairAnswersAtTheDefaultSource() async throws {116 let client = PriceClient(configuration: .default, transport: URLSessionTransport())117 var seen = [String: Double]()118 for (id, pair) in PriceClient.checkPairs.sorted(by: { $0.key < $1.key }) {119 if let known = seen[pair] {120 print("LIVE price-check \(id) → \(pair) = \(known) (pair already read)")121 continue122 }123 let price = try await client.checkPrice(id: id)124 #expect(price != nil, "\(id) → \(pair)")125 if let price {126 seen[pair] = price127 print("LIVE price-check \(id) → \(pair) = \(price)")128 }129 try await Task.sleep(nanoseconds: 400_000_000)130 }131 }132}133