Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraWallet/WalletService+Solana.swift8// Module : Qyvora Wallet9// 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 QyvoraMath43import QyvoraCore44import QyvoraNetworking45import QyvoraSolana4647/// The Solana part of a send review: the plan the transaction was built from, and what the node said about it.48public struct SolanaSendDetails: Equatable, Sendable {49 public let network: SolanaNetwork50 /// The unsigned transaction and every figure derived from it (`plan.review` is what a cold device would decode).51 public let plan: SolanaSendPlan52 /// Compute units the simulation consumed; nil when the node did not say.53 public let simulatedUnits: UInt64?54 /// Block height after which the transaction can no longer be executed (about a minute after it was prepared).55 public var lastValidBlockHeight: UInt64 { plan.blockhash.lastValidBlockHeight }56}5758extension WalletService {59 // MARK: Clients and accounts6061 static let solanaPriceID = "solana"6263 /// CoinGecko identifiers of the built-in SPL tokens, by mint.64 static let solanaTokenPriceIDs: [String: String] = [65 "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v": "usd-coin",66 "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB": "tether",67 ]6869 func solanaAccount(_ network: SolanaNetwork) throws -> SolanaPublicKey {70 _ = try requireWallet()71 try requireAllowed(.solana(network))72 guard let text = profile.solanaAddress, let key = SolanaPublicKey(base58: text) else {73 throw WalletError.featureUnavailable("This wallet has no Solana account.")74 }75 return key76 }7778 /// Verifies once per session (and per endpoint list) that the endpoints serve the expected cluster (genesis hash).79 func verifiedSolana(_ network: SolanaNetwork) async throws -> SolanaRPC {80 try requireAllowed(.solana(network))81 if gate.isOffline { throw WalletError.offline }82 let client = SolanaRPC(network: network, endpoints: profile.solanaEndpoints, transport: gate)83 guard client.isConfigured else { throw WalletError.network("No Solana RPC endpoint is configured for \(network.displayName).") }84 let key = "sol|\(network.rawValue)|" + (profile.solanaEndpoints.rpc[network.rawValue] ?? []).joined(separator: ",")85 if !verifiedChains.contains(key) {86 do {87 try await client.verifyChain()88 } catch NetworkError.disagreement(let text) {89 throw WalletError.wrongChain(text)90 }91 verifiedChains.insert(key)92 }93 return client94 }9596 // MARK: Token list9798 static func solanaStandard(_ program: SolanaTokenProgram.Kind) -> ChainToken.Standard { program == .token2022 ? .splToken2022 : .spl }99100 static func builtInSolanaTokens(_ network: SolanaNetwork) -> [ChainToken] {101 let chain = ChainRegistry.id(network)102 return SolanaToken.builtIn(network).map {103 ChainToken(chain: chain, address: $0.mint.base58, symbol: $0.symbol, name: $0.name, decimals: Int($0.decimals), standard: solanaStandard($0.program),104 priceID: solanaTokenPriceIDs[$0.mint.base58])105 }106 }107108 /// Built-in, then custom tokens of a cluster (hidden ones included).109 func knownSolanaTokens(_ network: SolanaNetwork) -> [ChainToken] {110 let chain = ChainRegistry.id(network)111 var seen = Set<String>()112 return (Self.builtInSolanaTokens(network) + profile.customSolanaTokens.filter { $0.chain == chain }).filter { seen.insert($0.address).inserted }113 }114115 func listedSolanaTokens(_ network: SolanaNetwork) -> [ChainToken] {116 let hidden = Set(profile.hiddenTokens)117 return knownSolanaTokens(network).filter { !hidden.contains($0.id) }118 }119120 // MARK: Synchronization121122 /// Signatures of history read at each synchronization (one request per transaction follows).123 static let solanaHistoryLimit = 20124 /// Token accounts of unknown mints reported at most.125 static let solanaDetectedLimit = 50126127 func syncSolana(_ network: SolanaNetwork) async throws {128 try await runChainSync(.solana(network)) { try await self.performSolanaSync(network) }129 }130131 private func performSolanaSync(_ network: SolanaNetwork) async throws {132 let kind = ChainKind.solana(network)133 let chain = ChainRegistry.id(network)134 let owner = try solanaAccount(network)135 let rpc = try await verifiedSolana(network)136 var notes = [String]()137138 noteProgress(kind, stage: "Reading the account", completed: 0, total: 4)139 let slot = try await rpc.slot()140 let lamports = try await rpc.balance(of: owner)141142 noteProgress(kind, stage: "Reading token accounts", completed: 1, total: 4)143 let accounts = try await rpc.tokenAccounts(owner: owner)144 // one holding per mint: a wallet may own several token accounts of the same mint145 struct Sum { var amount: UInt64 = 0; var decimals: UInt8; var program: SolanaTokenProgram.Kind; var frozen = false; var overflow = false; var count = 0 }146 var byMint = [String: Sum]()147 var order = [String]()148 for a in accounts {149 let mint = a.mint.base58150 if byMint[mint] == nil { order.append(mint) }151 var sum = byMint[mint] ?? Sum(decimals: a.decimals, program: a.program)152 let (total, overflow) = sum.amount.addingReportingOverflow(a.amount)153 sum.amount = total154 sum.overflow = sum.overflow || overflow || a.decimals != sum.decimals155 sum.frozen = sum.frozen || a.isFrozen156 sum.count += 1157 byMint[mint] = sum158 }159 let hidden = Set(profile.hiddenTokens)160 let listed = listedSolanaTokens(network)161 var holdings = [ChainHolding]()162 for token in listed {163 guard let sum = byMint[token.address] else {164 // no token account: the wallet holds none of it165 holdings.append(ChainHolding(token: token, amount: .zero, reason: nil, warning: nil, listed: true))166 continue167 }168 if sum.overflow {169 holdings.append(ChainHolding(token: token, amount: nil, reason: "The token accounts of this mint do not add up.", warning: nil, listed: true))170 } else if Int(sum.decimals) != token.decimals {171 holdings.append(ChainHolding(token: token, amount: nil, reason: "The chain reports \(sum.decimals) decimals, the token list says \(token.decimals).", warning: nil,172 listed: true))173 } else {174 holdings.append(ChainHolding(token: token, amount: UInt256(sum.amount), reason: nil,175 warning: sum.frozen ? "This token account is frozen by the token's issuer: it cannot send." : nil, listed: true))176 }177 }178 let known = Set(knownSolanaTokens(network).map(\.address))179 var detected = 0180 for mint in order where !known.contains(mint) {181 guard let sum = byMint[mint], sum.amount > 0, !sum.overflow else { continue }182 // a mint carries no symbol on chain: the wallet shows the mint itself and never a name it did not verify183 let token = ChainToken(chain: chain, address: mint, symbol: String(mint.prefix(4)) + "…" + String(mint.suffix(4)), name: "Unlisted SPL token",184 decimals: Int(sum.decimals), standard: Self.solanaStandard(sum.program), isCustom: true)185 guard !hidden.contains(token.id) else { continue }186 if detected == Self.solanaDetectedLimit {187 notes.append("More than \(Self.solanaDetectedLimit) unlisted tokens were found on this account; only the first ones are shown.")188 break189 }190 detected += 1191 holdings.append(ChainHolding(token: token, amount: UInt256(sum.amount), reason: nil,192 warning: sum.frozen ? "This token account is frozen by the token's issuer: it cannot send." : nil, listed: false))193 }194 if accounts.count >= SolanaRPC.maximumTokenAccounts {195 notes.append("This account has \(SolanaRPC.maximumTokenAccounts) token accounts or more; the ones beyond that number were not read.")196 }197198 noteProgress(kind, stage: "Reading rent minimums", completed: 2, total: 4)199 let systemRent = try await rpc.minimumBalanceForRentExemption(dataLength: 0)200 let tokenRent = try await rpc.minimumBalanceForRentExemption(dataLength: SolanaTokenProgram.Kind.token.associatedAccountSize)201 let token2022Rent = try await rpc.minimumBalanceForRentExemption(dataLength: SolanaTokenProgram.Kind.token2022.associatedAccountSize)202 let ceiling = MainnetPolicy.solanaAccountCreationLamportsCeiling203 guard systemRent > 0, systemRent <= ceiling, tokenRent >= systemRent, tokenRent <= ceiling, token2022Rent >= systemRent, token2022Rent <= ceiling else {204 throw WalletError.untrustedResponse("rent minimums out of range")205 }206 let extras = SolanaExtras(accountExists: lamports > 0, systemAccountRent: systemRent, tokenAccountRent: tokenRent, token2022AccountRent: token2022Rent,207 tokenAccountCount: accounts.count)208209 noteProgress(kind, stage: "Reading history", completed: 3, total: 4)210 var history: [ActivityEntry]?211 var historyReason: String?212 var hasOutgoing: Bool?213 do {214 let tokens = Dictionary(uniqueKeysWithValues: knownSolanaTokens(network).map { ($0.address, $0) })215 let signatures = try await rpc.signatures(for: owner, limit: Self.solanaHistoryLimit)216 let read = try await boundedMap(signatures, limit: 2) { info -> (SolanaSignatureInfo, SolanaHistoryEntry?) in217 do {218 guard let json = try await rpc.transaction(info.signature) else { return (info, nil) }219 return (info, try SolanaHistory.entry(transaction: json, signature: info.signature, for: owner))220 } catch let e as NetworkError {221 if case .offline = e { throw e }222 return (info, nil)223 }224 }225 var entries = [ActivityEntry]()226 var skipped = 0227 var outgoing = false228 for (info, entry) in read {229 guard let entry else {230 skipped += 1231 continue232 }233 if entry.isInitiator(owner) { outgoing = true }234 entries += Self.activity(entry, info: info, owner: owner, chain: chain, tokens: tokens)235 }236 if skipped > 0 { notes.append("\(skipped) transaction(s) of the history could not be read from the endpoint and are not shown.") }237 if signatures.count >= Self.solanaHistoryLimit { notes.append("Only the \(Self.solanaHistoryLimit) most recent transactions are shown.") }238 history = entries239 // older transactions than the page read may exist: "none found" is only a fact when the page was not full240 hasOutgoing = outgoing ? true : (signatures.count < Self.solanaHistoryLimit && skipped == 0 ? false : nil)241 } catch let e as NetworkError {242 if case .offline = e { throw e }243 historyReason = Self.describe(WalletError.from(e))244 }245246 guard profile.kind != nil, Self.activeKinds(profile).contains(kind), profile.solanaAddress == owner.base58,247 let identity = Self.solanaIdentity(profile, network: network) else {248 throw WalletError.stalePlan("the active network changed during synchronization")249 }250 solanaRecords[network] = SolanaChainRecord(identity: identity, network: network, address: owner.base58, synchronizedAt: now(), slot: slot, lamports: lamports,251 extras: extras, holdings: holdings, history: history, historyReason: historyReason, hasOutgoing: hasOutgoing,252 notes: notes, isFromPreviousSession: nil)253 persistSolana(network)254 }255256 /// One transaction as activity lines: the balance changes the node reports for this account, never an257 /// interpretation of the instructions. The counterparty is not known from balance changes and is left empty.258 static func activity(_ e: SolanaHistoryEntry, info: SolanaSignatureInfo, owner: SolanaPublicKey, chain: ChainID,259 tokens: [String: ChainToken]) -> [ActivityEntry] {260 let status: ActivityEntry.Status = !e.succeeded ? .failed : (info.confirmationStatus == .finalized ? .finalized : .confirmed(confirmations: nil))261 let time = e.blockTime.flatMap { $0 > 0 ? Date(timeIntervalSince1970: TimeInterval($0)) : nil }262 let paidFee = e.isInitiator(owner)263 var out = [ActivityEntry]()264 var feeShown = false265 func fee() -> UInt256? {266 guard paidFee, !feeShown else { return nil }267 feeShown = true268 return UInt256(e.fee)269 }270 for (n, change) in e.tokenChanges.enumerated() where !change.change.isZero {271 let mint = change.mint.base58272 let token = tokens[mint]273 out.append(ActivityEntry(chain: chain, id: "\(e.signature):token:\(n)", hash: e.signature, direction: change.change.isNegative ? .sent : .received,274 counterparty: nil, amount: UInt256(change.change.magnitude), decimals: Int(change.decimals), symbol: token?.symbol, fee: fee(),275 status: status, time: time, blockHeight: e.slot,276 kind: .token(address: mint, symbol: token?.symbol, decimals: Int(change.decimals), verified: true)))277 }278 // the native change without the fee this account paid279 var magnitude = e.nativeChange.magnitude280 var negative = e.nativeChange.isNegative281 if paidFee {282 if negative {283 magnitude = magnitude >= e.fee ? magnitude - e.fee : 0284 } else {285 let (sum, overflow) = magnitude.addingReportingOverflow(e.fee)286 magnitude = overflow ? magnitude : sum287 }288 if magnitude == 0 { negative = false }289 }290 if magnitude > 0 {291 out.append(ActivityEntry(chain: chain, id: "\(e.signature):native", hash: e.signature, direction: negative ? .sent : .received, counterparty: nil,292 amount: UInt256(magnitude), decimals: SolanaNetwork.decimals, symbol: SolanaNetwork.symbol, fee: fee(), status: status,293 time: time, blockHeight: e.slot, kind: .native))294 }295 if out.isEmpty {296 // nothing moved for this account but the fee (a failed transaction, or a call without transfer)297 out.append(ActivityEntry(chain: chain, id: "\(e.signature):call", hash: e.signature, direction: .none, counterparty: nil, amount: .zero,298 decimals: SolanaNetwork.decimals, symbol: SolanaNetwork.symbol, fee: fee(), status: status, time: time, blockHeight: e.slot,299 kind: .contract(method: nil)))300 }301 return out302 }303304 // MARK: Custom tokens305306 /// Adds an SPL token by mint address. **Network**: the mint is read on chain (decimals, token program, Token-2022307 /// extensions). A mint carries no symbol: `label` is the user's own name for it (16 characters at most), shown as308 /// such; without one the shortened mint address is shown.309 func addSolanaToken(mint text: String, label: String?, network: SolanaNetwork) async throws -> ChainToken {310 _ = try requireWallet()311 let chain = ChainRegistry.id(network)312 guard let mint = SolanaPublicKey(base58: text.trimmingCharacters(in: .whitespacesAndNewlines)) else {313 throw WalletError.address(Self.classifyForeign(text, expected: .solana, chainName: "Solana", expectedForm: "A mint address is 32 to 44 base58 characters."))314 }315 if let existing = knownSolanaTokens(network).first(where: { $0.address == mint.base58 }) {316 profile.hiddenTokens.removeAll { $0 == existing.id }317 try saveProfile()318 alignSolanaHoldings(network)319 return existing320 }321 let rpc = try await verifiedSolana(network)322 let info: SolanaMintInfo323 do {324 guard let found = try await rpc.mintInfo(mint) else { throw WalletError.solana(.missingTokenData) }325 info = found326 } catch NetworkError.invalidResponse {327 throw WalletError.invalidInput("This address is not a token mint on \(network.displayName).")328 }329 let cleaned = (label ?? "").unicodeScalars.filter { $0.isASCII && $0.value > 0x20 && $0.value < 0x7f }.map(Character.init)330 let symbol = cleaned.isEmpty ? String(mint.base58.prefix(4)) + "…" + String(mint.base58.suffix(4)) : String(String(cleaned).prefix(16))331 let token = ChainToken(chain: chain, address: mint.base58, symbol: symbol, name: cleaned.isEmpty ? "SPL token" : "SPL token (your label)",332 decimals: Int(info.decimals), standard: Self.solanaStandard(info.program), isCustom: true,333 note: info.transferRefusal.map { "QYVORA can show this token but will not send it: \($0)." })334 guard profile.kind != nil, Self.activeKinds(profile).contains(.solana(network)) else { throw WalletError.stalePlan("the active network changed") }335 profile.customSolanaTokens.removeAll { $0.id == token.id }336 profile.customSolanaTokens.append(token)337 profile.hiddenTokens.removeAll { $0 == token.id }338 try saveProfile()339 alignSolanaHoldings(network)340 return token341 }342343 /// Brings the holdings of the Solana record in line with the token list, without network.344 func alignSolanaHoldings(_ network: SolanaNetwork) {345 guard var record = solanaRecords[network] else { return }346 let hidden = Set(profile.hiddenTokens)347 let listed = listedSolanaTokens(network)348 let listedIDs = Set(listed.map(\.id))349 var known = [String: ChainHolding]()350 for h in record.holdings { known[h.token.id] = h }351 var holdings = listed.map { token -> ChainHolding in352 if let h = known[token.id] {353 // a detected holding that was accepted keeps the balance read on chain354 let mismatch = h.token.decimals != token.decimals355 return ChainHolding(token: token, amount: mismatch ? nil : h.amount,356 reason: mismatch ? "The chain reports \(h.token.decimals) decimals, the token list says \(token.decimals)." : h.reason,357 warning: h.warning, listed: true)358 }359 return ChainHolding(token: token, amount: nil, reason: "Not read yet: synchronize.", warning: nil, listed: true)360 }361 holdings += record.holdings.filter { !$0.listed && !listedIDs.contains($0.token.id) && !hidden.contains($0.token.id) }362 guard holdings != record.holdings else { return }363 record.holdings = holdings364 solanaRecords[network] = record365 persistSolana(network)366 }367368 // MARK: Sending369370 /// True when a payment with this key was signed in this session and can still be executed.371 func inFlightPayment(_ paymentKey: String) -> SentTransaction? {372 sentTransactions.values.first { $0.paymentKey == paymentKey && !$0.settled && $0.outcome != .rejected }373 }374375 static func paymentKey(_ kind: ChainKind, recipient: String, asset: ChainAsset, amount: UInt256) -> String {376 var assetKey = "native"377 if case .token(let token) = asset { assetKey = token.address }378 return "\(ChainRegistry.id(kind).rawValue)|\(recipient)|\(assetKey)|\(amount)"379 }380381 /// Refuses a payment that is the same as one still in flight; a first one that has settled meanwhile is marked so.382 func requireNoPaymentInFlight(_ paymentKey: String) async throws {383 guard let first = inFlightPayment(paymentKey) else { return }384 switch try await trackSent(first) {385 case .pending, .notFound: throw WalletError.transactionInFlight(id: first.id)386 default: break387 }388 }389390 /// How long a Solana transaction stays valid after its blockhash was read: 150 blocks, about a minute at the391 /// cluster's target of 400 ms a block. An estimate for the interface; the chain decides by block height392 /// (`SolanaBlockhash.lastValidBlockHeight`, which tracking uses).393 public static let solanaBlockhashLifetime: TimeInterval = 60394395 func prepareSolanaSend(network: SolanaNetwork, asset requested: ChainAsset, to: String, amount: UInt256, options: SendOptions) async throws -> SendReview {396 let kind = ChainKind.solana(network)397 let descriptor = ChainRegistry.descriptor(kind)398 // the symbol of a token is the wallet's own, never the caller's description (QYV-SVC-103); its decimals are399 // read from the mint when the payment is planned400 let asset: ChainAsset401 if case .token(let asked) = requested { asset = .token(try solanaToken(asked, network: network)) } else { asset = requested }402 let sender = try solanaAccount(network)403 let check = try checkAddress(to, kind: kind)404 guard let recipient = SolanaPublicKey(base58: check.canonical) else { throw WalletError.address(.malformed(chain: "Solana", expected: "")) }405 guard options.sendMax || amount.uint64 != nil else { throw WalletError.invalidInput("The amount is too large.") }406 var requestAsset = SolanaSendRequest.Asset.sol407 if case .token(let token) = asset {408 guard token.chain == descriptor.id, let mint = SolanaPublicKey(base58: token.address) else { throw WalletError.invalidInput("This token belongs to another network.") }409 requestAsset = .token(mint: mint)410 }411 if !options.sendMax { try await requireNoPaymentInFlight(Self.paymentKey(kind, recipient: recipient.base58, asset: asset, amount: amount)) }412 let rpc = try await verifiedSolana(network)413414 // priority fee: the 75th percentile of what recent transactions paid, halved or doubled by the tier415 var unitPrice = SolanaFees.minimumUnitPrice416 if let explicit = options.solanaComputeUnitPrice {417 unitPrice = explicit418 } else {419 let recent = (try? await rpc.recentPrioritizationFees(accounts: [sender])) ?? []420 let suggested = SolanaFees.suggestedUnitPrice(recentFees: recent)421 switch options.feeTier {422 case .slow: unitPrice = max(SolanaFees.minimumUnitPrice, suggested / 2)423 case .normal: unitPrice = suggested424 case .fast: unitPrice = min(SolanaFees.maximumUnitPrice, suggested.multipliedReportingOverflow(by: 2).overflow ? SolanaFees.maximumUnitPrice : suggested * 2)425 }426 }427 let memo = options.memo.flatMap { $0.isEmpty ? nil : $0 }428 let request = SolanaSendRequest(sender: sender, recipient: recipient, asset: requestAsset, amount: options.sendMax ? .max : .exact(amount.uint64 ?? 0),429 memo: memo, computeUnitPrice: unitPrice)430 let snapshot: SolanaChainSnapshot431 do {432 snapshot = try await rpc.snapshot(for: request)433 } catch NetworkError.invalidResponse(let what) where what == "not a token mint" {434 throw WalletError.solana(.missingTokenData)435 }436 let ceiling = MainnetPolicy.solanaAccountCreationLamportsCeiling437 guard snapshot.systemAccountRent > 0, snapshot.systemAccountRent <= ceiling, (snapshot.token?.tokenAccountRent ?? 0) <= ceiling else {438 throw WalletError.untrustedResponse("rent minimums out of range")439 }440 let plan = try SolanaSendPlanner.plan(request, snapshot: snapshot)441 try await enforceUnauditedSolanaLimits(plan.transaction, network: network, owner: sender)442 // QYV-SVC-022: refused here already, so that a transaction valid on mainnet-beta is neither shown for443 // signature nor exported to a cold device (checked again just before signing)444 try await requireNotValidOnMainnet(plan.transaction, network: network)445446 // the node runs the very transaction on current state before the user is asked anything447 let simulation = try await rpc.simulate(plan.transaction)448 guard simulation.succeeded else {449 throw WalletError.simulationFailed((simulation.error ?? "failed") + (simulation.logs.last.map { " — \($0)" } ?? ""))450 }451452 var warnings = [SendWarning]()453 for w in plan.warnings {454 switch w {455 case .recipientOffCurve:456 warnings.append(SendWarning(id: "solana.off-curve", message: "This address is not a wallet key (it is a program-derived address): only the program it belongs to can move what is sent there.", isCritical: true))457 case .recipientIsNew:458 warnings.append(SendWarning(id: "solana.new-account", message: "No account exists at this address yet: this payment creates it.", isCritical: false))459 case .createsRecipientTokenAccount:460 warnings.append(SendWarning(id: "solana.creates-token-account", message: "The recipient has no account for this token: you pay \(WalletMessages.sol(plan.accountCreationCost)) to create it. That amount stays in the recipient's account; it is not a fee.", isCritical: false))461 case .emptiesSender:462 warnings.append(SendWarning(id: "solana.empties-sender", message: "This leaves no SOL on your account: it disappears from the chain until it is funded again, and token transfers need SOL for fees.", isCritical: false))463 case .tokenHasPermanentDelegate:464 warnings.append(SendWarning(id: "solana.permanent-delegate", message: "The issuer of this token can move or burn it from any account, the recipient's included.", isCritical: false))465 }466 }467 if !paidRecipients.contains(Self.paidKey(kind, recipient.base58)) {468 warnings.append(SendWarning(id: "first-payment", message: "First payment to this address from this device: a Solana address has no checksum, and a mistyped character usually gives another valid address. Compare every character with the address you were given, on its original source.", isCritical: true))469 }470 if !network.isTest, MainnetPolicy.unauditedMainnet { warnings.append(SendWarning(id: "unaudited-mainnet", message: WalletError.unauditedText, isCritical: true)) }471472 var symbol = SolanaNetwork.symbol473 if case .token(let token) = asset { symbol = token.symbol }474 let notes = [475 "The transaction was simulated by the network and would succeed on the state it saw.",476 "It is valid for about a minute (until block height \(plan.blockhash.lastValidBlockHeight)). After that it can no longer be executed and must be prepared again.",477 ]478 let maximumFee = plan.fee479 let review = makeReview(kind: kind, from: sender.base58, recipient: recipient.base58, asset: asset, amount: UInt256(plan.amount), decimals: Int(plan.decimals),480 symbol: symbol, expectedFee: UInt256(plan.fee), maximumFee: UInt256(maximumFee),481 feeLines: [SendFeeLine(label: "Signature fee", amount: UInt256(plan.signatureFee)),482 SendFeeLine(label: "Priority fee", amount: UInt256(plan.priorityFee))]483 + (plan.accountCreationCost > 0 ? [SendFeeLine(label: "New token account for the recipient (not a fee)", amount: UInt256(plan.accountCreationCost))] : []),484 totalNative: UInt256(plan.totalLamports), isSendMax: options.sendMax, warnings: warnings, notes: notes,485 // counted from now: the blockhash was read a moment ago, so the transaction expires no later486 expiresAt: now().addingTimeInterval(Self.solanaBlockhashLifetime),487 body: .solana(SolanaSendDetails(network: network, plan: plan, simulatedUnits: simulation.unitsConsumed)))488 // what the review shows is what the bytes say, read back by the decoder a cold device would use489 try Self.requireSolanaPayment(plan.transaction, matches: review, owner: sender)490 return review491 }492493 /// QYV-SVC-023. Checks the figures of a review against the **decoding of the bytes that will be signed**: the494 /// transaction must be a legacy message signed and paid by `owner` alone, made of the compute-unit limit, the495 /// compute-unit price, at most one creation of the recipient's own associated token account, exactly one transfer496 /// — of the reviewed amount, of the reviewed asset, to the reviewed recipient — and at most one memo; and its fee497 /// (signature fee plus priority fee) must be the fee shown. Applied when the review is made and again before it is498 /// signed, so that neither a defect of the planner nor a review object altered in memory can make the wallet sign499 /// something else than what was shown.500 static func requireSolanaPayment(_ transaction: SolanaTransaction, matches review: SendReview, owner: SolanaPublicKey) throws {501 func refuse(_ what: String) -> WalletError {502 .stalePlan("The transaction does not match what the review shows (\(what)). Prepare the payment again.")503 }504 let decoded = transaction.message.review()505 guard decoded.version == .legacy, decoded.feePayer == owner, decoded.signers == [owner], !decoded.requiresBlindSigning else { throw refuse("signers") }506 guard review.from == owner.base58, let recipient = SolanaPublicKey(base58: review.recipient), let amount = review.amount.uint64, amount > 0 else {507 throw refuse("parties")508 }509 guard let priority = decoded.priorityFee else { throw refuse("fee") }510 let (fee, feeOverflow) = decoded.signatureFee.addingReportingOverflow(priority)511 guard !feeOverflow, UInt256(fee) == review.fee.maximum, review.fee.expected == review.fee.maximum else { throw refuse("fee") }512513 var rest = decoded.instructions[...]514 guard case .computeUnitLimit? = rest.first else { throw refuse("compute-unit limit") }515 rest = rest.dropFirst()516 guard case .computeUnitPrice? = rest.first else { throw refuse("compute-unit price") }517 rest = rest.dropFirst()518 switch review.asset {519 case .native:520 guard case .systemTransfer(let from, let to, let lamports)? = rest.first, from == owner, to == recipient, lamports == amount,521 review.amountDecimals == SolanaNetwork.decimals else { throw refuse("transfer") }522 rest = rest.dropFirst()523 case .token(let token):524 guard let mint = SolanaPublicKey(base58: token.address) else { throw refuse("token") }525 if case .createAssociatedTokenAccount(let payer, let account, let accountOwner, let createdMint, let program, let idempotent)? = rest.first {526 guard payer == owner, accountOwner == recipient, createdMint == mint, idempotent, let kind = SolanaTokenProgram.Kind(programID: program),527 (try? SolanaAddress.associatedTokenAccount(owner: recipient, mint: mint, tokenProgram: kind)) == account else {528 throw refuse("token account creation")529 }530 rest = rest.dropFirst()531 }532 guard case .tokenTransferChecked(let kind, let source, let sentMint, let destination, let authority, let sent, let decimals)? = rest.first,533 authority == owner, sentMint == mint, sent == amount, Int(decimals) == review.amountDecimals,534 (try? SolanaAddress.associatedTokenAccount(owner: owner, mint: mint, tokenProgram: kind)) == source,535 (try? SolanaAddress.associatedTokenAccount(owner: recipient, mint: mint, tokenProgram: kind)) == destination else {536 throw refuse("token transfer")537 }538 rest = rest.dropFirst()539 }540 if case .memo? = rest.first { rest = rest.dropFirst() }541 guard rest.isEmpty else { throw refuse("unexpected instruction") }542 }543544 /// QYV-SVC-022. A Solana transaction names no cluster, and this wallet's account is the same key on every545 /// cluster: a transaction prepared for a test cluster whose recent blockhash is in fact a blockhash of546 /// mainnet-beta — which an endpoint of the test cluster can arrange, since the blockhash comes from it — would be547 /// executed on mainnet-beta with real funds, whatever the mainnet switch and the limits say. Before signing a548 /// test-cluster transaction the wallet therefore asks the mainnet-beta endpoints whether they know its blockhash549 /// and refuses when one does. When no mainnet-beta endpoint answers, nothing is signed (the check cannot be made).550 /// Only the blockhash is sent: no address, no amount.551 func requireNotValidOnMainnet(_ transaction: SolanaTransaction, network: SolanaNetwork) async throws {552 guard network.isTest else { return }553 if gate.isOffline { throw WalletError.offline }554 let mainnet = SolanaRPC(network: .mainnetBeta, endpoints: profile.solanaEndpoints, transport: gate)555 guard mainnet.isConfigured else {556 throw WalletError.network("No Solana mainnet endpoint is configured: QYVORA cannot check that this test transaction is not also valid on the main network, and does not sign it.")557 }558 let known: Bool559 do {560 known = try await mainnet.isRecentBlockhash(transaction.message.recentBlockhash)561 } catch let e as NetworkError {562 if case .offline = e { throw WalletError.offline }563 throw WalletError.network("The Solana mainnet endpoints did not answer: QYVORA cannot check that this test transaction is not also valid on the main network, and does not sign it. (\(e.summary))")564 }565 guard !known else {566 throw WalletError.wrongChain("The blockhash this \(network.displayName) endpoint gave is a blockhash of Solana mainnet: the transaction would be valid on the main network, with real funds. Nothing was signed. Change the \(network.displayName) endpoint.")567 }568 }569570 /// What a Solana transaction moves out of `owner`, read from its decoded instructions (the same decoding as on a571 /// cold device): lamports sent by System transfers, token amounts by mint, the priority fee, and whether anything572 /// in it could not be decoded.573 struct SolanaOutflow {574 var lamports: UInt64 = 0575 var tokens: [String: (amount: UInt64, decimals: UInt8)] = [:]576 var priorityFee: UInt64 = 0577 var createsAccounts = 0578 var blind = false579 var other = [String]()580 }581582 static func solanaOutflow(_ review: SolanaTransactionReview, owner: SolanaPublicKey) -> SolanaOutflow {583 var out = SolanaOutflow()584 out.blind = review.requiresBlindSigning585 guard let fee = review.priorityFee else {586 out.blind = true587 return out588 }589 out.priorityFee = fee590 for instruction in review.instructions {591 switch instruction {592 case .systemTransfer(let from, _, let lamports):593 if from == owner {594 let (sum, overflow) = out.lamports.addingReportingOverflow(lamports)595 out.lamports = overflow ? .max : sum596 }597 case .tokenTransferChecked(_, _, let mint, _, let authority, let amount, let decimals):598 if authority == owner {599 let (sum, overflow) = (out.tokens[mint.base58]?.amount ?? 0).addingReportingOverflow(amount)600 out.tokens[mint.base58] = (overflow ? .max : sum, decimals)601 }602 case .createAssociatedTokenAccount(let payer, _, _, _, _, _):603 if payer == owner { out.createsAccounts += 1 }604 case .computeUnitLimit, .computeUnitPrice, .memo:605 break606 case .unknown:607 out.blind = true608 default:609 // decodable, but not something a payment contains (approvals, account closing, raw transfers…)610 out.other.append(instruction.summary)611 }612 }613 return out614 }615616 /// Ceilings of an unaudited build on Solana mainnet, applied when a transaction is prepared and again before it is617 /// signed (on the online device and on a cold one): SOL sent ≤ 150 USD at a fresh price; each token ≤ 150 USD at a618 /// fresh price (a token without known price cannot be sent); priority fee ≤ 0.01 SOL; nothing that is not a plain619 /// payment (no instruction the wallet cannot decode, no approval, no account closing).620 func enforceUnauditedSolanaLimits(_ transaction: SolanaTransaction, network: SolanaNetwork, owner: SolanaPublicKey) async throws {621 let outflow = Self.solanaOutflow(transaction.message.review(), owner: owner)622 // the planner's ceiling holds on every cluster623 guard outflow.priorityFee <= SolanaSendPlanner.maximumPriorityFee else { throw WalletError.solana(.priorityFeeTooHigh(lamports: outflow.priorityFee)) }624 guard !network.isTest, MainnetPolicy.unauditedMainnet else { return }625 let limits = MainnetPolicy.solanaLimits626 guard !outflow.blind else { throw WalletError.unauditedLimitUnverifiable("On mainnet this build does not sign a Solana transaction it cannot decode entirely.") }627 guard outflow.other.isEmpty else {628 throw WalletError.unauditedLimitUnverifiable("On mainnet this build only signs plain payments on Solana. This transaction also does: \(outflow.other.joined(separator: "; ")).")629 }630 guard outflow.priorityFee <= limits.feePerTransaction else {631 throw WalletError.exceedsUnauditedLimit(limit: "a priority fee of \(WalletMessages.sol(limits.feePerTransaction)) per transaction")632 }633 guard outflow.createsAccounts <= 1 else { throw WalletError.unauditedLimitUnverifiable("This transaction creates several token accounts.") }634 if outflow.lamports > 0 {635 let price = try await limitUSDPrice(Self.solanaPriceID)636 guard let ceiling = MainnetPolicy.nativeCeiling(usd: limits.nativeUSDPerTransaction, priceUSD: price, decimals: SolanaNetwork.decimals) else {637 throw WalletError.unauditedLimitUnverifiable("The SOL amount cannot be valued, so it cannot be checked against the limit.")638 }639 guard outflow.lamports <= ceiling else {640 throw WalletError.exceedsUnauditedLimit(limit: "\(Int(limits.nativeUSDPerTransaction)) USD of SOL per transaction (\(WalletMessages.sol(ceiling)) at the current price)")641 }642 }643 let tokenLimit = MainnetPolicy.limits.tokenUSDPerTransaction644 for (mint, sent) in outflow.tokens {645 // the built-in list only: a token of the stored profile never brings its own price identifier (QYV-SVC-087)646 guard let builtIn = SolanaToken.builtIn(network).first(where: { $0.mint.base58 == mint }),647 let token = Self.builtInSolanaTokens(network).first(where: { $0.address == mint }), let priceID = token.priceID,648 token.decimals == Int(sent.decimals) else {649 throw WalletError.unauditedLimitUnverifiable("This token has no known price, so its value cannot be checked against the limit of \(Int(tokenLimit)) USD.")650 }651 let price = try await limitUSDPrice(priceID, pricing: builtIn.pegUSD ? .dollarPegged : .twoSources)652 guard let units = Double(BaseUnits.format(UInt256(sent.amount), decimals: token.decimals)), units.isFinite else {653 throw WalletError.unauditedLimitUnverifiable("The token amount cannot be valued.")654 }655 guard units * price <= tokenLimit else { throw WalletError.exceedsUnauditedLimit(limit: "\(Int(tokenLimit)) USD per token transfer") }656 }657 }658659 /// Signs with the Solana key (m/44'/501'/0'/0', SLIP-0010) read from the vault for the duration of the signature,660 /// then checks the result: the signature verifies, the message is byte for byte the one given, the transaction661 /// decodes back to itself. The key derived must be the account the vault vouches for.662 func signSolana(_ transaction: SolanaTransaction, network: SolanaNetwork) async throws -> SolanaTransaction {663 let owner = try solanaAccount(network)664 guard transaction.message.signers == [owner], transaction.message.feePayer == owner else {665 throw WalletError.signingFailed("This wallet's account is not the only signer of the transaction.")666 }667 if let trusted = await trustedPublicData(), trusted.solana != owner.base58 {668 throw WalletError.signingFailed("The account of the profile is not the one the vault holds. Lock and unlock the wallet, then try again.")669 }670 try await enforceUnauditedSolanaLimits(transaction, network: network, owner: owner)671 let signed: SolanaTransaction = try await withSeed { seed in672 var secret = try SolanaKeys.privateSeed(bip39Seed: seed)673 defer { SecureMemory.zero(&secret) }674 guard try SolanaKeys.publicKey(privateSeed: secret) == owner else {675 throw WalletError.signingFailed("The recovery phrase in the vault does not match this wallet's account.")676 }677 var copy = transaction678 try copy.sign(privateSeed: secret)679 return copy680 }681 guard signed.isFullySigned, signed.verifySignatures(), signed.message == transaction.message, signed.id != nil,682 let bytes = try? signed.serialize(), (try? SolanaTransaction.decode(bytes)) == signed else {683 throw WalletError.signingFailed("The signed transaction does not verify.")684 }685 return signed686 }687688 /// Records a signed transaction, then sends it. A send that fails for lack of an answer leaves the transaction689 /// recorded: it may have reached the cluster, and the same bytes are sent again on retry.690 func broadcastSolana(_ signed: SolanaTransaction, network: SolanaNetwork, paymentKey: String, lastValidBlockHeight: UInt64?,691 rpc: SolanaRPC) async throws -> SendResult {692 let kind = ChainKind.solana(network)693 guard let id = signed.id, let bytes = try? signed.serialize() else { throw WalletError.signingFailed("The transaction is not fully signed.") }694 if sentTransactions[id] == nil {695 sentTransactions[id] = SentTransaction(kind: kind, id: id, paymentKey: paymentKey, signed: bytes, lastValidBlockHeight: lastValidBlockHeight,696 expirationMilliseconds: nil)697 }698 do {699 let reported = try await rpc.send(signed)700 guard reported == id else { throw WalletError.broadcastMismatch(local: id, remote: reported) }701 } catch NetworkError.rpc(_, let message) {702 // every endpoint refused it (failed preflight, expired blockhash): it was not broadcast703 sentTransactions[id]?.outcome = .rejected704 throw WalletError.broadcastRejected(message)705 }706 sentTransactions[id]?.outcome = .unknown707 noteBroadcast(kind, id: id)708 return SendResult(chain: ChainRegistry.id(kind), id: id, raw: SolanaBase64.encode(bytes), explorerURL: ChainRegistry.descriptor(kind).explorerTransactionURL(id),709 lastValidBlockHeight: lastValidBlockHeight, expiresAt: nil)710 }711712 func signAndBroadcastSolana(_ review: SendReview, details: SolanaSendDetails) async throws -> SendResult {713 let network = details.network714 let kind = ChainKind.solana(network)715 let owner = try solanaAccount(network)716 guard Self.activeKinds(profile).contains(kind), review.from == owner.base58, details.plan.transaction.message.feePayer == owner else {717 throw WalletError.stalePlan("The review was made for another account or network.")718 }719 let rpc = try await verifiedSolana(network)720 let paymentKey = Self.paymentKey(kind, recipient: review.recipient, asset: review.asset, amount: review.amount)721 // a review is signed once: asking again re-sends the same signed bytes722 if let id = signedReviews[review.id], let sent = sentTransactions[id], let again = try? SolanaTransaction.decode(sent.signed) {723 return try await broadcastSolana(again, network: network, paymentKey: paymentKey, lastValidBlockHeight: sent.lastValidBlockHeight, rpc: rpc)724 }725 try await requireNoPaymentInFlight(paymentKey)726 guard try await rpc.blockHeight() <= details.lastValidBlockHeight else {727 throw WalletError.transactionExpired("its blockhash is no longer valid on \(network.displayName).")728 }729 // simulated again on the state of this moment, before anything is signed730 let simulation = try await rpc.simulate(details.plan.transaction)731 guard simulation.succeeded else {732 throw WalletError.simulationFailed((simulation.error ?? "failed") + (simulation.logs.last.map { " — \($0)" } ?? ""))733 }734 // QYV-SVC-023: the bytes about to be signed still say what the review shows735 try Self.requireSolanaPayment(details.plan.transaction, matches: review, owner: owner)736 // QYV-SVC-022: a test-cluster transaction must not be executable on mainnet-beta737 try await requireNotValidOnMainnet(details.plan.transaction, network: network)738 let signed = try await signSolana(details.plan.transaction, network: network)739 if let id = signed.id { signedReviews[review.id] = id }740 let result = try await broadcastSolana(signed, network: network, paymentKey: paymentKey, lastValidBlockHeight: details.lastValidBlockHeight, rpc: rpc)741 paidRecipients.insert(Self.paidKey(kind, review.recipient))742 return result743 }744745 /// Status of a Solana transaction. One sent in this session is tracked against its blockhash expiry: `.expired`746 /// means it can no longer be executed, decided on the finalized block height.747 func trackSolana(_ id: String, network: SolanaNetwork) async throws -> TransactionStatus {748 guard SolanaRPC.isSignature(id) else { throw WalletError.invalidInput("Not a Solana transaction signature.") }749 let rpc = try await verifiedSolana(network)750 if let sent = sentTransactions[id], let last = sent.lastValidBlockHeight {751 switch try await rpc.track(signature: id, lastValidBlockHeight: last) {752 case .pending: return sent.outcome == .rejected ? .notFound : .pending753 case .expired:754 sentTransactions[id]?.settled = true755 return .expired756 case .failed(let slot, let error):757 sentTransactions[id]?.settled = true758 return .failed(blockHeight: slot, reason: error, fee: nil)759 case .included(let slot, let commitment):760 sentTransactions[id]?.settled = true761 return commitment == .finalized ? .finalized(blockHeight: slot, fee: nil) : .confirmed(blockHeight: slot, confirmations: nil, fee: nil)762 }763 }764 guard let status = try await rpc.signatureStatuses([id])[0] else { return .notFound }765 if let error = status.error { return .failed(blockHeight: status.slot, reason: error, fee: nil) }766 return status.confirmationStatus == .finalized ? .finalized(blockHeight: status.slot, fee: nil)767 : .confirmed(blockHeight: status.slot, confirmations: status.confirmations, fee: nil)768 }769}770