Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraWallet/WalletService+Cold.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 QyvoraBitcoin45import QyvoraEthereum46import QyvoraNetworking47import QyvoraSolana48import QyvoraTron4950// Cold signing on every chain: the online device (possibly watch-only) prepares a transaction and shows it as QR51// frames; the cold device, which never touches the network, decodes the bytes itself, shows what they do, signs, and52// shows the signed transaction; the online device broadcasts it.53//54// Bitcoin travels as a PSBT and an EVM transaction as its 0x02 payload, exactly as in QYVORA 1.0. Solana and TRON55// travel in a small text envelope that names the chain: "qyvtx1|u|<chain id>|<payload>" (unsigned) and56// "qyvtx1|s|<chain id>|<payload>" (signed); the payload is base64 on Solana and hexadecimal on TRON.5758extension WalletService {59 static let coldEnvelope = "qyvtx1"6061 private enum ColdPayload {62 case psbt63 case evm64 case envelope(signed: Bool, kind: ChainKind, payload: String)65 }6667 private func classify(_ input: [String]) throws -> ColdPayload {68 let text = try QRExport.text(from: input)69 if text.hasPrefix(Self.coldEnvelope + "|") {70 let parts = text.split(separator: "|", omittingEmptySubsequences: false).map(String.init)71 guard parts.count == 4, parts[1] == "u" || parts[1] == "s", parts[3].utf8.count <= 40_000 else {72 throw WalletError.invalidPayload("This transaction envelope is not one QYVORA wrote.")73 }74 let kind = try activeKind(ChainID(parts[2]))75 return .envelope(signed: parts[1] == "s", kind: kind, payload: parts[3])76 }77 return text.hasPrefix("0x") ? .evm : .psbt78 }7980 /// The unsigned transaction of a review as text and QR frames, for a cold device. No secret, no network.81 ///82 /// Bitcoin: a PSBT. EVM: the 0x02 payload. Solana and TRON: the QYVORA envelope. Prepare TRON payments with83 /// `SendOptions.forColdSigning` (thirty minutes of validity); a Solana transaction is valid for about a minute84 /// whatever is done — its blockhash expires — so the three steps must follow each other without delay.85 public func exportUnsigned(_ review: SendReview) async throws(WalletError) -> QRExport {86 try await run {87 switch review.body {88 case .bitcoin(let plan):89 guard Self.isPrimaryUTXO(plan.network) else {90 throw WalletError.featureUnavailable("Cold signing is not available for \(plan.network.displayName) yet: sign on this device.")91 }92 return try await exportPSBT(plan)93 case .evm(let inner): return try await exportUnsignedEthereum(inner)94 case .solana(let details):95 let payload = try details.plan.transaction.base64()96 return try QRExport.make(text: "\(Self.coldEnvelope)|u|\(review.chain.id.rawValue)|\(payload)")97 case .tron(let details):98 return try QRExport.make(text: "\(Self.coldEnvelope)|u|\(review.chain.id.rawValue)|\(Hex.encode(details.plan.transaction.rawData))")99 }100 }101 }102103 private func decodeSolana(_ payload: String) throws -> SolanaTransaction {104 guard let bytes = SolanaBase64.decode(payload), let tx = try? SolanaTransaction.decode(bytes), (try? tx.serialize()) == bytes else {105 throw WalletError.invalidPayload("This is not a Solana transaction, or its encoding is not canonical.")106 }107 return tx108 }109110 private func coldSolanaReview(_ tx: SolanaTransaction, network: SolanaNetwork) throws -> ColdTransactionReview {111 let kind = ChainKind.solana(network)112 let owner = try solanaAccount(network)113 let decoded = tx.message.review()114 guard decoded.feePayer == owner, decoded.signers == [owner] else {115 throw WalletError.invalidPayload("This transaction is not paid and signed by this wallet's Solana account alone.")116 }117 let outflow = Self.solanaOutflow(decoded, owner: owner)118 var warnings = [SendWarning]()119 if decoded.requiresBlindSigning || outflow.blind {120 warnings.append(SendWarning(id: "blind-signing", message: "Blind signing: part of this transaction cannot be decoded by QYVORA (an unknown program, or accounts taken from a lookup table). Sign only if you fully trust its source.", isCritical: true))121 }122 if !outflow.other.isEmpty {123 warnings.append(SendWarning(id: "solana.not-a-payment", message: "This transaction does more than a payment. Read every line.", isCritical: true))124 }125 if !network.isTest, MainnetPolicy.unauditedMainnet { warnings.append(SendWarning(id: "unaudited-mainnet", message: WalletError.unauditedText, isCritical: true)) }126 if network.isTest {127 // QYV-SVC-022, QYV-APP-040: the online device checks this before it signs; an offline device cannot128 warnings.append(SendWarning(id: "solana.cross-cluster", message: "A Solana transaction names no network and this account is the same key on every Solana network: if the blockhash below is a main-network blockhash, these bytes move real funds on the main network, whatever the label \"\(network.displayName)\" says. " + Self.networkBindingSentence(offline: gate.isOffline), isCritical: true))129 }130 var summary = ["Network: \(network.displayName)", "Account: \(owner.base58)"]131 summary += decoded.instructions.map(\.summary)132 summary.append("Signature fee: \(WalletMessages.sol(decoded.signatureFee))")133 summary.append(decoded.priorityFee.map { "Priority fee: \(WalletMessages.sol($0))" } ?? "Priority fee: cannot be computed from this transaction")134 if outflow.createsAccounts > 0 {135 summary.append("This creates a token account for the recipient. The SOL it locks (rent) depends on chain state: this offline device cannot verify the amount; the online device showed it when the transaction was prepared.")136 }137 summary.append("Recent blockhash: \(decoded.recentBlockhash). The transaction is valid for about a minute after it was prepared: sign and return it without delay.")138 summary += warnings.map { "Warning: \($0.message)" }139 // the tokens of the wallet's list among the mints the transaction names: the review can then give their symbol140 var known = [ChainToken]()141 for instruction in decoded.instructions {142 guard case .tokenTransferChecked(_, _, let mint, _, _, _, let decimals) = instruction,143 let token = knownSolanaTokens(network).first(where: { $0.address == mint.base58 }), !known.contains(token) else { continue }144 // the instruction states the decimals and the token program checks them: a list that disagrees is not used145 guard token.decimals == Int(decimals) else { continue }146 known.append(token)147 }148 return ColdTransactionReview(chain: ChainRegistry.descriptor(kind), summary: summary, warnings: warnings,149 requiresBlindSigning: decoded.requiresBlindSigning || outflow.blind, body: .solana(decoded), knownTokens: known,150 signingRefusal: Self.networkBindingRefusal(isTest: network.isTest, offline: gate.isOffline, chain: "Solana"))151 }152153 private func decodeTron(_ payload: String) throws -> TronTransaction {154 guard let bytes = Hex.decode(payload), bytes.count <= TronTransaction.maximumRawDataBytes, let tx = try? TronTransaction.decode(rawData: bytes),155 tx.rawData == bytes else {156 throw WalletError.invalidPayload("This is not a TRON transaction, or its encoding is not canonical.")157 }158 return tx159 }160161 private func coldTronReview(_ tx: TronTransaction, network: TronNetwork) throws -> ColdTransactionReview {162 let kind = ChainKind.tron(network)163 let owner = try tronAccount(network)164 let decoded = TronTransactionReview(tx)165 if let declared = decoded.owner {166 guard declared == owner else { throw WalletError.invalidPayload("This transaction is not sent from this wallet's TRON account.") }167 }168 var warnings = [SendWarning]()169 for w in decoded.warnings {170 switch w {171 case .blindSigning:172 warnings.append(SendWarning(id: "blind-signing", message: "Blind signing: QYVORA cannot decode this contract. Sign only if you fully trust its source.", isCritical: true))173 case .unlimitedApproval:174 warnings.append(SendWarning(id: "tron.unlimited-approval", message: "This approval lets the spender move an unlimited amount of the token.", isCritical: true))175 case .nonOwnerPermission:176 warnings.append(SendWarning(id: "tron.non-owner-permission", message: "The transaction asks for another permission than the owner's.", isCritical: true))177 case .valueAttachedToCall:178 warnings.append(SendWarning(id: "tron.value-attached", message: "TRX is attached to a contract call.", isCritical: true))179 case .memo: warnings.append(SendWarning(id: "tron.memo", message: "The transaction carries a public note.", isCritical: false))180 case .notSignedByOwner: break181 }182 }183 if !network.isTest, MainnetPolicy.unauditedMainnet { warnings.append(SendWarning(id: "unaudited-mainnet", message: WalletError.unauditedText, isCritical: true)) }184 if network.isTest {185 // the bytes do not say which TRON network they are for, and an offline device cannot look the reference block up186 warnings.append(SendWarning(id: "tron.network-not-bound", message: "A TRON transaction does not name its network. This one is presented as \(network.displayName); its signature would also be valid on TRON mainnet, for the same account and with real funds, if its reference block existed there. " + Self.networkBindingSentence(offline: gate.isOffline), isCritical: true))187 }188 var summary = ["Network: \(network.displayName)", "Account: \(owner.base58)"]189 var knownTokens = [ChainToken]()190 switch decoded.action {191 case .trxTransfer(_, let to, let amountSun): summary.append("Send \(WalletMessages.trx(amountSun)) to \(to.base58)")192 case .trc20Transfer(_, let token, let to, let amount):193 let known = knownTronTokens(network).first { $0.address == token.base58 }194 if let known { knownTokens = [known] }195 summary.append(known.map { "Send \(BaseUnits.format(amount, decimals: $0.decimals)) \($0.symbol) to \(to.base58)" } ?? "Token transfer of \(amount) base units to \(to.base58)")196 summary.append("Token contract: \(token.base58)" + (known == nil ? " (not in this wallet's token list)" : ""))197 case .trc20Approve(_, let token, let spender, let amount):198 if let known = knownTronTokens(network).first(where: { $0.address == token.base58 }) { knownTokens = [known] }199 summary.append(amount.isZero ? "Revoke the allowance of \(spender.base58)" : "Allow \(spender.base58) to spend \(ERC20.isUnlimited(amount) ? "an UNLIMITED amount" : "\(amount) base units")")200 summary.append("Token contract: \(token.base58)")201 case .contractCall(_, let contract, let callValueSun, let data, _, _):202 summary.append("Contract call to \(contract.base58) with \(WalletMessages.trx(callValueSun))")203 summary.append("Call data (\(data.count) bytes): \(Hex.encode(Bytes(data.prefix(200))))")204 case .unknownContract(let type, let typeName, _, let value):205 summary.append("Contract of type \(typeName ?? String(type)) that QYVORA cannot decode (\(value.count) bytes)")206 }207 if let memo = decoded.memoText { summary.append("Note: \(memo)") }208 if decoded.feeLimitSun > 0 {209 summary.append("Fee limit: \(WalletMessages.trx(decoded.feeLimitSun)). This is the most the call can burn; what it will really burn (energy, bandwidth) depends on chain state that this offline device cannot verify.")210 } else {211 summary.append("Network fee: bandwidth, and the activation of the recipient's address if it is new, depend on chain state that this offline device cannot verify. The online device showed them when the transaction was prepared.")212 }213 summary.append("Valid until \(decoded.expirationDate.formatted(date: .abbreviated, time: .standard)).")214 summary += warnings.map { "Warning: \($0.message)" }215 return ColdTransactionReview(chain: ChainRegistry.descriptor(kind), summary: summary, warnings: warnings, requiresBlindSigning: decoded.requiresBlindSigning,216 body: .tron(decoded), knownTokens: knownTokens,217 signingRefusal: Self.networkBindingRefusal(isTest: network.isTest, offline: gate.isOffline, chain: "TRON"))218 }219220 /// The key under which a cold-signed Solana transaction is remembered while it can still be executed.221 /// A plain payment of SOL (one System transfer from the owner, no token) takes the key `prepareSend` computes for222 /// the same recipient and amount, so that preparing that payment again while the first is in flight is refused223 /// (`transactionInFlight`, QYV-SVC-025). Anything else keeps a key of its own: a token transfer names the224 /// recipient's token account, not the recipient, and is not matched (still open in QYV-SVC-025).225 static func coldSolanaPaymentKey(_ tx: SolanaTransaction, network: SolanaNetwork, owner: SolanaPublicKey) -> String {226 let decoded = tx.message.review()227 let outflow = solanaOutflow(decoded, owner: owner)228 var transfers = [(SolanaPublicKey, UInt64)]()229 for instruction in decoded.instructions {230 if case .systemTransfer(let from, let to, let lamports) = instruction, from == owner { transfers.append((to, lamports)) }231 }232 guard transfers.count == 1, outflow.tokens.isEmpty, outflow.other.isEmpty, !outflow.blind, outflow.lamports == transfers[0].1 else { return "cold|\(tx.id ?? "")" }233 return paymentKey(.solana(network), recipient: transfers[0].0.base58, asset: .native, amount: UInt256(transfers[0].1))234 }235236 // MARK: Network binding of Solana and TRON (QYV-APP-040, QYV-SVC-022, QYV-SVC-040)237238 /// What a cold review says about the one thing its bytes do not state: the network.239 static func networkBindingSentence(offline: Bool) -> String {240 if offline {241 return MainnetPolicy.auditCompleted242 ? "This offline device cannot check it: sign only a transaction prepared by a device and an endpoint you trust."243 : "This offline device cannot check it, so this unaudited build does not sign it here: a transaction labelled as a test network could otherwise pass the mainnet switch and the per-transaction limits. Sign it on a device that is online, which asks the main-network nodes first."244 }245 return "Before signing, this device asks the main-network nodes whether they would accept it, and signs nothing if they would or if they do not answer."246 }247248 /// Why a test-network Solana or TRON transaction is not signed on this device, or nil when it can be.249 ///250 /// Root cause (QYV-APP-040): nothing in the signed bytes names the network and the account key is the same on251 /// every network, so the label of the envelope ("tron-nile", "solana-devnet") is the only thing that says "test".252 /// A payload built by a compromised companion with a main-network reference block or blockhash, labelled as a253 /// test network, is valid on the main network: signed here, it would move real funds past the mainnet switch and254 /// the limits. An online device asks the main-network nodes (`requireNotValidOnMainnet`,255 /// `requireNotValidOnTronMainnet`); an offline device cannot. While the build is unaudited — while the switch and256 /// the limits are what stands between a defect and real funds — an offline device therefore refuses.257 static func networkBindingRefusal(isTest: Bool, offline: Bool, chain: String) -> String? {258 guard isTest, offline, !MainnetPolicy.auditCompleted else { return nil }259 return "A \(chain) transaction does not name its network, and this offline device cannot check that this one is not valid on the main network. This unaudited build does not sign it offline. Turn cold mode off on a device you trust to sign it there (it asks the main-network nodes first), or sign \(chain) payments on the online device."260 }261262 private func evmColdReview(_ inner: ColdEthereumReview) -> ColdTransactionReview {263 let warnings = inner.warnings.map { w -> SendWarning in264 let critical = w == .blindSigning || w == .unlimitedApproval || w == .unauditedMainnet || w == .unknownTokenContract265 return SendWarning(id: w == .blindSigning ? "blind-signing" : (w == .unauditedMainnet ? "unaudited-mainnet" : "evm.cold"), message: w.message, isCritical: critical)266 }267 return ColdTransactionReview(chain: ChainRegistry.descriptor(.evm(inner.network)), summary: inner.summary, warnings: warnings,268 requiresBlindSigning: inner.warnings.contains(.blindSigning), body: .evm(inner))269 }270271 private func psbtColdReview(_ inner: PSBTReview) -> ColdTransactionReview {272 ColdTransactionReview(chain: ChainRegistry.descriptor(.utxo(inner.network)), summary: inner.summary,273 warnings: inner.warnings.map { SendWarning(id: "btc.psbt", message: $0, isCritical: false) }, requiresBlindSigning: false,274 body: .bitcoin(inner))275 }276277 /// Decodes and reviews an unsigned transaction on the cold device (text or QR frames), whatever its chain.278 /// **No secret, no network.** The chain must be active on this device (same chain enabled, same network mode).279 ///280 /// Everything shown is decoded on this device from the bytes that will be signed. What depends on chain state281 /// cannot be verified offline and the summary says so: the L1 data fee of Base and OP Mainnet, the rent of a new282 /// Solana token account, the energy and bandwidth a TRON transaction burns.283 public func reviewColdTransaction(_ input: [String]) async throws(WalletError) -> ColdTransactionReview {284 try await run {285 switch try classify(input) {286 case .psbt: return psbtColdReview(try await reviewPSBT(input))287 case .evm: return evmColdReview(try await reviewColdEthereumPayload(input))288 case .envelope(let signed, let kind, let payload):289 guard !signed else { throw WalletError.invalidPayload("This transaction is already signed: broadcast it from the online device.") }290 switch kind {291 case .solana(let network): return try coldSolanaReview(try decodeSolana(payload), network: network)292 case .tron(let network): return try coldTronReview(try decodeTron(payload), network: network)293 default: throw WalletError.invalidPayload("This transaction envelope is not one QYVORA wrote.")294 }295 }296 }297 }298299 /// Signs an unsigned transaction on the cold device. **Needs an unlocked vault (full wallet) and a fresh300 /// authentication. No network.** Returns the signed transaction as text and QR frames for the online device.301 ///302 /// A transaction that cannot be decoded entirely is refused unless `allowBlindSigning`; on a main network of an303 /// unaudited build it is refused whatever is passed, and so is any transaction whose value cannot be checked304 /// against the limits — on Solana and TRON that needs a fresh price, which an offline device does not have:305 /// main-network Solana and TRON payments cannot be cold-signed by an unaudited build.306 ///307 /// `acceptUnverifiedAmounts` concerns a PSBT only, with the meaning and the refusals of `signPSBT`: when308 /// `PSBTReview.inputAmountsVerified` is false the fee shown is the PSBT's word, and signing is refused unless the309 /// user confirmed that separately — and always refused on a main network of an unaudited build. It changes310 /// nothing on the other chains.311 ///312 /// `acknowledged` holds the identifiers of the critical warnings of the review (`reviewColdTransaction`) that the313 /// user confirmed having read, one by one; a critical warning that is not in it refuses the signature314 /// (`invalidInput`). The blind-signing warning is acknowledged by `allowBlindSigning` and needs no entry.315 public func signColdTransaction(_ input: [String], allowBlindSigning: Bool = false, acceptUnverifiedAmounts: Bool = false,316 acknowledged: Set<String>) async throws(WalletError) -> ColdSignedTransaction {317 let review = try await reviewColdTransaction(input)318 if let refusal = review.signingRefusal { throw WalletError.unauditedLimitUnverifiable(refusal) }319 try Self.requireAcknowledged(review.warnings.filter { $0.id != "blind-signing" }, acknowledged)320 return try await signColdTransaction(input, allowBlindSigning: allowBlindSigning, acceptUnverifiedAmounts: acceptUnverifiedAmounts)321 }322323 /// The signature itself, without the acknowledgement rule. Internal: the application reaches it only through324 /// `signColdTransaction(_:allowBlindSigning:acceptUnverifiedAmounts:acknowledged:)`.325 func signColdTransaction(_ input: [String], allowBlindSigning: Bool = false,326 acceptUnverifiedAmounts: Bool = false) async throws(WalletError) -> ColdSignedTransaction {327 try await run {328 switch try classify(input) {329 case .psbt:330 let signed = try await signPSBT(input, acceptUnverifiedAmounts: acceptUnverifiedAmounts)331 return ColdSignedTransaction(review: psbtColdReview(signed.review), id: signed.review.isFullySigned ? signed.review.txid : "", export: signed.export)332 case .evm:333 let signed = try await signColdEthereumPayload(input, allowBlindSigning: allowBlindSigning)334 return ColdSignedTransaction(review: evmColdReview(signed.review), id: signed.hash, export: signed.export)335 case .envelope(let alreadySigned, let kind, let payload):336 guard !alreadySigned else { throw WalletError.invalidPayload("This transaction is already signed: broadcast it from the online device.") }337 let chain = ChainRegistry.id(kind).rawValue338 switch kind {339 case .solana(let network):340 let tx = try decodeSolana(payload)341 let review = try coldSolanaReview(tx, network: network)342 // QYV-APP-040: the network is the one thing the bytes do not say343 if let refusal = review.signingRefusal { throw WalletError.unauditedLimitUnverifiable(refusal) }344 if network.isTest, !gate.isOffline { try await requireNotValidOnMainnet(tx, network: network) }345 if review.requiresBlindSigning, !allowBlindSigning {346 throw WalletError.invalidPayload("Part of this transaction cannot be decoded. Blind signing must be allowed explicitly.")347 }348 let signed = try await signSolana(tx, network: network)349 guard let id = signed.id else { throw WalletError.signingFailed("The transaction is not fully signed.") }350 return ColdSignedTransaction(review: review, id: id, export: try QRExport.make(text: "\(Self.coldEnvelope)|s|\(chain)|\(try signed.base64())"))351 case .tron(let network):352 let tx = try decodeTron(payload)353 let review = try coldTronReview(tx, network: network)354 if let refusal = review.signingRefusal { throw WalletError.unauditedLimitUnverifiable(refusal) }355 if network.isTest, !gate.isOffline { try await requireNotValidOnTronMainnet(tx, network: network) }356 if review.requiresBlindSigning, !allowBlindSigning {357 throw WalletError.invalidPayload("This contract cannot be decoded. Blind signing must be allowed explicitly.")358 }359 let signed = try await signTron(tx, network: network, allowBlindSigning: allowBlindSigning && review.requiresBlindSigning)360 return ColdSignedTransaction(review: review, id: signed.txIDHex, export: try QRExport.make(text: "\(Self.coldEnvelope)|s|\(chain)|\(signed.hex)"))361 default: throw WalletError.invalidPayload("This transaction envelope is not one QYVORA wrote.")362 }363 }364 }365 }366367 /// Broadcasts a transaction signed by the cold device (text or QR frames) from the online device. **Network.**368 ///369 /// The signature must verify and be this wallet's account's, the chain must be active, and the limits of an370 /// unaudited build are applied again here. Solana: the transaction is simulated first. TRON: an expired371 /// transaction gives `transactionExpired`, a refusal by the node `broadcastRejected`.372 public func broadcastSigned(_ input: [String]) async throws(WalletError) -> SendResult {373 try await run {374 switch try classify(input) {375 case .psbt:376 let result = try await finalizeAndBroadcastPSBT(input)377 let descriptor = ChainRegistry.descriptor(.utxo(profile.bitcoinNetwork))378 return SendResult(chain: descriptor.id, id: result.txid, raw: result.rawHex, explorerURL: descriptor.explorerTransactionURL(result.txid),379 lastValidBlockHeight: nil, expiresAt: nil)380 case .evm:381 let text = try QRExport.text(from: input)382 var network = profile.ethereumNetwork383 if let raw = Hex.decode(String(text.dropFirst(2))), let signed = try? SignedEIP1559Transaction.decode(raw) {384 network = try coldNetwork(chainID: signed.transaction.chainID)385 }386 let result = try await broadcastSignedEthereum(input)387 let descriptor = ChainRegistry.descriptor(.evm(network))388 return SendResult(chain: descriptor.id, id: result.hash, raw: result.rawHex, explorerURL: descriptor.explorerTransactionURL(result.hash),389 lastValidBlockHeight: nil, expiresAt: nil)390 case .envelope(let signed, let kind, let payload):391 guard signed else { throw WalletError.invalidPayload("This transaction is not signed yet: sign it on the cold device first.") }392 switch kind {393 case .solana(let network):394 let tx = try decodeSolana(payload)395 let owner = try solanaAccount(network)396 guard tx.isFullySigned, tx.verifySignatures(), tx.message.feePayer == owner, tx.message.signers == [owner] else {397 throw WalletError.invalidPayload("The signature does not verify, or the transaction is not this wallet's.")398 }399 try await enforceUnauditedSolanaLimits(tx, network: network, owner: owner)400 // QYV-SVC-022: the signed bytes of a test-cluster transaction are not handed to any endpoint401 // (simulation included) when mainnet-beta would execute them402 try await requireNotValidOnMainnet(tx, network: network)403 let rpc = try await verifiedSolana(network)404 let simulation = try await rpc.simulate(tx)405 guard simulation.succeeded else {406 throw WalletError.simulationFailed((simulation.error ?? "failed") + (simulation.logs.last.map { " — \($0)" } ?? ""))407 }408 // the expiry of its blockhash is not written in a transaction: 150 blocks from now is an upper bound409 let bound = try await rpc.blockHeight().addingReportingOverflow(150).partialValue410 return try await broadcastSolana(tx, network: network, paymentKey: Self.coldSolanaPaymentKey(tx, network: network, owner: owner),411 lastValidBlockHeight: bound, rpc: rpc)412 case .tron(let network):413 guard let bytes = Hex.decode(payload), bytes.count <= TronTransaction.maximumRawDataBytes + 512,414 let signedTx = try? SignedTronTransaction.decode(bytes), signedTx.serialized == bytes else {415 throw WalletError.invalidPayload("This is not a signed TRON transaction, or its encoding is not canonical.")416 }417 let owner = try tronAccount(network)418 guard signedTx.isSignedByOwner, signedTx.transaction.owner == owner else {419 throw WalletError.invalidPayload("The signature does not verify, or the transaction is not this wallet's.")420 }421 try await enforceTronLimits(signedTx.transaction, network: network, maximumFeeSun: nil)422 let client = try await verifiedTron(network)423 return try await broadcastTron(signedTx, network: network, paymentKey: "cold|\(signedTx.txIDHex)", client: client)424 default: throw WalletError.invalidPayload("This transaction envelope is not one QYVORA wrote.")425 }426 }427 }428 }429}430