Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraSolanaTests/SolanaRPCTests.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 QyvoraCore43import QyvoraMath44import QyvoraNetworking45import Testing46@testable import QyvoraSolana4748/// Answers requests from a closure: (host, method, params) → (HTTP status, body). Records what was asked.49final class MockTransport: HTTPTransport, @unchecked Sendable {50 private let lock = NSLock()51 private var log = [(host: String, method: String, params: SolanaJSON)]()52 private let handler: @Sendable (String, String, SolanaJSON) throws -> (Int, String)5354 init(_ handler: @escaping @Sendable (String, String, SolanaJSON) throws -> (Int, String)) { self.handler = handler }5556 /// Every endpoint returns `result` for `method`.57 static func results(_ table: [String: String]) -> MockTransport {58 MockTransport { _, method, _ in59 guard let result = table[method] else { return (200, #"{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"Method not found"}}"#) }60 return (200, #"{"jsonrpc":"2.0","id":1,"result":"# + result + "}")61 }62 }6364 var calls: [(host: String, method: String, params: SolanaJSON)] { lock.withLock { log } }6566 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {67 let body = SolanaJSON.parse(request.httpBody ?? Data())68 let method = body?["method"]?.string ?? ""69 let host = request.url?.host ?? ""70 #expect(request.httpMethod == "POST" && body?["jsonrpc"]?.string == "2.0" && body?["id"]?.uint64 == 1)71 #expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json")72 lock.withLock { log.append((host, method, body?["params"] ?? .null)) }73 let (status, text) = try handler(host, method, body?["params"] ?? .null)74 return (Data(text.utf8), HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!)75 }76}7778func rpc(_ transport: MockTransport, hosts: [String] = ["https://a.example", "https://b.example"]) -> SolanaRPC {79 SolanaRPC(network: .devnet, endpoints: SolanaEndpoints(rpc: ["devnet": hosts]), transport: transport)80}8182func ok(_ result: String) -> (Int, String) { (200, #"{"jsonrpc":"2.0","id":1,"result":"# + result + "}") }8384@Suite struct SolanaJSONTests {85 @Test func exactIntegers() {86 let v = SolanaJSON.parse(Bytes(#"{"a":18446744073709551615,"b":9007199254740993,"c":-9223372036854775808,"d":1.5,"e":1e3,"f":18446744073709551616,"g":0,"h":-0}"#.utf8))!87 #expect(v["a"]?.uint64 == .max)88 #expect(v["b"]?.uint64 == 9_007_199_254_740_993) // 2^53 + 1: not representable as a Double89 #expect(v["c"]?.int64 == .min && v["c"]?.uint64 == nil)90 #expect(v["d"]?.uint64 == nil && v["d"]?.int64 == nil && v["e"]?.uint64 == nil)91 #expect(v["f"]?.uint64 == nil && v["g"]?.uint64 == 0 && v["h"]?.uint64 == nil && v["h"]?.int64 == 0)92 #expect(SolanaJSON.integer(UInt64.max).serialized() == "18446744073709551615")93 }9495 @Test func stringsAndStructure() {96 let v = SolanaJSON.parse(Bytes(#" { "s" : "a\"b\\c\/\n\t\u00e9\ud83d\ude00" , "l" : [ null , true , false , [ ] , { } ] } "#.utf8))!97 #expect(v["s"]?.string == "a\"b\\c/\n\t\u{e9}\u{1F600}")98 #expect(v["l"]?.array == [.null, .bool(true), .bool(false), .array([]), .object([:])])99 #expect(v["l"]?.array?[1].bool == true && v["missing"] == nil && v["s"]?.isNull == false)100 // deterministic serialization, round trip101 let text = v.serialized()102 #expect(text == #"{"l":[null,true,false,[],{}],"s":"a\"b\\c/\n\t\#u{e9}\#u{1F600}"}"#)103 #expect(SolanaJSON.parse(Bytes(text.utf8)) == v)104 #expect(SolanaJSON.string("\u{01}\u{1f}").serialized() == #""\u0001\u001f""#)105 #expect(SolanaJSON.parse(Bytes(SolanaJSON.string("\u{01}\u{1f}").serialized().utf8)) == .string("\u{01}\u{1f}"))106 }107108 @Test func invalidDocumentsAreRefused() {109 let bad = ["", " ", "{", "}", "[1,]", "{\"a\":1,}", "{\"a\":1 \"b\":2}", "{a:1}", "[1 2]", "01", "1.", ".5", "+1", "1e", "--1", "nul", "tru", "True",110 "\"abc", "\"a\nb\"", "\"\\x\"", "\"\\u12\"", "\"\\ud83d\"", "\"\\ud83d\\u0041\"", "\"\\udc00\"", "1 2", "[1]]", "{\"a\":1}{",111 "{\"a\":1,\"a\":2}", "'a'", "[\"a\":1]", "{\"a\"}", "NaN", "Infinity", "0x10"]112 for text in bad { #expect(SolanaJSON.parse(Bytes(text.utf8)) == nil, "\(text) must be refused") }113 #expect(SolanaJSON.parse([0x22, 0xff, 0xfe, 0x22]) == nil) // invalid UTF-8 inside a string114 #expect(SolanaJSON.parse([0xef, 0xbb, 0xbf, 0x31]) == nil) // byte-order mark115 }116117 @Test func depthIsBounded() {118 let deep = Bytes(String(repeating: "[", count: 100_000).utf8)119 #expect(SolanaJSON.parse(deep) == nil)120 let nested = String(repeating: "[", count: 64) + String(repeating: "]", count: 64)121 #expect(SolanaJSON.parse(Bytes(nested.utf8)) != nil)122 let tooDeep = String(repeating: "[", count: 65) + String(repeating: "]", count: 65)123 #expect(SolanaJSON.parse(Bytes(tooDeep.utf8)) == nil)124 let objects = String(repeating: "{\"a\":", count: 65) + "1" + String(repeating: "}", count: 65)125 #expect(SolanaJSON.parse(Bytes(objects.utf8)) == nil)126 #expect(SolanaJSON.parse(Bytes("[[1]]".utf8), maximumDepth: 1) == nil && SolanaJSON.parse(Bytes("[[1]]".utf8), maximumDepth: 2) != nil)127 }128129 @Test func randomInputsNeverTrap() {130 var rng = SystemRandomNumberGenerator()131 let alphabet = Array("{}[]\",:\\ue0123456789.-+tfn rlsau\n".utf8)132 let seed = Bytes(ReferenceVectors.historyTransaction.utf8)133 var parsed = 0134 for round in 0..<20_000 {135 var bytes: Bytes136 if round % 2 == 0 {137 bytes = (0..<Int(rng.next() % 60)).map { _ in alphabet[Int(rng.next() % UInt64(alphabet.count))] }138 } else {139 bytes = Bytes(seed.prefix(400 + Int(rng.next() % 600)))140 bytes[Int(rng.next() % UInt64(bytes.count))] = UInt8(truncatingIfNeeded: rng.next())141 }142 if let v = SolanaJSON.parse(bytes) {143 parsed += 1144 #expect(SolanaJSON.parse(Bytes(v.serialized().utf8)) == v)145 }146 }147 #expect(SolanaJSON.parse(seed) != nil)148 _ = parsed149 }150}151152@Suite struct SolanaRPCClientTests {153 let owner = Fixture.payer154155 @Test func scalarMethods() async throws {156 let transport = MockTransport.results([157 "getBalance": #"{"context":{"slot":1},"value":18446744073709551615}"#,158 "getSlot": "9007199254740993",159 "getBlockHeight": "12345",160 "getMinimumBalanceForRentExemption": "890880",161 "getLatestBlockhash": #"{"context":{"slot":2},"value":{"blockhash":"\#(ReferenceVectors.blockhash)","lastValidBlockHeight":4242}}"#,162 "getRecentPrioritizationFees": #"[{"slot":1,"prioritizationFee":0},{"slot":2,"prioritizationFee":70000},{"slot":3,"prioritizationFee":10}]"#,163 "getFeeForMessage": #"{"context":{"slot":2},"value":5000}"#,164 ])165 let client = rpc(transport)166 #expect(client.isConfigured && client.network == .devnet)167 #expect(try await client.balance(of: owner) == .max)168 #expect(try await client.slot() == 9_007_199_254_740_993)169 #expect(try await client.blockHeight(commitment: .finalized) == 12_345)170 #expect(try await client.minimumBalanceForRentExemption(dataLength: 165) == 890_880)171 let blockhash = try await client.latestBlockhash()172 #expect(blockhash.blockhash == Fixture.blockhash && blockhash.lastValidBlockHeight == 4_242 && blockhash.base58 == ReferenceVectors.blockhash)173 #expect(try await client.recentPrioritizationFees(accounts: [owner]) == [0, 70_000, 10])174 let message = try SolanaMessage(feePayer: owner, instructions: [Fixture.solTransfer], recentBlockhash: Fixture.blockhash)175 #expect(try await client.feeForMessage(message) == 5_000)176177 // requests: first endpoint only, expected parameters178 let calls = transport.calls179 #expect(calls.allSatisfy { $0.host == "a.example" })180 #expect(calls[0].params == .array([.string(owner.base58), .object(["commitment": .string("confirmed")])]))181 #expect(calls[2].params == .array([.object(["commitment": .string("finalized")])]))182 #expect(calls[3].params.array?[0] == .number("165"))183 #expect(calls[6].params.array?[0] == .string(Data(message.serialize()).base64EncodedString()))184 }185186 @Test func fallbackAndErrors() async throws {187 // HTTP 429 on the first endpoint: the second answers188 let limited = MockTransport { host, _, _ in host == "a.example" ? (429, "slow down") : ok("77") }189 #expect(try await rpc(limited).slot() == 77)190 #expect(limited.calls.map(\.host) == ["a.example", "b.example"])191192 // a rate limit delivered as a JSON-RPC error moves on too193 let limitedInBody = MockTransport { host, _, _ in194 host == "a.example" ? (200, #"{"jsonrpc":"2.0","error":{"code": 429,"message":"Too many requests for a specific RPC call"}, "id": 1 }"#) : ok("78")195 }196 #expect(try await rpc(limitedInBody).slot() == 78)197198 // a JSON-RPC error is an answer: not retried elsewhere199 let rpcError = MockTransport { _, _, _ in (200, #"{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid param: \#(String(repeating: "x", count: 1000))"}}"#) }200 do {201 _ = try await rpc(rpcError).slot()202 Issue.record("expected an RPC error")203 } catch NetworkError.rpc(let code, let message) {204 #expect(code == -32602 && message.count == 300)205 }206 #expect(rpcError.calls.count == 1)207208 // transport failure and garbage on every endpoint209 let down = MockTransport { host, _, _ in210 if host == "a.example" { throw URLError(.timedOut) }211 return (200, "<html>not json</html>")212 }213 do {214 _ = try await rpc(down).slot()215 Issue.record("expected a failure")216 } catch NetworkError.allEndpointsFailed(let failures) {217 #expect(failures.count == 2 && failures[0].contains("a.example") && failures[0].contains("did not answer in time") && failures[1].contains("invalid answer"))218 }219 // no endpoint220 let none = SolanaRPC(network: .testnet, endpoints: SolanaEndpoints(rpc: [:]), transport: down)221 #expect(!none.isConfigured)222 await #expect(throws: NetworkError.allEndpointsFailed(["no endpoint configured"])) { try await none.slot() }223 await #expect(throws: NetworkError.allEndpointsFailed(["no endpoint configured"])) { try await none.verifyChain() }224 }225226 @Test func malformedAnswersAreInvalidResponses() async throws {227 let bodies = [228 #"{"jsonrpc":"2.0","id":1,"result":-5}"#, #"{"jsonrpc":"2.0","id":1,"result":1.5}"#, #"{"jsonrpc":"2.0","id":1,"result":"12"}"#,229 #"{"jsonrpc":"2.0","id":1,"result":18446744073709551616}"#, #"{"jsonrpc":"2.0","id":1,"result":null}"#, #"{"jsonrpc":"2.0","id":1}"#,230 #"{"id":1,"result":5}"#, #"{"jsonrpc":"2.0","id":2,"result":5}"#, #"{"jsonrpc":"2.0","id":null,"result":5}"#, #"{"jsonrpc":"2.0","result":5}"#, #"{"jsonrpc":"1.0","id":1,"result":5}"#, #"[]"#, #"{"jsonrpc":"2.0","id":1,"error":{"code":"x","message":"y"}}"#,231 #"{"jsonrpc":"2.0","id":1,"error":"boom"}"#, "", #"{"jsonrpc":"2.0","id":1,"result":5"#,232 ]233 for body in bodies {234 let client = rpc(MockTransport { _, _, _ in (200, body) }, hosts: ["https://a.example"])235 await #expect(throws: NetworkError.self, "\(body)") { try await client.slot() }236 }237 // structured methods with hostile shapes238 let shapes: [String: [String]] = [239 "getBalance": [#"{"value":"1"}"#, #"{}"#, "[]", "5"],240 "getLatestBlockhash": [#"{"value":{"blockhash":"abc","lastValidBlockHeight":1}}"#, #"{"value":{"blockhash":"\#(ReferenceVectors.blockhash)"}}"#, #"{"value":null}"#],241 "getAccountInfo": [#"{}"#, #"{"value":{"lamports":1,"owner":"x","executable":false}}"#, #"{"value":{"lamports":-1,"owner":"11111111111111111111111111111111","executable":false}}"#,242 #"{"value":{"lamports":1,"owner":"11111111111111111111111111111111"}}"#],243 "getSignaturesForAddress": [#"{}"#, #"[{"signature":"abc","slot":1}]"#, #"[{"slot":1}]"#],244 "getRecentPrioritizationFees": [#"{}"#, #"[{"slot":1}]"#, #"[{"prioritizationFee":-1}]"#],245 "getSignatureStatuses": [#"{"value":[]}"#, #"{"value":[null,null]}"#, #"{"value":[{"confirmations":1}]}"#],246 "getFeeForMessage": [#"{}"#, #"{"value":"5000"}"#],247 ]248 let signature = Fixture.legacy["transfer"]!.signature249 let message = try SolanaMessage(feePayer: owner, instructions: [Fixture.solTransfer], recentBlockhash: Fixture.blockhash)250 var checked = 0251 for (method, results) in shapes {252 for result in results {253 let client = rpc(MockTransport.results([method: result]), hosts: ["https://a.example"])254 await #expect(throws: NetworkError.self, "\(method) \(result)") {255 switch method {256 case "getBalance": _ = try await client.balance(of: owner)257 case "getLatestBlockhash": _ = try await client.latestBlockhash()258 case "getAccountInfo": _ = try await client.accountInfo(owner)259 case "getSignaturesForAddress": _ = try await client.signatures(for: owner)260 case "getRecentPrioritizationFees": _ = try await client.recentPrioritizationFees(accounts: [])261 case "getSignatureStatuses": _ = try await client.signatureStatuses([signature])262 default: _ = try await client.feeForMessage(message)263 }264 }265 checked += 1266 }267 }268 #expect(checked == 22)269 // an oversized body is refused before parsing270 let huge = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"" + String(repeating: "a", count: SolanaRPC.maximumResponseBytes) + "\"}"271 let client = rpc(MockTransport { _, _, _ in (200, huge) }, hosts: ["https://a.example"])272 await #expect(throws: NetworkError.self) { try await client.call("getHealth") }273 }274275 @Test func chainIdentity() async throws {276 let good = MockTransport.results(["getGenesisHash": "\"\(SolanaNetwork.devnet.genesisHash)\""])277 try await rpc(good).verifyChain()278 #expect(good.calls.map(\.host) == ["a.example", "b.example"]) // every endpoint is asked279 // one endpoint serves mainnet280 let mixed = MockTransport { host, _, _ in ok("\"" + (host == "a.example" ? SolanaNetwork.devnet : .mainnetBeta).genesisHash + "\"") }281 do {282 try await rpc(mixed).verifyChain()283 Issue.record("expected a disagreement")284 } catch NetworkError.disagreement(let text) {285 #expect(text.contains("b.example") && text.contains("devnet"))286 }287 // one endpoint down, the other right: accepted288 let partial = MockTransport { host, _, _ in host == "a.example" ? (503, "") : ok("\"" + SolanaNetwork.devnet.genesisHash + "\"") }289 try await rpc(partial).verifyChain()290 // all down291 await #expect(throws: NetworkError.self) { try await rpc(MockTransport { _, _, _ in (503, "") }).verifyChain() }292 }293294 @Test func accountsAndTokens() async throws {295 let mintJSON = #"{"context":{"slot":1},"value":{"data":{"parsed":{"info":{"decimals":6,"freezeAuthority":null,"isInitialized":true,"mintAuthority":null,"supply":"9000000000000000000"},"type":"mint"},"program":"spl-token","space":82},"executable":false,"lamports":1461600,"owner":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","rentEpoch":18446744073709551615,"space":82}}"#296 let mint = try await rpc(MockTransport.results(["getAccountInfo": mintJSON])).mintInfo(Fixture.usdc)297 #expect(mint == SolanaMintInfo(address: Fixture.usdc, program: .token, decimals: 6, supply: 9_000_000_000_000_000_000, isInitialized: true, extensions: []))298 #expect(mint?.transferRefusal == nil)299300 let mint2022 = #"{"context":{"slot":1},"value":{"data":{"parsed":{"info":{"decimals":6,"extensions":[{"extension":"transferFeeConfig","state":{}},{"extension":"metadataPointer","state":{}}],"isInitialized":true,"supply":"5"},"type":"mint"},"program":"spl-token-2022","space":400},"executable":false,"lamports":1,"owner":"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb","space":400}}"#301 let info = try await rpc(MockTransport.results(["getAccountInfo": mint2022])).mintInfo(Fixture.pyusd)302 #expect(info?.program == .token2022 && info?.extensions == ["transferFeeConfig", "metadataPointer"])303 #expect(info?.transferRefusal == "unsupported Token-2022 extension: transferFeeConfig")304305 // missing account, a wallet, a token account and unparsed data are not mints306 #expect(try await rpc(MockTransport.results(["getAccountInfo": #"{"context":{"slot":1},"value":null}"#])).mintInfo(Fixture.usdc) == nil)307 let wallet = #"{"context":{"slot":1},"value":{"data":["","base64"],"executable":false,"lamports":5,"owner":"11111111111111111111111111111111","space":0}}"#308 let walletClient = rpc(MockTransport.results(["getAccountInfo": wallet]))309 await #expect(throws: NetworkError.invalidResponse("not a token mint")) { try await walletClient.mintInfo(Fixture.usdc) }310 let account = try await walletClient.accountInfo(owner)311 #expect(account == SolanaAccountInfo(lamports: 5, owner: SolanaProgram.system, executable: false, space: 0, parsed: nil))312 let raw2022 = #"{"context":{"slot":1},"value":{"data":["AAAA","base64"],"executable":false,"lamports":5,"owner":"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb","space":3}}"#313 let rawClient = rpc(MockTransport.results(["getAccountInfo": raw2022]))314 await #expect(throws: NetworkError.invalidResponse("not a token mint")) { try await rawClient.mintInfo(Fixture.pyusd) }315316 // token accounts under both programs317 let ata = try SolanaAddress.associatedTokenAccount(owner: owner, mint: Fixture.usdc)318 @Sendable func tokenAccountJSON(owner: SolanaPublicKey, program: String) -> String {319 #"{"account":{"data":{"parsed":{"info":{"isNative":false,"mint":"\#(Fixture.usdc)","owner":"\#(owner)","state":"initialized","tokenAmount":{"amount":"18446744073709551615","decimals":6,"uiAmount":1.8446744073709552e13,"uiAmountString":"18446744073709.551615"}},"type":"account"},"program":"spl-token","space":165},"executable":false,"lamports":2039280,"owner":"\#(program)","rentEpoch":0,"space":165},"pubkey":"\#(ata)"}"#320 }321 let tokens = MockTransport { _, _, params in322 let program = params.array?[1]["programId"]?.string ?? ""323 let items = program == SolanaProgram.token.base58 ? tokenAccountJSON(owner: Fixture.payer, program: program) : ""324 return ok(#"{"context":{"slot":1},"value":[\#(items)]}"#)325 }326 let accounts = try await rpc(tokens).tokenAccounts(owner: owner)327 #expect(accounts == [SolanaTokenAccount(address: ata, mint: Fixture.usdc, owner: owner, program: .token, amount: .max, decimals: 6,328 state: "initialized", lamports: 2_039_280)])329 #expect(tokens.calls.count == 2 && tokens.calls[1].params.array?[1]["programId"]?.string == SolanaProgram.token2022.base58)330 #expect(tokens.calls[0].params.array?[2] == .object(["commitment": .string("confirmed"), "encoding": .string("jsonParsed")]))331 // an endpoint that returns someone else's account, or an account of the wrong program, is refused332 let foreign = MockTransport { _, _, params in ok(#"{"context":{"slot":1},"value":[\#(tokenAccountJSON(owner: Fixture.other, program: SolanaProgram.token.base58))]}"#) }333 await #expect(throws: NetworkError.self) { try await rpc(foreign).tokenAccounts(owner: owner) }334 let wrongProgram = MockTransport { _, _, params in ok(#"{"context":{"slot":1},"value":[\#(tokenAccountJSON(owner: Fixture.payer, program: SolanaProgram.system.base58))]}"#) }335 await #expect(throws: NetworkError.self) { try await rpc(wrongProgram).tokenAccounts(owner: owner) }336 }337338 @Test func simulationSendAndTracking() async throws {339 let unsigned = SolanaTransaction(message: try SolanaMessage(feePayer: owner, instructions: [Fixture.solTransfer], recentBlockhash: Fixture.blockhash))340 let simulated = MockTransport.results(["simulateTransaction": #"{"context":{"slot":1},"value":{"accounts":null,"err":null,"logs":["Program 11111111111111111111111111111111 invoke [1]","Program 11111111111111111111111111111111 success"],"unitsConsumed":150}}"#])341 let simulation = try await rpc(simulated).simulate(unsigned)342 #expect(simulation.succeeded && simulation.logs.count == 2 && simulation.unitsConsumed == 150)343 let options = simulated.calls[0].params.array![1]344 #expect(options["sigVerify"] == .bool(false) && options["encoding"] == .string("base64") && options["replaceRecentBlockhash"] == .bool(false))345 #expect(simulated.calls[0].params.array![0] == .string(Data(Fixture.legacy["plainTransfer"]!.unsigned).base64EncodedString()))346 let failing = MockTransport.results(["simulateTransaction": #"{"context":{"slot":1},"value":{"err":{"InstructionError":[0,{"Custom":1}]},"logs":null}}"#])347 let failure = try await rpc(failing).simulate(unsigned)348 #expect(!failure.succeeded && failure.error == #"{"InstructionError":[0,{"Custom":1}]}"# && failure.logs.isEmpty)349350 // an unsigned transaction is never broadcast351 await #expect(throws: SolanaError.missingSignature) { try await rpc(simulated).send(unsigned) }352 #expect(simulated.calls.count == 1)353 var signing = unsigned354 try signing.sign(privateSeed: Fixture.payerSeed)355 let transaction = signing356 let id = try #require(transaction.id)357 #expect(id == Fixture.legacy["plainTransfer"]!.signature)358359 let accepting = MockTransport { host, _, _ in host == "a.example" ? (500, "") : ok("\"\(id)\"") }360 #expect(try await rpc(accepting).send(transaction) == id)361 #expect(accepting.calls.count == 2)362 let sendOptions = accepting.calls[0].params.array![1]363 #expect(sendOptions["skipPreflight"] == .bool(false) && sendOptions["maxRetries"] == .number("5") && sendOptions["encoding"] == .string("base64"))364 #expect(accepting.calls[0].params.array![0] == .string(Data(Fixture.legacy["plainTransfer"]!.signed).base64EncodedString()))365 // "already processed" counts as accepted366 let known = MockTransport { _, _, _ in (200, #"{"jsonrpc":"2.0","id":1,"error":{"code":-32002,"message":"Transaction simulation failed: This transaction has already been processed"}}"#) }367 #expect(try await rpc(known).send(transaction) == id)368 // an endpoint that returns another identifier is not trusted369 let lying = MockTransport { _, _, _ in ok("\"\(Fixture.legacy["transfer"]!.signature)\"") }370 await #expect(throws: NetworkError.self) { try await rpc(lying).send(transaction) }371 // a rejection by the cluster is reported as such372 let rejected = MockTransport { _, _, _ in (200, #"{"jsonrpc":"2.0","id":1,"error":{"code":-32002,"message":"Transaction simulation failed: Blockhash not found"}}"#) }373 await #expect(throws: NetworkError.rpc(code: -32002, message: "Transaction simulation failed: Blockhash not found")) { try await rpc(rejected).send(transaction) }374375 // tracking376 func tracker(status: String, height: UInt64) -> SolanaRPC {377 rpc(MockTransport.results(["getSignatureStatuses": #"{"context":{"slot":9},"value":[\#(status)]}"#, "getBlockHeight": "\(height)"]))378 }379 #expect(try await tracker(status: "null", height: 100).track(signature: id, lastValidBlockHeight: 100) == .pending)380 #expect(try await tracker(status: "null", height: 101).track(signature: id, lastValidBlockHeight: 100) == .expired)381 #expect(try await tracker(status: #"{"slot":7,"confirmations":3,"err":null,"confirmationStatus":"confirmed"}"#, height: 500)382 .track(signature: id, lastValidBlockHeight: 100) == .included(slot: 7, commitment: .confirmed))383 #expect(try await tracker(status: #"{"slot":7,"confirmations":null,"err":null,"confirmationStatus":"finalized"}"#, height: 500)384 .track(signature: id, lastValidBlockHeight: 100) == .included(slot: 7, commitment: .finalized))385 #expect(try await tracker(status: #"{"slot":7,"confirmations":1,"err":{"InstructionError":[2,"InsufficientFunds"]},"confirmationStatus":"processed"}"#, height: 5)386 .track(signature: id, lastValidBlockHeight: 100) == .failed(slot: 7, error: #"{"InstructionError":[2,"InsufficientFunds"]}"#))387 let expiryCheck = MockTransport.results(["getSignatureStatuses": #"{"context":{"slot":9},"value":[null]}"#, "getBlockHeight": "1"])388 _ = try await rpc(expiryCheck).track(signature: id, lastValidBlockHeight: 100)389 #expect(expiryCheck.calls[1].params == .array([.object(["commitment": .string("finalized")])]))390 #expect(expiryCheck.calls[0].params.array?[1] == .object(["searchTransactionHistory": .bool(true)]))391 #expect(SolanaCommitment.processed < .confirmed && SolanaCommitment.confirmed < .finalized)392 await #expect(throws: NetworkError.self) { try await rpc(expiryCheck).signatureStatuses(["not a signature"]) }393 await #expect(throws: NetworkError.self) { try await rpc(expiryCheck).transaction("abc") }394 }395396 @Test func signaturesArePagedAndBounded() async throws {397 let s1 = Fixture.legacy["transfer"]!.signature, s2 = Fixture.legacy["token"]!.signature398 let transport = MockTransport.results(["getSignaturesForAddress": #"[{"blockTime":1700000000,"confirmationStatus":"finalized","err":null,"memo":null,"signature":"\#(s1)","slot":10},{"blockTime":null,"confirmationStatus":"confirmed","err":{"InstructionError":[0,"Custom"]},"signature":"\#(s2)","slot":9}]"#])399 let page = try await rpc(transport).signatures(for: owner, limit: 5000, before: s1)400 #expect(page == [SolanaSignatureInfo(signature: s1, slot: 10, blockTime: 1_700_000_000, failed: false, confirmationStatus: .finalized),401 SolanaSignatureInfo(signature: s2, slot: 9, blockTime: nil, failed: true, confirmationStatus: .confirmed)])402 let options = transport.calls[0].params.array![1]403 #expect(options["limit"] == .number("100") && options["before"] == .string(s1))404 // the answer is cut to the requested page size even when the endpoint sends more405 #expect(try await rpc(transport).signatures(for: owner, limit: 1).count == 1)406 #expect(SolanaFees.suggestedUnitPrice(recentFees: []) == 5_000)407 #expect(SolanaFees.suggestedUnitPrice(recentFees: [0, 0, 0, 0]) == 5_000)408 #expect(SolanaFees.suggestedUnitPrice(recentFees: [1, 2, 3, 80_000, 90_000, 100_000, 7, 8]) == 90_000)409 #expect(SolanaFees.suggestedUnitPrice(recentFees: [.max, .max]) == 2_000_000)410 }411}412413@Suite struct SolanaHistoryTests {414 /// A real mainnet transaction (unmodified `getTransaction` answer): a swap between two wallets, USDC against cbBTC.415 @Test func normalisesARealTransaction() async throws {416 let envelope = try #require(SolanaJSON.parse(Bytes(ReferenceVectors.historyTransaction.utf8)))417 let json = try #require(envelope["result"])418 let signature = ReferenceVectors.historySignature419 let payer = key("MfDuWeqSHEqTFVYZ7LoexgAK9dxk7cy4DFJWjWMGVWa"), counterparty = key("HxA6SKW5qA4o12fjVgTpXdq2YnZ5Zv1s7SB4FFomsyLM")420 let entry = try SolanaHistory.entry(transaction: json, signature: signature, for: payer)421 #expect(entry.signature == signature && entry.slot == 477_659_931 && entry.blockTime == 1_796_448_657 && entry.succeeded)422 #expect(entry.fee == 8_626 && entry.feePayer == payer && entry.isInitiator(payer) && !entry.isInitiator(counterparty))423 #expect(entry.nativeChange == SolanaSignedAmount(isNegative: true, magnitude: 8_626))424 #expect(entry.tokenChanges.count == 2)425 let usdc = try #require(entry.tokenChanges.first { $0.mint == Fixture.usdc })426 #expect(usdc.decimals == 6 && usdc.change == SolanaSignedAmount(isNegative: false, magnitude: 193_131_291))427 let cbbtc = try #require(entry.tokenChanges.first { $0.mint != Fixture.usdc })428 #expect(cbbtc.mint.base58.hasPrefix("cbbtcf") && cbbtc.decimals == 8 && cbbtc.change == SolanaSignedAmount(isNegative: true, magnitude: 430_283))429430 let other = try SolanaHistory.entry(transaction: json, signature: signature, for: counterparty)431 #expect(other.tokenChanges.first { $0.mint == Fixture.usdc }?.change == SolanaSignedAmount(isNegative: true, magnitude: 193_131_291))432 #expect(other.tokenChanges.first { $0.mint != Fixture.usdc }?.change == SolanaSignedAmount(isNegative: false, magnitude: 430_283))433 #expect(other.nativeChange.isZero)434 // an address that is not involved sees nothing435 let stranger = try SolanaHistory.entry(transaction: json, signature: signature, for: Fixture.payer)436 #expect(stranger.nativeChange.isZero && stranger.tokenChanges.isEmpty)437 // the answer must be the transaction that was asked for438 #expect(throws: NetworkError.self) { try SolanaHistory.entry(transaction: json, signature: Fixture.legacy["transfer"]!.signature, for: payer) }439440 // through the client441 let client = rpc(MockTransport { _, method, _ in442 method == "getSignaturesForAddress" ? ok(#"[{"signature":"\#(signature)","slot":477659931,"err":null,"blockTime":1796448657,"confirmationStatus":"finalized"}]"#)443 : (200, ReferenceVectors.historyTransaction)444 })445 #expect(try await client.history(of: payer, limit: 3) == [entry])446 }447448 @Test func malformedTransactionsAreRefused() throws {449 let json = SolanaJSON.parse(Bytes(ReferenceVectors.historyTransaction.utf8))!["result"]!450 let signature = ReferenceVectors.historySignature451 guard case .object(var top) = json, case .object(var meta) = top["meta"]! else { return }452 func entry(_ object: [String: SolanaJSON]) throws -> SolanaHistoryEntry {453 try SolanaHistory.entry(transaction: .object(object), signature: signature, for: key("MfDuWeqSHEqTFVYZ7LoexgAK9dxk7cy4DFJWjWMGVWa"))454 }455 for removed in ["slot", "meta", "transaction"] {456 var o = top457 o[removed] = nil458 #expect(throws: NetworkError.self, "without \(removed)") { try entry(o) }459 }460 for (field, value) in [("fee", SolanaJSON.number("-1")), ("fee", .number("1.5")), ("preBalances", .array([])), ("postBalances", .string("x")),461 ("postTokenBalances", .string("x")), ("err", nil)] as [(String, SolanaJSON?)] {462 var m = meta463 m[field] = value464 var o = top465 o["meta"] = .object(m)466 #expect(throws: NetworkError.self, "bad \(field)") { try entry(o) }467 }468 // a failed transaction is reported as failed469 meta["err"] = .object(["InstructionError": .array([.number("0"), .string("Custom")])])470 top["meta"] = .object(meta)471 #expect(try entry(top).succeeded == false)472 #expect(SolanaSignedAmount(from: 5, to: 5) == .zero && SolanaSignedAmount(isNegative: true, magnitude: 0) == .zero)473 #expect(SolanaSignedAmount(from: .max, to: 0) == SolanaSignedAmount(isNegative: true, magnitude: .max))474 }475}476