Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraSolana/SolanaHistory.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 QyvoraCore42import QyvoraMath43import QyvoraNetworking4445/// Change of one token balance of the wallet in a transaction.46public struct SolanaTokenChange: Equatable, Sendable {47 public let mint: SolanaPublicKey48 public let decimals: UInt849 /// Sum over every token account of the wallet for this mint, in base units.50 public let change: SolanaSignedAmount51}5253/// One transaction as the wallet shows it: what changed for one address.54public struct SolanaHistoryEntry: Equatable, Sendable {55 public let signature: String56 public let slot: UInt6457 /// Unix time of the block, when the node knows it.58 public let blockTime: Int64?59 /// False when the transaction was included but failed: only the fee was paid.60 public let succeeded: Bool61 /// Fee of the transaction in lamports, paid by `feePayer`.62 public let fee: UInt6463 public let feePayer: SolanaPublicKey?64 /// Change of the lamport balance of the address, fee included when it paid it. Zero when the address is not65 /// one of the accounts of the transaction (it then appears only as the owner of token accounts).66 public let nativeChange: SolanaSignedAmount67 /// Changes of the token balances owned by the address, one entry per mint that changed.68 public let tokenChanges: [SolanaTokenChange]6970 /// True when the address paid the fee, that is when it initiated the transaction.71 public func isInitiator(_ address: SolanaPublicKey) -> Bool { feePayer == address }72}7374/// Normalisation of `getTransaction` (jsonParsed) answers. Pure: no network access.75public enum SolanaHistory {76 /// Reads balance changes from the pre/post balances the node reports, which cover every program and every77 /// instruction (inner ones included), rather than interpreting instructions.78 ///79 /// Throws `NetworkError.invalidResponse` when a field is missing or malformed, or when the transaction does not80 /// carry the requested signature.81 public static func entry(transaction json: SolanaJSON, signature: String, for address: SolanaPublicKey) throws -> SolanaHistoryEntry {82 func bad(_ what: String) -> NetworkError { .invalidResponse("transaction: \(what)") }83 guard let slot = json["slot"]?.uint64, let meta = json["meta"], let message = json["transaction"]?["message"],84 let signatures = json["transaction"]?["signatures"]?.array else { throw bad("structure") }85 guard signatures.first?.string == signature else { throw bad("signature mismatch") }86 guard let fee = meta["fee"]?.uint64, let error = meta["err"] else { throw bad("meta") }87 guard let keyItems = message["accountKeys"]?.array, !keyItems.isEmpty, keyItems.count <= 512 else { throw bad("account keys") }88 // jsonParsed gives objects {pubkey, signer, writable}; older encodings give plain strings89 let keys = try keyItems.map { item -> SolanaPublicKey in90 guard let text = item["pubkey"]?.string ?? item.string, let key = SolanaPublicKey(base58: text) else { throw bad("account key") }91 return key92 }93 guard let pre = meta["preBalances"]?.array, let post = meta["postBalances"]?.array, pre.count == keys.count, post.count == keys.count else {94 throw bad("balances")95 }96 var native = SolanaSignedAmount.zero97 if let index = keys.firstIndex(of: address) {98 guard let before = pre[index].uint64, let after = post[index].uint64 else { throw bad("balance") }99 native = SolanaSignedAmount(from: before, to: after)100 }101102 func tokenBalances(_ field: String) throws -> [SolanaPublicKey: (amount: UInt64, decimals: UInt8)] {103 guard let list = meta[field], !list.isNull else { return [:] }104 guard let items = list.array, items.count <= 1024 else { throw bad(field) }105 var out = [SolanaPublicKey: (amount: UInt64, decimals: UInt8)]()106 for item in items {107 // balances of token accounts owned by someone else are not ours; entries without an owner are skipped108 guard let ownerText = item["owner"]?.string, ownerText == address.base58 else { continue }109 guard let mintText = item["mint"]?.string, let mint = SolanaPublicKey(base58: mintText),110 let amountText = item["uiTokenAmount"]?["amount"]?.string, let amount = UInt64(amountText),111 let decimals = item["uiTokenAmount"]?["decimals"]?.uint64, decimals <= 255 else { throw bad(field) }112 let (sum, overflow) = (out[mint]?.amount ?? 0).addingReportingOverflow(amount)113 guard !overflow else { throw bad(field) }114 out[mint] = (sum, UInt8(decimals))115 }116 return out117 }118 let before = try tokenBalances("preTokenBalances"), after = try tokenBalances("postTokenBalances")119 var changes = [SolanaTokenChange]()120 for mint in Set(before.keys).union(after.keys).sorted() {121 let change = SolanaSignedAmount(from: before[mint]?.amount ?? 0, to: after[mint]?.amount ?? 0)122 if !change.isZero {123 changes.append(SolanaTokenChange(mint: mint, decimals: (after[mint] ?? before[mint])!.decimals, change: change))124 }125 }126 return SolanaHistoryEntry(signature: signature, slot: slot, blockTime: json["blockTime"]?.int64, succeeded: error.isNull, fee: fee,127 feePayer: keys.first, nativeChange: native, tokenChanges: changes)128 }129}130