SPB Git

Repository Public

SolanaRPC.swift 34.6 KB 585 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraSolana/SolanaRPC.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 QyvoraCore43import QyvoraMath44import QyvoraNetworking4546/// How far the cluster has gone in agreeing on a block.47public enum SolanaCommitment: String, Codable, Sendable, CaseIterable, Comparable {48    /// Seen by the node; may still be dropped.49    case processed50    /// Voted on by a supermajority; dropped only in exceptional cases. The default for reads and for the wallet's "sent" state.51    case confirmed52    /// Rooted: cannot be rolled back. The state to wait for before treating funds as received.53    case finalized5455    private var rank: Int { self == .processed ? 0 : (self == .confirmed ? 1 : 2) }56    public static func < (a: SolanaCommitment, b: SolanaCommitment) -> Bool { a.rank < b.rank }57}5859public struct SolanaBlockhash: Equatable, Sendable {60    /// 32 bytes.61    public let blockhash: Bytes62    /// Last block height at which a transaction using this blockhash can still be included. Past it (compare with63    /// `SolanaRPC.blockHeight`), a transaction that is not in a block has expired and can never be executed.64    public let lastValidBlockHeight: UInt646566    public var base58: String { Base58.bitcoin.encode(blockhash) }6768    public init(blockhash: Bytes, lastValidBlockHeight: UInt64) {69        self.blockhash = blockhash70        self.lastValidBlockHeight = lastValidBlockHeight71    }72}7374public struct SolanaAccountInfo: Equatable, Sendable {75    public let lamports: UInt6476    /// The program that owns the account: the System program for a wallet, a token program for a mint or token account.77    public let owner: SolanaPublicKey78    public let executable: Bool79    /// Size of the account data in bytes.80    public let space: UInt6481    /// `data.parsed` when the node recognised the account (jsonParsed): `{"type": "mint" | "account", "info": {…}}`.82    public let parsed: SolanaJSON?83}8485public struct SolanaSignatureInfo: Equatable, Sendable {86    public let signature: String87    public let slot: UInt6488    /// Unix time of the block, when the node knows it.89    public let blockTime: Int64?90    /// True when the transaction was included but failed (the fee was still paid).91    public let failed: Bool92    public let confirmationStatus: SolanaCommitment?93}9495public struct SolanaSignatureStatus: Equatable, Sendable {96    public let slot: UInt6497    /// Blocks since inclusion; nil once finalized.98    public let confirmations: UInt64?99    /// nil when the transaction succeeded; otherwise the error as the node reports it (compact JSON, truncated).100    public let error: String?101    public let confirmationStatus: SolanaCommitment?102}103104public struct SolanaSimulation: Equatable, Sendable {105    /// nil when the simulated transaction succeeded; otherwise the error as the node reports it (compact JSON, truncated).106    public let error: String?107    /// Program logs, at most `SolanaRPC.maximumLogLines` lines of at most 500 characters.108    public let logs: [String]109    public let unitsConsumed: UInt64?110111    public var succeeded: Bool { error == nil }112}113114/// Solana JSON-RPC 2.0 client over one or several endpoints.115///116/// - Requests go to the endpoints in order and the first answer wins; a connection or HTTP error (429 included)117///   moves on to the next endpoint. A JSON-RPC error is an answer and is returned as `NetworkError.rpc` without118///   trying elsewhere. There is no automatic retry and no parallel fan-out: one request, one endpoint at a time.119/// - Answers are bounded: `maximumResponseBytes` per body (on top of the transport's own limit), lists are capped,120///   strings taken from an answer are truncated before they reach an error or a log.121/// - Amounts are parsed as exact 64-bit integers (`SolanaJSON`), never through floating point.122/// - Nothing identifies the user: no API key, no account; the endpoints do see the addresses that are queried.123public struct SolanaRPC: Sendable {124    public static let maximumResponseBytes = 8 << 20125    public static let maximumSignaturesPerPage = 100126    public static let maximumTokenAccounts = 1000127    public static let maximumLogLines = 200128    /// Highest transaction version asked from `getTransaction` (legacy, 0 and 1 exist on mainnet-beta as of 2026-12;129    /// without it the node refuses to return newer transactions and the history would have holes).130    public static let maximumTransactionVersion = 1131132    let endpoints: [URL]133    let transport: HTTPTransport134    public let network: SolanaNetwork135136    public init(network: SolanaNetwork, endpoints: SolanaEndpoints = .default, transport: HTTPTransport) {137        self.network = network138        self.endpoints = endpoints.urls(for: network)139        self.transport = transport140    }141142    public var isConfigured: Bool { !endpoints.isEmpty }143144    // MARK: transport145146    func call(_ method: String, _ params: [SolanaJSON], on endpoint: URL) async throws -> SolanaJSON {147        var r = URLRequest(url: endpoint)148        r.httpMethod = "POST"149        r.setValue("application/json", forHTTPHeaderField: "Content-Type")150        let body = SolanaJSON.object(["jsonrpc": .string("2.0"), "id": .integer(1), "method": .string(method), "params": .array(params)])151        r.httpBody = Data(body.serialized().utf8)152        let (data, response) = try await transport.send(r)153        guard (200...299).contains(response.statusCode) else {154            throw NetworkError.http(status: response.statusCode, body: String(decoding: data.prefix(300), as: UTF8.self))155        }156        guard data.count <= Self.maximumResponseBytes else { throw NetworkError.invalidResponse("\(method): response larger than \(Self.maximumResponseBytes) bytes") }157        guard let envelope = SolanaJSON.parse(data), envelope["jsonrpc"]?.string == "2.0" else { throw NetworkError.invalidResponse(method) }158        if let error = envelope["error"], !error.isNull {159            guard let code = error["code"]?.int64, let message = error["message"]?.string else { throw NetworkError.invalidResponse(method) }160            // some gateways answer a rate limit as a JSON-RPC error: it is a refusal to serve, not an answer of the cluster161            if code == 429 { throw NetworkError.http(status: 429, body: String(message.prefix(300))) }162            throw NetworkError.rpc(code: Int(clamping: code), message: String(message.prefix(300)))163        }164        // the answer must be the answer to this request165        guard let result = envelope["result"], envelope["id"]?.uint64 == 1 else { throw NetworkError.invalidResponse(method) }166        return result167    }168169    /// First endpoint that answers. A JSON-RPC error is an answer and is not retried elsewhere.170    public func call(_ method: String, _ params: [SolanaJSON] = []) async throws -> SolanaJSON {171        guard !endpoints.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }172        var failures = [String]()173        for endpoint in endpoints {174            do {175                return try await call(method, params, on: endpoint)176            } catch let e as NetworkError {177                if case .rpc = e { throw e }178                failures.append("\(endpoint.host ?? "?"): \(e.summary)")179            } catch {180                failures.append("\(endpoint.host ?? "?"): \(NetworkError.transportSummary(error))")181            }182        }183        throw NetworkError.allEndpointsFailed(failures)184    }185186    private static func config(_ commitment: SolanaCommitment, _ extra: [String: SolanaJSON] = [:]) -> SolanaJSON {187        var o = extra188        o["commitment"] = .string(commitment.rawValue)189        return .object(o)190    }191192    private static func u64(_ v: SolanaJSON?, _ what: String) throws -> UInt64 {193        guard let n = v?.uint64 else { throw NetworkError.invalidResponse(what) }194        return n195    }196197    private static func key(_ v: SolanaJSON?, _ what: String) throws -> SolanaPublicKey {198        guard let s = v?.string, let k = SolanaPublicKey(base58: s) else { throw NetworkError.invalidResponse(what) }199        return k200    }201202    /// A value of the answer as short text for an error message.203    static func brief(_ v: SolanaJSON) -> String { String(v.serialized().prefix(200)) }204205    // MARK: chain identity and height206207    /// Checks that every endpoint that answers serves the expected cluster (genesis hash), and that at least one does.208    /// Run it before trusting balances and before every send: a mainnet endpoint configured for devnet (or the209    /// reverse) would otherwise show wrong balances or broadcast to the wrong cluster.210    public func verifyChain() async throws {211        guard !endpoints.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }212        var answered = 0213        var failures = [String]()214        for endpoint in endpoints {215            do {216                let hash = try await call("getGenesisHash", [], on: endpoint)217                guard let text = hash.string else { throw NetworkError.invalidResponse("getGenesisHash") }218                guard text == network.genesisHash else {219                    throw NetworkError.disagreement("\(endpoint.host ?? "?") serves another cluster than \(network.rawValue) (genesis \(String(text.prefix(44))))")220                }221                answered += 1222            } catch let e as NetworkError {223                if case .disagreement = e { throw e }224                failures.append("\(endpoint.host ?? "?"): \(e.summary)")225            } catch {226                failures.append("\(endpoint.host ?? "?"): \(NetworkError.transportSummary(error))")227            }228        }229        guard answered > 0 else { throw NetworkError.allEndpointsFailed(failures) }230    }231232    public func slot(commitment: SolanaCommitment = .confirmed) async throws -> UInt64 {233        try Self.u64(try await call("getSlot", [Self.config(commitment)]), "getSlot")234    }235236    /// Block height (not the slot): what `lastValidBlockHeight` is compared with to detect an expired blockhash.237    public func blockHeight(commitment: SolanaCommitment = .confirmed) async throws -> UInt64 {238        try Self.u64(try await call("getBlockHeight", [Self.config(commitment)]), "getBlockHeight")239    }240241    /// A recent blockhash and the last block height at which it is accepted (about 150 blocks, one to two minutes).242    public func latestBlockhash(commitment: SolanaCommitment = .confirmed) async throws -> SolanaBlockhash {243        let v = try await call("getLatestBlockhash", [Self.config(commitment)])["value"]244        guard let text = v?["blockhash"]?.string, let bytes = Base58.bitcoin.decode(text), bytes.count == 32 else {245            throw NetworkError.invalidResponse("getLatestBlockhash")246        }247        return SolanaBlockhash(blockhash: bytes, lastValidBlockHeight: try Self.u64(v?["lastValidBlockHeight"], "lastValidBlockHeight"))248    }249250    // MARK: accounts251252    /// Lamports of an account (0 when it does not exist).253    public func balance(of address: SolanaPublicKey, commitment: SolanaCommitment = .confirmed) async throws -> UInt64 {254        try Self.u64(try await call("getBalance", [.string(address.base58), Self.config(commitment)])["value"], "getBalance")255    }256257    /// Smallest balance that makes an account of `dataLength` bytes rent-exempt: 0 for a wallet (System account),258    /// `SolanaTokenProgram.Kind.associatedAccountSize` for a token account.259    public func minimumBalanceForRentExemption(dataLength: Int, commitment: SolanaCommitment = .confirmed) async throws -> UInt64 {260        try Self.u64(try await call("getMinimumBalanceForRentExemption", [.integer(max(0, dataLength)), Self.config(commitment)]),261                     "getMinimumBalanceForRentExemption")262    }263264    /// The account, or nil when it does not exist (jsonParsed encoding).265    public func accountInfo(_ address: SolanaPublicKey, commitment: SolanaCommitment = .confirmed) async throws -> SolanaAccountInfo? {266        let result = try await call("getAccountInfo", [.string(address.base58), Self.config(commitment, ["encoding": .string("jsonParsed")])])267        guard let value = result["value"] else { throw NetworkError.invalidResponse("getAccountInfo") }268        if value.isNull { return nil }269        return try Self.accountInfo(value)270    }271272    static func accountInfo(_ value: SolanaJSON) throws -> SolanaAccountInfo {273        guard let executable = value["executable"]?.bool else { throw NetworkError.invalidResponse("account") }274        let space = value["space"]?.uint64 ?? value["data"]?["space"]?.uint64 ?? 0275        return SolanaAccountInfo(lamports: try u64(value["lamports"], "account lamports"), owner: try key(value["owner"], "account owner"),276                                 executable: executable, space: space, parsed: value["data"]?["parsed"])277    }278279    /// The mint at `address`, or nil when no account exists there. Throws `invalidResponse` when the account exists280    /// but is not a mint of the Token or Token-2022 program: the address is not a token.281    public func mintInfo(_ address: SolanaPublicKey, commitment: SolanaCommitment = .confirmed) async throws -> SolanaMintInfo? {282        guard let account = try await accountInfo(address, commitment: commitment) else { return nil }283        return try Self.mintInfo(address: address, account: account)284    }285286    static func mintInfo(address: SolanaPublicKey, account: SolanaAccountInfo) throws -> SolanaMintInfo {287        guard let program = SolanaTokenProgram.Kind(programID: account.owner) else { throw NetworkError.invalidResponse("not a token mint") }288        guard let parsed = account.parsed, parsed["type"]?.string == "mint", let info = parsed["info"],289              let decimals = info["decimals"]?.uint64, decimals <= 255, let supplyText = info["supply"]?.string, let supply = UInt64(supplyText),290              let initialized = info["isInitialized"]?.bool else {291            // a token account, or a mint the node could not parse: in both cases nothing this wallet can transfer292            throw NetworkError.invalidResponse("not a token mint")293        }294        var extensions = [String]()295        var known = true296        if let list = info["extensions"] {297            guard let items = list.array, items.count <= 64 else { throw NetworkError.invalidResponse("mint extensions") }298            for item in items {299                if let name = item["extension"]?.string { extensions.append(String(name.prefix(64))) } else { known = false }300            }301        }302        return SolanaMintInfo(address: address, program: program, decimals: UInt8(decimals), supply: supply, isInitialized: initialized,303                              extensions: extensions, extensionsKnown: known)304    }305306    /// Every token account of `owner` under both token programs (two requests), at most `maximumTokenAccounts`.307    public func tokenAccounts(owner: SolanaPublicKey, commitment: SolanaCommitment = .confirmed) async throws -> [SolanaTokenAccount] {308        var out = [SolanaTokenAccount]()309        for program in SolanaTokenProgram.Kind.allCases {310            let result = try await call("getTokenAccountsByOwner", [.string(owner.base58), .object(["programId": .string(program.programID.base58)]),311                                                                    Self.config(commitment, ["encoding": .string("jsonParsed")])])312            guard let items = result["value"]?.array else { throw NetworkError.invalidResponse("getTokenAccountsByOwner") }313            for item in items.prefix(Self.maximumTokenAccounts - out.count) {314                let account = try Self.tokenAccount(item, program: program)315                // an endpoint must not slip in accounts of someone else316                guard account.owner == owner else { throw NetworkError.invalidResponse("token account of another owner") }317                out.append(account)318            }319        }320        return out321    }322323    static func tokenAccount(_ item: SolanaJSON, program: SolanaTokenProgram.Kind) throws -> SolanaTokenAccount {324        let account = item["account"]325        guard try key(account?["owner"], "token account program") == program.programID,326              let parsed = account?["data"]?["parsed"], parsed["type"]?.string == "account", let info = parsed["info"],327              let amountText = info["tokenAmount"]?["amount"]?.string, let amount = UInt64(amountText),328              let decimals = info["tokenAmount"]?["decimals"]?.uint64, decimals <= 255, let state = info["state"]?.string else {329            throw NetworkError.invalidResponse("token account")330        }331        return SolanaTokenAccount(address: try key(item["pubkey"], "token account address"), mint: try key(info["mint"], "token account mint"),332                                  owner: try key(info["owner"], "token account owner"), program: program, amount: amount, decimals: UInt8(decimals),333                                  state: String(state.prefix(32)), lamports: try u64(account?["lamports"], "token account lamports"))334    }335336    /// The token account at `address` (for instance an associated token account), or nil when it does not exist.337    /// Throws `invalidResponse` when the account exists but is not a token account.338    public func tokenAccount(_ address: SolanaPublicKey, commitment: SolanaCommitment = .confirmed) async throws -> SolanaTokenAccount? {339        let result = try await call("getAccountInfo", [.string(address.base58), Self.config(commitment, ["encoding": .string("jsonParsed")])])340        guard let value = result["value"] else { throw NetworkError.invalidResponse("getAccountInfo") }341        if value.isNull { return nil }342        guard let program = SolanaTokenProgram.Kind(programID: try Self.key(value["owner"], "account owner")) else {343            throw NetworkError.invalidResponse("not a token account")344        }345        return try Self.tokenAccount(.object(["pubkey": .string(address.base58), "account": value]), program: program)346    }347348    // MARK: history349350    /// Signatures of the transactions that reference `address`, newest first. `before` continues after the last351    /// signature of the previous page. `limit` is clamped to 1…`maximumSignaturesPerPage`.352    public func signatures(for address: SolanaPublicKey, limit: Int = 25, before: String? = nil,353                           commitment: SolanaCommitment = .confirmed) async throws -> [SolanaSignatureInfo] {354        let bounded = min(max(1, limit), Self.maximumSignaturesPerPage)355        var extra: [String: SolanaJSON] = ["limit": .integer(bounded)]356        if let before { extra["before"] = .string(before) }357        guard let items = try await call("getSignaturesForAddress", [.string(address.base58), Self.config(commitment, extra)]).array else {358            throw NetworkError.invalidResponse("getSignaturesForAddress")359        }360        return try items.prefix(bounded).map { item in361            guard let signature = item["signature"]?.string, Self.isSignature(signature) else { throw NetworkError.invalidResponse("signature") }362            let status = item["confirmationStatus"]?.string.flatMap(SolanaCommitment.init(rawValue:))363            return SolanaSignatureInfo(signature: signature, slot: try Self.u64(item["slot"], "signature slot"), blockTime: item["blockTime"]?.int64,364                                       failed: !(item["err"]?.isNull ?? true), confirmationStatus: status)365        }366    }367368    /// True for the base58 text of 64 bytes.369    public static func isSignature(_ text: String) -> Bool {370        guard (64...88).contains(text.utf8.count), let bytes = Base58.bitcoin.decode(text) else { return false }371        return bytes.count == 64372    }373374    /// The transaction with that signature in `jsonParsed` form, or nil when the node does not have it.375    /// `SolanaHistory.entry` turns it into balance changes for one address.376    public func transaction(_ signature: String, commitment: SolanaCommitment = .confirmed) async throws -> SolanaJSON? {377        guard Self.isSignature(signature) else { throw NetworkError.invalidResponse("signature") }378        let extra: [String: SolanaJSON] = ["encoding": .string("jsonParsed"), "maxSupportedTransactionVersion": .integer(Self.maximumTransactionVersion)]379        let result = try await call("getTransaction", [.string(signature), Self.config(commitment, extra)])380        return result.isNull ? nil : result381    }382383    /// One page of history for `address`: the signatures, then each transaction, normalised. Transactions the node384    /// no longer has are skipped. One request per transaction: keep `limit` small (public endpoints are rate limited).385    public func history(of address: SolanaPublicKey, limit: Int = 10, before: String? = nil,386                        commitment: SolanaCommitment = .confirmed) async throws -> [SolanaHistoryEntry] {387        var out = [SolanaHistoryEntry]()388        for info in try await signatures(for: address, limit: limit, before: before, commitment: commitment) {389            guard let json = try await transaction(info.signature, commitment: commitment) else { continue }390            out.append(try SolanaHistory.entry(transaction: json, signature: info.signature, for: address))391        }392        return out393    }394395    // MARK: fees396397    /// Priority fees (micro-lamports per compute unit) paid in recent slots by transactions that wrote to398    /// `accounts`, oldest first, at most 150 values. Feed them to `SolanaFees.suggestedUnitPrice`.399    public func recentPrioritizationFees(accounts: [SolanaPublicKey]) async throws -> [UInt64] {400        let params: [SolanaJSON] = [.array(accounts.prefix(128).map { .string($0.base58) })]401        guard let items = try await call("getRecentPrioritizationFees", params).array else {402            throw NetworkError.invalidResponse("getRecentPrioritizationFees")403        }404        return try items.suffix(150).map { try Self.u64($0["prioritizationFee"], "prioritizationFee") }405    }406407    /// The base fee the cluster charges for this message (signatures; the priority fee is not always included408    /// by every node version), or nil when the blockhash of the message is unknown to the node (expired).409    public func feeForMessage(_ message: SolanaMessage, commitment: SolanaCommitment = .confirmed) async throws -> UInt64? {410        let result = try await call("getFeeForMessage", [.string(SolanaBase64.encode(message.serialize())), Self.config(commitment)])411        guard let value = result["value"] else { throw NetworkError.invalidResponse("getFeeForMessage") }412        if value.isNull { return nil }413        return try Self.u64(value, "getFeeForMessage")414    }415416    // MARK: simulation, broadcast, tracking417418    /// Runs the transaction against the current state without broadcasting it. Signatures are not checked419    /// (`sigVerify: false`), so an unsigned transaction can be simulated before the user is asked to approve it.420    public func simulate(_ transaction: SolanaTransaction, commitment: SolanaCommitment = .confirmed) async throws -> SolanaSimulation {421        let extra: [String: SolanaJSON] = ["encoding": .string("base64"), "sigVerify": .bool(false), "replaceRecentBlockhash": .bool(false)]422        let result = try await call("simulateTransaction", [.string(try transaction.base64()), Self.config(commitment, extra)])423        guard let value = result["value"], let error = value["err"] else { throw NetworkError.invalidResponse("simulateTransaction") }424        let logs = (value["logs"]?.array ?? []).prefix(Self.maximumLogLines).compactMap { $0.string.map { String($0.prefix(500)) } }425        return SolanaSimulation(error: error.isNull ? nil : Self.brief(error), logs: logs, unitsConsumed: value["unitsConsumed"]?.uint64)426    }427428    /// Broadcasts a fully signed transaction to every endpoint (preflight simulation on, `maxRetries` rebroadcasts by429    /// the node) and returns its identifier. Success when one endpoint accepts it or already has it. The identifier430    /// is computed locally from the first signature; an endpoint that returns another one is treated as failed.431    ///432    /// Sending the same signed transaction again is safe: it has one signature, hence one identifier, and can be433    /// executed once. Never build and sign a *new* transaction for the same payment before the first one has434    /// expired (`blockHeight` above its `lastValidBlockHeight`) or failed: both could be executed.435    public func send(_ transaction: SolanaTransaction, maxRetries: Int = 5, preflightCommitment: SolanaCommitment = .confirmed) async throws -> String {436        guard transaction.isFullySigned, let id = transaction.id else { throw SolanaError.missingSignature }437        guard !endpoints.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }438        let params: [SolanaJSON] = [.string(try transaction.base64()), .object([439            "encoding": .string("base64"), "skipPreflight": .bool(false), "preflightCommitment": .string(preflightCommitment.rawValue),440            "maxRetries": .integer(min(max(0, maxRetries), 20)),441        ])]442        var accepted = false443        var failures = [String]()444        var rejection: NetworkError?445        for endpoint in endpoints {446            do {447                let result = try await call("sendTransaction", params, on: endpoint)448                guard result.string == id else { throw NetworkError.invalidResponse("sendTransaction returned another identifier") }449                accepted = true450            } catch NetworkError.rpc(_, let message) where message.range(of: "already been processed|AlreadyProcessed", options: [.regularExpression, .caseInsensitive]) != nil {451                accepted = true452            } catch let e as NetworkError {453                if case .rpc = e, rejection == nil { rejection = e }454                failures.append("\(endpoint.host ?? "?"): \(e.summary)")455            } catch {456                failures.append("\(endpoint.host ?? "?"): \(NetworkError.transportSummary(error))")457            }458        }459        if accepted { return id }460        // a rejection by the cluster (failed preflight, expired blockhash) is more useful than a list of hosts461        if let rejection, failures.count == endpoints.count { throw rejection }462        throw NetworkError.allEndpointsFailed(failures)463    }464465    /// Status of up to 256 transactions; nil for a signature the node does not know (not yet seen, expired, or466    /// older than its history unless `searchHistory` is set).467    public func signatureStatuses(_ signatures: [String], searchHistory: Bool = true) async throws -> [SolanaSignatureStatus?] {468        guard !signatures.isEmpty, signatures.count <= 256, signatures.allSatisfy(Self.isSignature) else { throw NetworkError.invalidResponse("signatures") }469        let result = try await call("getSignatureStatuses", [.array(signatures.map { .string($0) }),470                                                             .object(["searchTransactionHistory": .bool(searchHistory)])])471        guard let items = result["value"]?.array, items.count == signatures.count else { throw NetworkError.invalidResponse("getSignatureStatuses") }472        return try items.map(Self.signatureStatus)473    }474475    static func signatureStatus(_ item: SolanaJSON) throws -> SolanaSignatureStatus? {476        if item.isNull { return nil }477        let error = item["err"].flatMap { $0.isNull ? nil : Self.brief($0) }478        return SolanaSignatureStatus(slot: try Self.u64(item["slot"], "status slot"), confirmations: item["confirmations"]?.uint64, error: error,479                                     confirmationStatus: item["confirmationStatus"]?.string.flatMap(SolanaCommitment.init(rawValue:)))480    }481482    /// Where a sent transaction stands.483    public enum Tracking: Equatable, Sendable {484        /// Not in a block yet and its blockhash is still valid: keep waiting (and re-send the same signed bytes).485        case pending486        /// Included; `commitment` says how firmly.487        case included(slot: UInt64, commitment: SolanaCommitment)488        /// Included and failed on chain (the fee was paid, nothing else moved).489        case failed(slot: UInt64, error: String)490        /// Never included and its blockhash has expired: it can no longer be executed; a new transaction may be built.491        case expired492    }493494    /// One round of confirmation tracking for a transaction sent with `lastValidBlockHeight`.495    /// "Expired" is decided on the finalized block height, so that a slow node cannot declare a live transaction dead.496    ///497    /// QYV-SVC-021. **Every** endpoint is asked and the verdict must be unanimous among those that answer: "expired"498    /// and "failed" release the wallet's guard against paying twice, so one endpoint that hides an inclusion or499    /// announces a height it invented must not be enough to give them. Endpoints that disagree (or that see the500    /// transaction at different moments, which is normal while it propagates) give `.pending`; when all report the501    /// inclusion, the weakest commitment is returned. With a single endpoint configured there is nothing to compare502    /// with: its word is taken, and that residual risk is the user's choice of endpoint.503    public func track(signature: String, lastValidBlockHeight: UInt64) async throws -> Tracking {504        guard Self.isSignature(signature) else { throw NetworkError.invalidResponse("signatures") }505        guard !endpoints.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }506        var verdicts = [Tracking]()507        var failures = [String]()508        for endpoint in endpoints {509            do {510                verdicts.append(try await track(signature: signature, lastValidBlockHeight: lastValidBlockHeight, on: endpoint))511            } catch let e as NetworkError {512                failures.append("\(endpoint.host ?? "?"): \(e.summary)")513            } catch {514                failures.append("\(endpoint.host ?? "?"): \(NetworkError.transportSummary(error))")515            }516        }517        guard let first = verdicts.first else { throw NetworkError.allEndpointsFailed(failures) }518        var weakest = first519        for verdict in verdicts.dropFirst() {520            switch (weakest, verdict) {521            case (.expired, .expired), (.pending, .pending), (.failed, .failed): break522            case (.included(_, let a), .included(let slot, let b)): if b < a { weakest = .included(slot: slot, commitment: b) }523            default: return .pending524            }525        }526        return weakest527    }528529    /// The verdict of one endpoint.530    func track(signature: String, lastValidBlockHeight: UInt64, on endpoint: URL) async throws -> Tracking {531        let result = try await call("getSignatureStatuses", [.array([.string(signature)]), .object(["searchTransactionHistory": .bool(true)])], on: endpoint)532        guard let items = result["value"]?.array, items.count == 1 else { throw NetworkError.invalidResponse("getSignatureStatuses") }533        if let status = try Self.signatureStatus(items[0]) {534            if let error = status.error { return .failed(slot: status.slot, error: error) }535            return .included(slot: status.slot, commitment: status.confirmationStatus ?? .processed)536        }537        let height = try Self.u64(try await call("getBlockHeight", [Self.config(.finalized)], on: endpoint), "getBlockHeight")538        return height > lastValidBlockHeight ? .expired : .pending539    }540541    /// True when at least one endpoint of this cluster says `blockhash` is one of its recent blockhashes542    /// (`isBlockhashValid` at the `processed` commitment, the widest view a node has). Every endpoint is asked;543    /// throws when none answers.544    ///545    /// QYV-SVC-022. A Solana transaction names no cluster: the only thing that ties it to one is its recent546    /// blockhash. The wallet asks the **main** cluster this question before it signs a transaction prepared for a547    /// test cluster — the same key controls the account on every cluster.548    public func isRecentBlockhash(_ blockhash: Bytes) async throws -> Bool {549        guard blockhash.count == 32 else { throw SolanaError.invalidBlockhash }550        guard !endpoints.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }551        var answered = 0552        var failures = [String]()553        for endpoint in endpoints {554            do {555                let result = try await call("isBlockhashValid", [.string(Base58.bitcoin.encode(blockhash)), Self.config(.processed)], on: endpoint)556                guard let valid = result["value"]?.bool else { throw NetworkError.invalidResponse("isBlockhashValid") }557                if valid { return true }558                answered += 1559            } catch let e as NetworkError {560                failures.append("\(endpoint.host ?? "?"): \(e.summary)")561            } catch {562                failures.append("\(endpoint.host ?? "?"): \(NetworkError.transportSummary(error))")563            }564        }565        guard answered > 0 else { throw NetworkError.allEndpointsFailed(failures) }566        return false567    }568}569570/// Fee helpers.571public enum SolanaFees {572    /// Floor and ceiling of the suggested compute-unit price, in micro-lamports.573    public static let minimumUnitPrice: UInt64 = 5_000574    public static let maximumUnitPrice: UInt64 = 2_000_000575576    /// The 75th percentile of recent prioritization fees, kept between `minimumUnitPrice` and `maximumUnitPrice`577    /// (the floor when there is no data): enough to pass in normal conditions without following outliers.578    public static func suggestedUnitPrice(recentFees: [UInt64]) -> UInt64 {579        guard !recentFees.isEmpty else { return minimumUnitPrice }580        let sorted = recentFees.sorted()581        let percentile = sorted[min(sorted.count - 1, sorted.count * 3 / 4)]582        return min(maximumUnitPrice, max(minimumUnitPrice, percentile))583    }584}585
Files main
Menu

Theme