Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/MultiChainSendTests.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0512// Last Modified : 2026-12-0513//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import Testing43import QyvoraMath44import QyvoraCore45import QyvoraBitcoin46import QyvoraEthereum47import QyvoraNetworking48import QyvoraStorage49import QyvoraVault50import QyvoraSolana51import QyvoraTron52@testable import QyvoraWallet5354@Suite(.readsMainnetPolicy) struct MultiChainSendTests {55 static let sol: UInt64 = 1_000_000_00056 static let trx: UInt64 = 1_000_0005758 // MARK: EVM on an L25960 @Test func anL2PaymentThroughTheUniformEntryPoints() async throws {61 let h = try await MultiHarness.wallet(chains: [.ethereum, .base])62 defer { h.cleanup() }63 let owner = MultiHarness.ethereumAddress.lowercased(), recipient = EthereumWalletTests.recipient64 let base = h.backend.evm(.baseSepolia)65 base.balances[owner] = UInt256(2_000_000_000_000_000_000)66 // the GasPriceOracle quotes 8 gwei-units; the wallet reserves a quarter more67 base.rpcResultOverride["eth_call"] = "\"0x\(Hex.encode(UInt256(8_000_000_000).bytes32))\""68 let half = UInt256(500_000_000_000_000_000), gasFee = UInt256(21_000 * 21_000_000_000), l1 = UInt256(10_000_000_000)6970 let review = try await h.service.prepareSend(chain: .baseSepolia, asset: .native, to: recipient, amount: half)71 #expect(review.chain.id == .baseSepolia && !review.isMainnet && !review.unauditedMainnet && review.limits == nil)72 #expect(review.from == MultiHarness.ethereumAddress && review.recipient == recipient && review.amount == half && review.amountSymbol == "ETH")73 #expect(review.fee.maximum == gasFee + l1 && review.fee.expected <= review.fee.maximum && review.fee.symbol == "ETH" && review.fee.decimals == 18)74 #expect(review.fee.lines.map(\.amount) == [gasFee, l1] && review.totalNative == half + gasFee + l1)75 #expect(review.warnings.map(\.id) == ["first-payment"] && review.notes.contains { $0.contains("L1 data fee") })76 guard case .evm(let inner) = review.body else {77 Issue.record("an EVM body is expected")78 return79 }80 #expect(inner.network == .baseSepolia && inner.transaction.chainID == 84_532 && inner.l1DataFee == l1)8182 let result = try await h.service.signAndBroadcast(review)83 // signed for Base Sepolia and sent there; the primary network saw nothing84 let decoded = try SignedEIP1559Transaction.decode(try #require(base.broadcastEthereum.first))85 #expect(decoded.transaction.chainID == 84_532 && decoded.hashHex == result.id && result.chain == .baseSepolia)86 #expect(try decoded.sender().checksummed == MultiHarness.ethereumAddress && h.backend.base.broadcastEthereum.isEmpty)87 #expect(result.explorerURL?.absoluteString == "https://sepolia.basescan.org/tx/\(result.id)")8889 #expect(try await h.service.track(chain: .baseSepolia, id: result.id) == .pending)90 base.receipts[result.id] = "{\"blockNumber\":\"0x4c4b40\",\"status\":\"0x1\",\"gasUsed\":\"0x5208\",\"effectiveGasPrice\":\"0x2540be400\"}"91 #expect(try await h.service.track(chain: .baseSepolia, id: result.id)92 == .confirmed(blockHeight: 5_000_000, confirmations: 1, fee: UInt256(21_000 * 10_000_000_000)))93 base.blockNumber = 5_000_000 + 4_50094 #expect(try await h.service.track(chain: .baseSepolia, id: result.id) == .finalized(blockHeight: 5_000_000, fee: UInt256(21_000 * 10_000_000_000)))95 // paid once: no first-payment warning the second time, on this network only96 let again = try await h.service.prepareSend(chain: .baseSepolia, asset: .native, to: recipient, amount: UInt256(1))97 #expect(!again.warnings.contains { $0.id == "first-payment" })98 // a network that is not active is refused; a token of another network too99 #expect(await walletError { try await h.service.prepareSend(chain: .polygonAmoy, asset: .native, to: recipient, amount: half) } == .chainNotActive("Polygon Amoy"))100 let foreign = ChainToken(chain: .ethereumSepolia, address: MainnetPolicyTests.usdcMainnet, symbol: "X", name: "X", decimals: 6, standard: .erc20)101 #expect(await walletError { try await h.service.prepareSend(chain: .baseSepolia, asset: .token(foreign), to: recipient, amount: half) }102 == .ethereum(.tokenNetworkMismatch))103 }104105 // MARK: Solana106107 static func solanaWallet(lamports: UInt64 = 2 * sol) async throws -> MultiHarness {108 let h = try await MultiHarness.wallet(chains: [.solana])109 h.backend.solana.lamports[MultiHarness.solanaAddress] = lamports110 return h111 }112113 @Test func solanaPaymentSimulatedSignedTrackedAndNeverSignedTwice() async throws {114 let h = try await Self.solanaWallet()115 defer { h.cleanup() }116 let node = h.backend.solana117 let me = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))118 let recipient = solanaStranger()119 let amount = UInt256(500_000_000)120121 let review = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: amount)122 // 5000 lamports per signature, plus 5000 compute units at the floor price of 5000 micro-lamports123 #expect(review.fee.expected == UInt256(5_025) && review.fee.maximum == UInt256(5_025) && review.fee.lines.map(\.amount) == [UInt256(5_000), UInt256(25)])124 #expect(review.totalNative == UInt256(500_005_025) && review.amount == amount && review.amountDecimals == 9 && review.amountSymbol == "SOL")125 #expect(review.from == MultiHarness.solanaAddress && review.recipient == recipient.base58)126 // valid for about a minute: the lifetime of its blockhash, counted from the preparation127 #expect(review.expiresAt == h.clock.now.addingTimeInterval(60))128 // a Solana address has no checksum: the first payment to an address is a critical warning, acknowledged on the review (QYV-APP-020)129 #expect(Set(review.warnings.map(\.id)) == ["solana.new-account", "first-payment"] && review.warnings.filter(\.isCritical).map(\.id) == ["first-payment"])130 guard case .invalidInput? = await walletError({ try await h.service.signAndBroadcast(review, acknowledged: []) }) else {131 Issue.record("signed a first Solana payment without the acknowledgement")132 return133 }134 guard case .solana(let details) = review.body else {135 Issue.record("a Solana body is expected")136 return137 }138 #expect(details.lastValidBlockHeight == 4_150 && details.simulatedUnits == 450 && node.simulations == 1 && node.sent.isEmpty)139 #expect(details.plan.review.instructions.contains(.systemTransfer(from: me, to: recipient, lamports: 500_000_000)))140141 let result = try await h.service.signAndBroadcast(review)142 // simulated again before signing, then sent: one signature, by this wallet's key, over the reviewed message143 #expect(node.simulations == 2 && node.sent.count == 1)144 let sent = try #require(node.sent.first)145 #expect(sent.verifySignatures() && sent.message == details.plan.transaction.message && sent.message.feePayer == me && sent.id == result.id)146 let sentBytes = try sent.serialize()147 #expect(result.chain == .solanaDevnet && result.lastValidBlockHeight == 4_150 && SolanaBase64.decode(result.raw) == sentBytes)148 #expect(result.explorerURL?.absoluteString == "https://explorer.solana.com/tx/\(result.id)?cluster=devnet")149150 // not in a block yet, blockhash still valid: pending, and the same payment is not prepared a second time151 #expect(try await h.service.track(chain: .solanaDevnet, id: result.id) == .pending)152 #expect(await walletError { try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: amount) }153 == .transactionInFlight(id: result.id))154 // another payment is another matter155 _ = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(400_000_000))156 // asking again for the same review re-sends the very same signed bytes: nothing is signed twice157 let resent = try await h.service.signAndBroadcast(review)158 #expect(resent.id == result.id && resent.raw == result.raw && node.sent.count == 2 && node.sent[1] == sent)159160 // confirmed, then final161 node.statuses[result.id] = #"{"slot":5001,"confirmations":3,"err":null,"confirmationStatus":"confirmed"}"#162 #expect(try await h.service.track(chain: .solanaDevnet, id: result.id) == .confirmed(blockHeight: 5_001, confirmations: nil, fee: nil))163 node.statuses[result.id] = #"{"slot":5001,"confirmations":null,"err":null,"confirmationStatus":"finalized"}"#164 #expect(try await h.service.track(chain: .solanaDevnet, id: result.id) == .finalized(blockHeight: 5_001, fee: nil))165 // settled: the same payment may be made again, without the first-payment warning166 node.lamports[recipient.base58] = 500_000_000167 let second = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: amount)168 #expect(second.warnings.isEmpty)169170 // a transaction that failed on chain says so, with the chain's reason171 let failing = try await h.service.signAndBroadcast(second)172 node.statuses[failing.id] = #"{"slot":5002,"confirmations":1,"err":{"InstructionError":[2,"Custom"]},"confirmationStatus":"confirmed"}"#173 guard case .failed(let slot, let reason, _) = try await h.service.track(chain: .solanaDevnet, id: failing.id) else {174 Issue.record("a failed status is expected")175 return176 }177 #expect(slot == 5_002 && reason?.contains("InstructionError") == true)178 #expect(await walletError { try await h.service.track(chain: .solanaDevnet, id: "abc") } == .invalidInput("Not a Solana transaction signature."))179 }180181 @Test func solanaSimulationFailureAndBlockhashExpiry() async throws {182 let h = try await Self.solanaWallet()183 defer { h.cleanup() }184 let node = h.backend.solana185 let recipient = solanaStranger().base58186 node.lamports[recipient] = Self.sol187188 // the node says the transaction would fail: nothing is prepared189 node.simulationError = #"{"InstructionError":[2,{"Custom":1}]}"#190 guard case .simulationFailed(let text)? = await walletError({ try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient, amount: UInt256(1_000)) }) else {191 Issue.record("a simulation failure is expected")192 return193 }194 #expect(text.contains("InstructionError") && WalletError.simulationFailed(text).userMessage.contains("would fail"))195 // it fails at the second simulation, just before signing: nothing is signed, nothing is sent196 node.simulationError = nil197 let review = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient, amount: UInt256(1_000))198 node.simulationError = #"{"InstructionError":[2,{"Custom":1}]}"#199 guard case .simulationFailed? = await walletError({ try await h.service.signAndBroadcast(review) }) else {200 Issue.record("a simulation failure is expected")201 return202 }203 #expect(node.sent.isEmpty)204 node.simulationError = nil205206 // the blockhash expired before the user confirmed: refused before anything is signed207 node.blockHeight = 4_151208 #expect(await walletError { try await h.service.signAndBroadcast(review) }209 == .transactionExpired("its blockhash is no longer valid on Solana Devnet."))210 #expect(node.sent.isEmpty)211212 // sent in time, never included: once the finalized height passes the last valid one it has expired, and only213 // then may the same payment be prepared again214 node.blockHeight = 4_000215 let fresh = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient, amount: UInt256(2_000))216 let sent = try await h.service.signAndBroadcast(fresh)217 #expect(try await h.service.track(chain: .solanaDevnet, id: sent.id) == .pending)218 node.blockHeight = 4_200 // the head is past it, the finalized height is not: still not declared dead219 #expect(try await h.service.track(chain: .solanaDevnet, id: sent.id) == .pending)220 #expect(await walletError { try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient, amount: UInt256(2_000)) }221 == .transactionInFlight(id: sent.id))222 node.finalizedBlockHeight = 4_151223 #expect(try await h.service.track(chain: .solanaDevnet, id: sent.id) == .expired)224 node.lastValidBlockHeight = 4_400225 _ = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient, amount: UInt256(2_000))226227 // the cluster refuses the transaction at broadcast: it was not sent, and the reason is given228 let refused = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient, amount: UInt256(3_000))229 node.sendError = "Blockhash not found"230 #expect(await walletError { try await h.service.signAndBroadcast(refused) } == .broadcastRejected("Blockhash not found"))231 }232233 @Test func solanaTokensRentAndRefusals() async throws {234 let h = try await Self.solanaWallet()235 defer { h.cleanup() }236 let node = h.backend.solana237 let me = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))238 let recipient = solanaStranger()239 node.lamports[recipient.base58] = Self.sol240 let mint = solanaStranger(40)241 node.mints[mint.base58] = .init(decimals: 6)242 node.tokenAccounts = [.init(address: try SolanaAddress.associatedTokenAccount(owner: me, mint: mint, tokenProgram: .token).base58, mint: mint.base58,243 owner: me.base58, amount: 10_000_000)]244 let token = try await h.service.addCustomToken(chain: .solanaDevnet, address: mint.base58, label: "TST")245246 // the recipient has no account for this token: the sender creates it and pays its rent, shown apart from the fee247 let review = try await h.service.prepareSend(chain: .solanaDevnet, asset: .token(token), to: recipient.base58, amount: UInt256(2_500_000))248 guard case .solana(let details) = review.body else {249 Issue.record("a Solana body is expected")250 return251 }252 #expect(review.amountSymbol == "TST" && review.amountDecimals == 6 && review.amount == UInt256(2_500_000))253 #expect(review.warnings.map(\.id).contains("solana.creates-token-account") && details.plan.accountCreationCost == 2_039_280)254 #expect(review.fee.lines.count == 3 && review.fee.lines.last?.amount == UInt256(2_039_280) && review.fee.expected == UInt256(details.plan.fee))255 #expect(review.totalNative == UInt256(details.plan.fee + 2_039_280))256 let instructions = details.plan.review.instructions257 #expect(instructions.contains { if case .createAssociatedTokenAccount = $0 { return true } else { return false } })258 #expect(instructions.contains { if case .tokenTransferChecked(_, _, mint, _, me, 2_500_000, 6) = $0 { return true } else { return false } })259 let result = try await h.service.signAndBroadcast(review)260 #expect(node.sent.last?.id == result.id && node.sent.last?.verifySignatures() == true)261262 // everything, and a note263 let all = try await h.service.prepareSend(chain: .solanaDevnet, asset: .token(token), to: recipient.base58, amount: .zero, options: {264 var o = SendOptions()265 o.sendMax = true266 o.memo = "invoice 42"267 return o268 }())269 #expect(all.amount == UInt256(10_000_000) && all.isSendMax)270 if case .solana(let d) = all.body { #expect(d.plan.review.instructions.contains(.memo("invoice 42"))) }271272 // refusals, each with its reason273 func refusal(_ asset: ChainAsset, to: String, _ amount: UInt64, max: Bool = false) async -> WalletError? {274 var options = SendOptions()275 options.sendMax = max276 return await walletError { try await h.service.prepareSend(chain: .solanaDevnet, asset: asset, to: to, amount: UInt256(amount), options: options) }277 }278 #expect(await refusal(.token(token), to: recipient.base58, 10_000_001) == .solana(.insufficientTokens(required: 10_000_001, available: 10_000_000)))279 #expect(await refusal(.native, to: me.base58, 1) == .solana(.senderIsRecipient))280 #expect(await refusal(.native, to: recipient.base58, 0) == .solana(.zeroAmount))281 // leaving less than the rent-exempt minimum on the account is refused, with what can be sent282 guard case .solana(.senderBelowRentExemption(_, let minimum, let sendable))? = await refusal(.native, to: recipient.base58, 2 * Self.sol - 100_000) else {283 Issue.record("the rent rule is expected")284 return285 }286 #expect(minimum == 890_880 && sendable == 2 * Self.sol - 5_025 - 890_880)287 // a new account must receive at least the minimum288 #expect(await refusal(.native, to: solanaStranger(77).base58, 1_000) == .solana(.recipientBelowRentExemption(minimum: 890_880)))289 // a token account pasted instead of the wallet that owns it290 node.programOwned[solanaStranger(78).base58] = SolanaProgram.token.base58291 #expect(await refusal(.native, to: solanaStranger(78).base58, 1_000_000) == .solana(.recipientIsNotAWallet(owner: SolanaProgram.token)))292 // sending everything empties the account, and says so293 let empty = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: .zero, options: {294 var o = SendOptions()295 o.sendMax = true296 return o297 }())298 #expect(empty.amount == UInt256(2 * Self.sol - 5_025) && empty.warnings.map(\.id).contains("solana.empties-sender"))299300 // a Token-2022 mint that takes a fee on transfers: the recipient would not get the amount shown301 let taxed = solanaStranger(43)302 node.mints[taxed.base58] = .init(decimals: 6, program: .token2022, extensions: ["transferFeeConfig"])303 node.tokenAccounts.append(.init(address: try SolanaAddress.associatedTokenAccount(owner: me, mint: taxed, tokenProgram: .token2022).base58,304 mint: taxed.base58, owner: me.base58, amount: 5_000_000, program: .token2022))305 let taxedToken = try await h.service.addCustomToken(chain: .solanaDevnet, address: taxed.base58)306 #expect(taxedToken.standard == .splToken2022 && taxedToken.note?.contains("transferFeeConfig") == true)307 #expect(await refusal(.token(taxedToken), to: recipient.base58, 1_000) == .solana(.unsupportedToken(reason: "unsupported Token-2022 extension: transferFeeConfig")))308 // a priority fee above the ceiling of 0.01 SOL is refused on every cluster309 var costly = SendOptions()310 costly.solanaComputeUnitPrice = 3_000_000_000311 #expect(await walletError { try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(1_000_000), options: costly) }312 == .solana(.priorityFeeTooHigh(lamports: 15_000_000)))313 }314315 // MARK: TRON316317 static func tronWallet(balance: UInt64 = 50 * trx) async throws -> MultiHarness {318 let h = try await MultiHarness.wallet(chains: [.tron])319 h.backend.tron.balances[MultiHarness.tronHex(MultiHarness.tronAddress)] = balance320 return h321 }322323 @Test func tronPaymentToANewAddressConfirmedByItsReceipt() async throws {324 let h = try await Self.tronWallet()325 defer { h.cleanup() }326 let node = h.backend.tron327 let me = try #require(TronAddress(MultiHarness.tronAddress))328 let recipient = tronStranger()329330 let review = try await h.service.prepareSend(chain: .tronNile, asset: .native, to: recipient.base58, amount: UInt256(10 * Self.trx))331 // an address the chain never saw: 1 TRX of activation plus 0.1 TRX, on top of the amount332 #expect(review.fee.expected == UInt256(1_100_000) && review.fee.maximum == UInt256(1_100_000) && review.totalNative == UInt256(11_100_000))333 #expect(review.fee.lines.map(\.amount) == [UInt256(1_100_000)] && review.amountSymbol == "TRX" && review.amountDecimals == 6)334 #expect(Set(review.warnings.map(\.id)) == ["tron.activates-recipient", "first-payment", "tron.node-checked"])335 #expect(review.warnings.first { $0.id == "tron.node-checked" }?.message.contains("checks it when it is broadcast") == true)336 #expect(review.expiresAt == h.clock.now.addingTimeInterval(120))337 guard case .tron(let details) = review.body else {338 Issue.record("a TRON body is expected")339 return340 }341 // built on the latest irreversible block, not on the head342 #expect(details.plan.transaction.refBlockBytes == Bytes(Endian.be64(node.headNumber - 19)[6..<8]) && details.plan.from == me && details.plan.to == recipient)343 #expect(details.plan.review.action == .trxTransfer(from: me, to: recipient, amountSun: 10 * Self.trx))344345 let result = try await h.service.signAndBroadcast(review)346 let signed = try #require(node.broadcasts.first)347 #expect(node.broadcasts.count == 1 && signed.isSignedByOwner && signed.transaction == details.plan.transaction && signed.txIDHex == result.id)348 #expect(try signed.signers() == [me] && result.raw == signed.hex && result.expiresAt == review.expiresAt)349 #expect(result.explorerURL?.absoluteString == "https://nile.tronscan.org/#/transaction/\(result.id)")350351 // accepted is not confirmed: the receipt decides352 #expect(try await h.service.track(chain: .tronNile, id: result.id) == .notFound)353 node.include(signed, fee: 1_100_000)354 #expect(try await h.service.track(chain: .tronNile, id: result.id) == .confirmed(blockHeight: node.headNumber, confirmations: nil, fee: UInt256(1_100_000)))355 node.solid.insert(result.id)356 #expect(try await h.service.track(chain: .tronNile, id: result.id) == .finalized(blockHeight: node.headNumber, fee: UInt256(1_100_000)))357358 // refused by the node: nothing moved, the reason is shown, and the same signed bytes go out again on retry359 let second = try await h.service.prepareSend(chain: .tronNile, asset: .native, to: recipient.base58, amount: UInt256(2 * Self.trx))360 node.broadcastAnswer = #"{"code":"TAPOS_ERROR","message":"Tapos check error"}"#361 #expect(await walletError { try await h.service.signAndBroadcast(second) } == .broadcastRejected("TAPOS_ERROR: Tapos check error"))362 #expect(node.broadcasts.count == 1)363 node.broadcastAnswer = nil364 let retried = try await h.service.signAndBroadcast(second)365 #expect(node.broadcasts.count == 2 && node.broadcasts[1].txIDHex == retried.id)366367 // past its validity a prepared transaction is refused before anything is signed368 let late = try await h.service.prepareSend(chain: .tronNile, asset: .native, to: recipient.base58, amount: UInt256(3 * Self.trx))369 h.clock.advance(121)370 // the authentication is no longer fresh either, and that is said first371 #expect(await walletError { try await h.service.signAndBroadcast(late) } == .authenticationRequired)372 try await h.service.unlock(password: Harness.password)373 guard case .transactionExpired? = await walletError({ try await h.service.signAndBroadcast(late) }) else {374 Issue.record("an expired transaction must be refused")375 return376 }377 #expect(node.broadcasts.count == 2)378 // refusals of the planner reach the caller as they are379 node.headTimestamp = UInt64(h.clock.now.timeIntervalSince1970 * 1000)380 #expect(await walletError { try await h.service.prepareSend(chain: .tronNile, asset: .native, to: me.base58, amount: UInt256(1)) } == .tron(.recipientIsSender))381 guard case .tron(.insufficientBalance)? = await walletError({ try await h.service.prepareSend(chain: .tronNile, asset: .native, to: recipient.base58, amount: UInt256(900 * Self.trx)) }) else {382 Issue.record("an insufficient balance must be refused")383 return384 }385 // a device whose clock is far from the chain's is told so386 node.headTimestamp -= 3_600_000387 #expect(await walletError { try await h.service.prepareSend(chain: .tronNile, asset: .native, to: recipient.base58, amount: UInt256(1)) } == .tron(.clockSkew))388 }389390 @Test func tronTokenTransferWithEnergyAndTheReturnValueThatMeansNothing() async throws {391 let h = try await Self.tronWallet()392 defer { h.cleanup() }393 let node = h.backend.tron394 let me = try #require(TronAddress(MultiHarness.tronAddress))395 let recipient = tronStranger()396 node.balances[recipient.hex] = 1397 let contract = tronStranger(0x51)398 node.tokens[contract.hex] = .init(decimals: 6, symbol: "TUSD", name: "Test Dollar", balances: [Hex.encode(me.hash): UInt256(80_000_000)])399 let token = try await h.service.addCustomToken(chain: .tronNile, address: contract.base58)400401 let review = try await h.service.prepareSend(chain: .tronNile, asset: .token(token), to: recipient.base58, amount: UInt256(25_000_000))402 guard case .tron(let details) = review.body else {403 Issue.record("a TRON body is expected")404 return405 }406 // 29 650 energy simulated, a quarter of margin, 100 sun per unit: the fee limit; no staked energy, so it is burned407 #expect(details.plan.energyEstimate == 29_650 && details.plan.energyLimit == 37_063 && details.plan.feeLimitSun == 3_706_300)408 #expect(details.plan.transaction.feeLimit == 3_706_300 && details.plan.energyFeeSun == 2_965_000)409 #expect(review.fee.expected == UInt256(details.plan.estimatedFeeSun) && review.fee.maximum == UInt256(details.plan.maximumFeeSun))410 #expect(review.fee.maximum >= UInt256(3_706_300) && review.amountSymbol == "TUSD" && review.amount == UInt256(25_000_000))411 #expect(review.notes.contains { $0.contains("receipt") } && review.notes.contains { $0.contains("burned for energy") })412 #expect(details.plan.review.action == .trc20Transfer(from: me, token: contract, to: recipient, amount: UInt256(25_000_000)))413414 let result = try await h.service.signAndBroadcast(review)415 let signed = try #require(node.broadcasts.first)416 #expect(signed.txIDHex == result.id && signed.isSignedByOwner)417 // the simulated transfer returned nothing (as USDT does) and the transfer is still confirmed: the receipt decides418 node.include(signed, fee: 2_965_000)419 #expect(try await h.service.track(chain: .tronNile, id: result.id) == .confirmed(blockHeight: node.headNumber, confirmations: nil, fee: UInt256(2_965_000)))420 // … and a receipt that says the call ran out of energy is a failure, whatever else is reported421 node.include(signed, receipt: "OUT_OF_ENERGY", contractRet: "OUT_OF_ENERGY", fee: 3_706_300)422 #expect(try await h.service.track(chain: .tronNile, id: result.id) == .failed(blockHeight: node.headNumber, reason: "OUT_OF_ENERGY", fee: UInt256(3_706_300)))423424 // everything425 var max = SendOptions()426 max.sendMax = true427 #expect(try await h.service.prepareSend(chain: .tronNile, asset: .token(token), to: recipient.base58, amount: .zero, options: max).amount == UInt256(80_000_000))428 // refusals429 func refusal(_ amount: UInt64, to: TronAddress = recipient) async -> WalletError? {430 await walletError { try await h.service.prepareSend(chain: .tronNile, asset: .token(token), to: to.base58, amount: UInt256(amount)) }431 }432 #expect(await refusal(80_000_001) == .tron(.insufficientTokenBalance(required: UInt256(80_000_001), available: UInt256(80_000_000))))433 #expect(await refusal(1, to: contract) == .tron(.recipientIsTokenContract(contract)))434 node.tokens[contract.hex]?.revert = "REVERT opcode executed"435 #expect(await refusal(1_000) == .tron(.simulationFailed("REVERT opcode executed")))436 node.tokens[contract.hex]?.revert = nil437 // not enough TRX to pay for the energy with its margin: the call would fail and still burn its fee438 node.balances[me.hex] = 2 * Self.trx439 guard case .tron(.insufficientTRXForFees(let required, let available))? = await refusal(1_000) else {440 Issue.record("the fee reserve is expected")441 return442 }443 #expect(required == 3_706_300 && available == 2 * Self.trx)444 // a transfer that needs a fee limit above 100 TRX is refused on every network445 node.balances[me.hex] = 500 * Self.trx446 node.tokens[contract.hex]?.transferEnergy = 900_000447 #expect(await refusal(1_000) == .tron(.feeLimitTooHigh(requiredSun: 112_500_000, capSun: 100_000_000)))448 var memo = SendOptions()449 memo.memo = "x"450 #expect(await walletError { try await h.service.prepareSend(chain: .tronNile, asset: .token(token), to: recipient.base58, amount: UInt256(1), options: memo) }451 == .invalidInput("A note can only be attached to a TRX payment."))452 }453454 // MARK: Cold mode455456 /// The cold device: a full wallet in cold mode whose transport fails the test at the first request.457 static func coldDevice(chains: [ChainID]) async throws -> MultiHarness {458 let backend = MultiBackend()459 backend.forbidAllRequests = true460 let cold = try await MultiHarness.make(backend: backend, configure: false)461 try await cold.service.setColdMode(true)462 try await cold.service.importWallet(words: Harness.abandon, password: Harness.password)463 try await cold.service.setEnabledChains(chains)464 return cold465 }466467 /// The online companion: a watch-only wallet made from the cold device's package.468 static func companion(of cold: MultiHarness) async throws -> MultiHarness {469 let online = try await MultiHarness.make()470 try await online.service.importWatchOnly(package: try await cold.service.exportWatchOnlyPackage().frames)471 return online472 }473474 /// Since QYV-APP-040 an offline device of an unaudited build reviews a Solana or TRON transaction of a test network475 /// but does not sign it: nothing in the bytes names the network, and offline nothing can check that they are not476 /// valid on the main network. The signature is made by a device that is online (`signer`), which asks the477 /// main-network nodes first. The cold device still makes no request at all.478 @Test func coldSigningOnSolanaAndTronTouchesNoNetwork() async throws {479 let cold = try await Self.coldDevice(chains: [.solana, .tron])480 defer { cold.cleanup() }481 let signer = try await MultiHarness.wallet(chains: [.solana, .tron])482 defer { signer.cleanup() }483 let online = try await Self.companion(of: cold)484 defer { online.cleanup() }485 #expect(await online.service.currentProfile().kind == .watchOnly)486 // the companion shows the chains the cold device shows487 #expect(await online.service.activeChains().map(\.id) == [.solanaDevnet, .tronNile])488 let me = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))489490 // Solana: prepared online by the watch-only wallet, which cannot sign491 let recipient = solanaStranger()492 online.backend.solana.lamports[MultiHarness.solanaAddress] = 2 * Self.sol493 online.backend.solana.lamports[recipient.base58] = Self.sol494 let review = try await online.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(250_000_000))495 #expect(await walletError { try await online.service.signAndBroadcast(review) } == .watchOnly)496 let unsigned = try await online.service.exportUnsigned(review)497 #expect(unsigned.text.hasPrefix("qyvtx1|u|solana-devnet|") && !unsigned.frames.isEmpty)498499 // reviewed on the cold device from the bytes themselves500 let decoded = try await cold.service.reviewColdTransaction(unsigned.frames)501 #expect(decoded.chain.id == .solanaDevnet && !decoded.requiresBlindSigning && decoded.warnings.map(\.id) == ["solana.cross-cluster"] && decoded.warnings[0].isCritical)502 #expect(decoded.signingRefusal?.contains("does not sign it offline") == true && decoded.warnings[0].message.contains("does not sign it here"))503 guard case .unauditedLimitUnverifiable(let offlineRefusal)? = await walletError({ try await cold.service.signColdTransaction(unsigned.frames) }),504 case .unauditedLimitUnverifiable? = await walletError({ try await cold.service.signColdTransaction(unsigned.frames, acknowledged: ["solana.cross-cluster"]) }) else {505 Issue.record("an offline device must not sign a test-network Solana transaction")506 return507 }508 #expect(offlineRefusal == decoded.signingRefusal)509 // the online signer reads the same bytes; its review carries no refusal, and its warning must be acknowledged510 let onlineReview = try await signer.service.reviewColdTransaction(unsigned.frames)511 #expect(onlineReview.signingRefusal == nil && onlineReview.warnings.map(\.id) == ["solana.cross-cluster"] && onlineReview.warnings[0].isCritical)512 #expect(onlineReview.warnings[0].message.contains("asks the main-network nodes"))513 guard case .invalidInput(let unacknowledged)? = await walletError({ try await signer.service.signColdTransaction(unsigned.frames, acknowledged: []) }),514 case .invalidInput? = await walletError({ try await signer.service.signColdTransaction(unsigned.frames, acknowledged: ["unaudited-mainnet"]) }) else {515 Issue.record("a critical warning that was not acknowledged must refuse the signature")516 return517 }518 #expect(unacknowledged.contains("not acknowledged"))519 #expect(decoded.summary.contains("Transfer 0.25 SOL from \(me.base58) to \(recipient.base58)") || decoded.summary.contains { $0.contains(recipient.base58) })520 #expect(decoded.summary.contains { $0.contains("valid for about a minute") } && decoded.summary.contains("Signature fee: 0.000005 SOL"))521 guard case .solana(let instructions) = decoded.body else {522 Issue.record("a Solana body is expected")523 return524 }525 #expect(instructions.instructions.contains(.systemTransfer(from: me, to: recipient, lamports: 250_000_000)))526 let signed = try await signer.service.signColdTransaction(unsigned.frames, acknowledged: ["solana.cross-cluster"])527 #expect(signed.export.text.hasPrefix("qyvtx1|s|solana-devnet|") && SolanaRPC.isSignature(signed.id))528 // a signed envelope is not signed again, an unsigned one is not broadcast529 guard case .invalidPayload? = await walletError({ try await signer.service.signColdTransaction(signed.export.frames) }),530 case .invalidPayload? = await walletError({ try await online.service.broadcastSigned(unsigned.frames) }) else {531 Issue.record("the two steps must not be confused")532 return533 }534 let sent = try await online.service.broadcastSigned(signed.export.frames)535 #expect(sent.id == signed.id && online.backend.solana.sent.count == 1 && online.backend.solana.sent[0].verifySignatures())536 #expect(online.backend.solana.sent[0].message.feePayer == me && online.backend.solana.simulations == 2)537538 // TRON: thirty minutes of validity for the trip, a recipient that is new539 let tronRecipient = tronStranger()540 online.backend.tron.balances[MultiHarness.tronHex(MultiHarness.tronAddress)] = 50 * Self.trx541 var options = SendOptions()542 options.forColdSigning = true543 options.memo = "rent"544 let tronReview = try await online.service.prepareSend(chain: .tronNile, asset: .native, to: tronRecipient.base58, amount: UInt256(5 * Self.trx), options: options)545 #expect(tronReview.expiresAt == online.clock.now.addingTimeInterval(1_800))546 let tronUnsigned = try await online.service.exportUnsigned(tronReview)547 let tronDecoded = try await cold.service.reviewColdTransaction(tronUnsigned.frames)548 #expect(tronDecoded.chain.id == .tronNile && tronDecoded.summary.contains("Send 5 TRX to \(tronRecipient.base58)") && tronDecoded.summary.contains("Note: rent"))549 // what depends on chain state cannot be verified offline, and the review says so550 #expect(tronDecoded.summary.contains { $0.contains("this offline device cannot verify") } && tronDecoded.warnings.map(\.id) == ["tron.memo", "tron.network-not-bound"])551 #expect(tronDecoded.warnings[1].isCritical && tronDecoded.signingRefusal?.contains("TRON transaction does not name its network") == true)552 guard case .unauditedLimitUnverifiable? = await walletError({ try await cold.service.signColdTransaction(tronUnsigned.frames) }),553 case .unauditedLimitUnverifiable? = await walletError({ try await cold.service.signColdTransaction(tronUnsigned.frames, acknowledged: ["tron.network-not-bound"]) }),554 case .invalidInput? = await walletError({ try await signer.service.signColdTransaction(tronUnsigned.frames, acknowledged: []) }) else {555 Issue.record("offline: refused; online: the warning must be acknowledged")556 return557 }558 let tronSigned = try await signer.service.signColdTransaction(tronUnsigned.frames, acknowledged: ["tron.network-not-bound"])559 let tronSent = try await online.service.broadcastSigned(tronSigned.export.frames)560 #expect(tronSent.id == tronSigned.id && online.backend.tron.broadcasts.count == 1 && online.backend.tron.broadcasts[0].isSignedByOwner)561562 // a transaction of someone else's account, a tampered one and an unknown chain are refused on the cold device563 let foreign = try SolanaTransaction(message: SolanaMessage(feePayer: recipient, instructions: [SolanaSystemProgram.transfer(from: recipient, to: me, lamports: 5)],564 recentBlockhash: Bytes(repeating: 7, count: 32)))565 for payload in ["qyvtx1|u|solana-devnet|\(try foreign.base64())", "qyvtx1|u|solana-devnet|AAAA", "qyvtx1|u|tron-nile|zz", "qyvtx1|u|tron-nile|" + String(tronUnsigned.text.split(separator: "|")[3].dropLast(2)),566 "qyvtx1|x|tron-nile|00", "qyvtx1|u|solana-devnet"] {567 guard case .invalidPayload? = await walletError({ try await cold.service.reviewColdTransaction([payload]) }) else {568 Issue.record("\(payload.prefix(40)) must be refused")569 continue570 }571 }572 #expect(await walletError { try await cold.service.reviewColdTransaction(["qyvtx1|u|dogeclassic|00"]) } == .unknownChain("dogeclassic"))573 #expect(await walletError { try await cold.service.reviewColdTransaction(["qyvtx1|u|base-sepolia|00"]) } == .chainNotActive("Base Sepolia"))574575 // blind signing: an instruction of a program the wallet does not know needs an explicit yes576 let unknown = SolanaInstruction(programID: solanaStranger(90), accounts: [SolanaAccountMeta(me, isSigner: true, isWritable: true)], data: [1, 2, 3])577 let blind = try SolanaTransaction(message: SolanaMessage(feePayer: me, instructions: [unknown], recentBlockhash: Bytes(repeating: 7, count: 32)))578 let blindPayload = ["qyvtx1|u|solana-devnet|\(try blind.base64())"]579 let blindReview = try await cold.service.reviewColdTransaction(blindPayload)580 #expect(blindReview.requiresBlindSigning && blindReview.warnings.first?.id == "blind-signing" && blindReview.warnings.first?.isCritical == true)581 #expect(blindReview.signingRefusal != nil)582 guard case .invalidPayload? = await walletError({ try await signer.service.signColdTransaction(blindPayload) }) else {583 Issue.record("blind signing must be asked for")584 return585 }586 // the blind-signing warning is acknowledged by `allowBlindSigning`; the network warning still needs its own587 guard case .invalidInput? = await walletError({ try await signer.service.signColdTransaction(blindPayload, allowBlindSigning: true, acknowledged: []) }) else {588 Issue.record("the network warning must be acknowledged next to the blind-signing consent")589 return590 }591 #expect(SolanaRPC.isSignature(try await signer.service.signColdTransaction(blindPayload, allowBlindSigning: true, acknowledged: ["solana.cross-cluster"]).id))592593 // not one request left the cold device (its transport fails the test at the first one)594 #expect(cold.backend.requests.isEmpty)595 #expect(await cold.service.networkRequestCount() == 0)596 #expect(await cold.service.synchronize().allSatisfy { $0.error == WalletError.offline.userMessage })597 #expect(await walletError { try await cold.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(1)) } == .offline)598 #expect(cold.backend.requests.isEmpty)599 }600601 @Test func coldSigningOfAnL2SaysWhatItCannotVerify() async throws {602 let cold = try await Self.coldDevice(chains: [.ethereum, .base])603 defer { cold.cleanup() }604 let online = try await Self.companion(of: cold)605 defer { online.cleanup() }606 try await online.service.setChainEnabled(.base, enabled: true)607 let base = online.backend.evm(.baseSepolia)608 base.balances[MultiHarness.ethereumAddress.lowercased()] = UInt256(2_000_000_000_000_000_000)609 base.rpcResultOverride["eth_call"] = "\"0x\(Hex.encode(UInt256(8_000_000_000).bytes32))\""610 let review = try await online.service.prepareSend(chain: .baseSepolia, asset: .native, to: EthereumWalletTests.recipient, amount: UInt256(1_000_000))611 let unsigned = try await online.service.exportUnsigned(review)612 let decoded = try await cold.service.reviewColdTransaction(unsigned.frames)613 #expect(decoded.chain.id == .baseSepolia && decoded.summary.first == "Network: Base Sepolia (chain 84532)")614 // the L1 data fee is not in the transaction: the cold device cannot know it, and says so615 #expect(decoded.summary.contains { $0.contains("Not included: the L1 data fee") && $0.contains("offline device cannot compute it") })616 let signed = try await cold.service.signColdTransaction(unsigned.frames)617 let sent = try await online.service.broadcastSigned(signed.export.frames)618 #expect(sent.chain == .baseSepolia && sent.id == signed.id && base.broadcastEthereum.count == 1 && online.backend.base.broadcastEthereum.isEmpty)619 #expect(cold.backend.requests.isEmpty)620 }621622 @Test func theTronGridKeyLivesInTheVaultOnly() async throws {623 let h = try await MultiHarness.wallet(chains: [.tron])624 defer { h.cleanup() }625 let key = "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0"626 try await h.service.setTronAPIKey(key)627 #expect(await h.service.currentProfile().hasTronAPIKey)628 // nowhere outside the vault: not in the profile file, not in any other file of the application629 for file in try FileManager.default.contentsOfDirectory(at: h.directory, includingPropertiesForKeys: nil) where !file.hasDirectoryPath {630 #expect(String(decoding: try Data(contentsOf: file), as: UTF8.self).contains(key) == false, "\(file.lastPathComponent)")631 }632 // it comes back from the vault at unlock, and leaves memory at lock633 let reopened = try await MultiHarness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)634 #expect(await reopened.service.tronAPIKey == nil)635 try await reopened.service.unlock(password: Harness.password)636 let loaded = await reopened.service.tronAPIKey637 #expect(loaded != nil && "\(String(describing: loaded))".contains(key) == false)638 await reopened.service.lock()639 #expect(await reopened.service.tronAPIKey == nil)640 // removing it, and the rules around it641 try await h.service.setTronAPIKey(nil)642 #expect(await h.service.currentProfile().hasTronAPIKey == false)643 h.clock.advance(WalletService.authenticationWindow + 1)644 #expect(await walletError { try await h.service.setTronAPIKey(key) } == .authenticationRequired)645 #expect(await walletError { try await h.service.setChainEndpoints(.default) } == .authenticationRequired)646 try await h.service.unlock(password: Harness.password)647 var endpoints = MultiBackend.endpoints()648 endpoints.tron.fullNodes["nile"] = ["http://tron.example.com"]649 guard case .invalidInput? = await walletError({ try await h.service.setChainEndpoints(endpoints) }) else {650 Issue.record("a plain-http public endpoint must be refused")651 return652 }653 endpoints = MultiBackend.endpoints()654 endpoints.solana.rpc["moonnet"] = ["https://sol.test"]655 #expect(await walletError { try await h.service.setChainEndpoints(endpoints) } == .invalidInput("Unknown network name in the endpoint configuration."))656 try await h.service.resetEndpoints()657 #expect(await h.service.chainEndpoints() == .default)658 }659}660661// MARK: - Mainnet: the gate and the limits, for every chain662663extension MainnetPolicyTests {664 /// An internal build with mainnet switched on and every chain on its main network.665 static func mainnetMultiWallet(chains: [ChainID], prices: [(String, String)]) async throws -> MultiHarness {666 let backend = MultiBackend()667 backend.solana.genesis = SolanaNetwork.mainnetBeta.genesisHash668 backend.tron.genesisID = TronNetwork.mainnet.genesisBlockID669 backend.base.markets = ServiceTests.market(prices)670 let h = try await MultiHarness.make(backend: backend, internalBuildAllowsMainnet: true)671 try await h.service.importWallet(words: Harness.abandon, password: Harness.password)672 #expect(try await h.service.setMainnetOptIn(true))673 try await h.service.setEnabledChains(chains)674 try await h.service.setNetworkMode(.main)675 return h676 }677678 @Test func theNetworkModeNeedsBothConditionsAndMovesEveryChain() async throws {679 Self.reset()680 defer { Self.reset() }681 let chains: [ChainID] = [.bitcoin, .ethereum, .polygon, .solana, .tron]682 // a default build: no main network, whatever is asked683 let plain = try await MultiHarness.wallet(chains: chains)684 defer { plain.cleanup() }685 #expect(await walletError { try await plain.service.setNetworkMode(.main) } == .mainnetDisabled(WalletError.mainnetText))686 #expect(try await plain.service.setMainnetOptIn(true) == false)687 #expect(await walletError { try await plain.service.setNetworkMode(.main) } == .mainnetDisabled(WalletError.mainnetText))688 #expect(await plain.service.activeChains().allSatisfy(\.isTest))689690 // an internal build without the user's opt-in: still nothing691 let h = try await MultiHarness.make(internalBuildAllowsMainnet: true)692 defer { h.cleanup() }693 try await h.service.importWallet(words: Harness.abandon, password: Harness.password)694 try await h.service.setEnabledChains(chains)695 try await h.service.setTestNetwork(.solanaTestnet)696 #expect(await walletError { try await h.service.setNetworkMode(.main) } == .mainnetDisabled(WalletError.mainnetText))697 #expect(await h.service.snapshot().mainnetAvailable)698 #expect(!MainnetPolicy.mainnetEnabled)699700 // both: every chain moves to its main network, with its limits on display701 #expect(try await h.service.setMainnetOptIn(true))702 #expect(await h.service.activeChains().allSatisfy(\.isTest)) // opting in changes no network by itself703 try await h.service.setNetworkMode(.main)704 #expect(await h.service.activeChains().map(\.id) == [.bitcoin, .ethereum, .polygon, .solana, .tron])705 var snapshot = await h.service.snapshot()706 #expect(snapshot.networkMode == .main && snapshot.isMainnet && snapshot.unauditedMainnet && snapshot.profile.bitcoinNetwork == .mainnet)707 #expect(snapshot.profile.ethereumNetwork == .mainnet && snapshot.chains.allSatisfy { $0.limits != nil && $0.data == .notLoaded })708 #expect(snapshot.chain(.bitcoin)?.limits?.native == "At most 0.002 BTC per transaction.")709 #expect(snapshot.chain(.solana)?.limits?.native.contains("150 USD of SOL") == true && snapshot.chain(.solana)?.limits?.fee.contains("0.01 SOL") == true)710 #expect(snapshot.chain(.tron)?.limits?.fee.contains("100 TRX") == true && snapshot.chain(.polygon)?.limits?.native.contains("150 USD of POL") == true)711 #expect(snapshot.chain(.ethereum)?.limits?.native.contains("0.05 ETH") == true && snapshot.chain(.bitcoin)?.limits?.tokens == nil)712713 // back to the test networks without ceremony (the chosen ones); forward again needs a fresh authentication714 try await h.service.setNetworkMode(.test)715 #expect(await h.service.activeChains().map(\.id) == [.bitcoinSignet, .ethereumSepolia, .polygonAmoy, .solanaTestnet, .tronNile])716 h.clock.advance(WalletService.authenticationWindow + 1)717 #expect(await walletError { try await h.service.setNetworkMode(.main) } == .authenticationRequired)718 try await h.service.unlock(password: Harness.password)719 try await h.service.setNetworkMode(.main)720721 // a restart of the same build keeps the mode; a build without the declaration falls back to test networks722 let same = try await MultiHarness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false, internalBuildAllowsMainnet: true)723 #expect(await same.service.activeChains().allSatisfy { !$0.isTest })724 Self.reset()725 let demoted = try await MultiHarness.make(backend: h.backend, clock: h.clock, directory: h.directory, configure: false)726 snapshot = await demoted.service.snapshot()727 #expect(snapshot.networkMode == .test && !snapshot.isMainnet && snapshot.chains.map(\.id) == [.bitcoinSignet, .ethereumSepolia, .polygonAmoy, .solanaTestnet, .tronNile])728 #expect(await walletError { try await demoted.service.synchronize(chain: .solana) } == .mainnetDisabled(WalletError.mainnetText))729730 // switching the opt-in off moves everything back at once731 MainnetPolicy.configure(internalBuildAllowsMainnet: true, userOptedIn: true)732 #expect(try await same.service.setMainnetOptIn(false) == false)733 #expect(await same.service.snapshot().networkMode == .test)734 #expect(await same.service.activeChains().allSatisfy(\.isTest))735 #expect(h.backend.requests.isEmpty)736 }737738 @Test func solanaLimitsApplyWhenPreparingAndWhenSigning() async throws {739 Self.reset()740 defer { Self.reset() }741 let h = try await Self.mainnetMultiWallet(chains: [.solana], prices: [("solana", "100"), ("usd-coin", "1")])742 defer { h.cleanup() }743 let node = h.backend.solana744 let me = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))745 let recipient = solanaStranger()746 node.lamports[me.base58] = 100 * MultiChainSendTests.sol747 node.lamports[recipient.base58] = MultiChainSendTests.sol748 try await h.service.refreshMarket()749 func send(_ lamports: UInt64) async throws -> SendReview {750 try await h.service.prepareSend(chain: .solana, asset: .native, to: recipient.base58, amount: UInt256(lamports))751 }752 // 150 USD at 100 USD per SOL: 1.5 SOL753 let limit = WalletError.exceedsUnauditedLimit(limit: "150 USD of SOL per transaction (1.5 SOL at the current price)")754 #expect(await walletError { try await send(1_500_000_001) } == limit)755 let review = try await send(1_500_000_000)756 #expect(review.isMainnet && review.unauditedMainnet && review.limits != nil && review.hasCriticalWarning)757 #expect(review.warnings.contains { $0.id == "unaudited-mainnet" } && review.fee.expectedFiat != nil && !review.fee.fiatIsReference)758759 // the price moved between the review and the signature: the limit is applied again, nothing is signed760 h.backend.base.markets = ServiceTests.market([("solana", "200"), ("usd-coin", "1")])761 try await h.service.refreshMarket()762 #expect(await walletError { try await h.service.signAndBroadcast(review) }763 == .exceedsUnauditedLimit(limit: "150 USD of SOL per transaction (0.75 SOL at the current price)"))764 #expect(node.sent.isEmpty)765 h.backend.base.markets = ServiceTests.market([("solana", "100"), ("usd-coin", "1")])766 try await h.service.refreshMarket()767 _ = try await h.service.signAndBroadcast(review)768 #expect(node.sent.count == 1)769770 // tokens: USDC under 150 USD; a token without price cannot be sent at all771 let usdc = try #require(await h.service.knownSolanaTokens(.mainnetBeta).first { $0.symbol == "USDC" })772 let mint = try #require(SolanaPublicKey(base58: usdc.address))773 node.mints[usdc.address] = .init(decimals: 6)774 node.tokenAccounts = [.init(address: try SolanaAddress.associatedTokenAccount(owner: me, mint: mint, tokenProgram: .token).base58, mint: usdc.address,775 owner: me.base58, amount: 900_000_000)]776 #expect(await walletError { try await h.service.prepareSend(chain: .solana, asset: .token(usdc), to: recipient.base58, amount: UInt256(150_000_001)) }777 == .exceedsUnauditedLimit(limit: "150 USD per token transfer"))778 _ = try await h.service.prepareSend(chain: .solana, asset: .token(usdc), to: recipient.base58, amount: UInt256(150_000_000))779 let unknownMint = solanaStranger(44)780 node.mints[unknownMint.base58] = .init(decimals: 6)781 node.tokenAccounts.append(.init(address: try SolanaAddress.associatedTokenAccount(owner: me, mint: unknownMint, tokenProgram: .token).base58,782 mint: unknownMint.base58, owner: me.base58, amount: 5_000))783 let unpriced = try await h.service.addCustomToken(chain: .solana, address: unknownMint.base58)784 guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.prepareSend(chain: .solana, asset: .token(unpriced), to: recipient.base58, amount: UInt256(1)) }) else {785 Issue.record("a token without price must be refused on mainnet")786 return787 }788789 // without a fresh price of SOL nothing is sent: no price, no transaction790 h.backend.base.markets = "[]"791 h.clock.advance(WalletService.quoteFreshness + 1)792 node.lastValidBlockHeight = 9_000793 try await h.service.unlock(password: Harness.password)794 guard case .unauditedLimitUnverifiable(let text)? = await walletError({ try await send(1_000) }) else {795 Issue.record("no price, no transaction")796 return797 }798 #expect(text.contains("No fresh price"))799 // the cold device has no price either: a main-network Solana payment cannot be cold-signed by an unaudited build800 let blockhash = Bytes(repeating: 7, count: 32)801 let payment = try SolanaTransaction(message: SolanaMessage(feePayer: me, instructions: [802 SolanaComputeBudget.setComputeUnitLimit(5_000), SolanaComputeBudget.setComputeUnitPrice(microLamports: 5_000),803 SolanaSystemProgram.transfer(from: me, to: recipient, lamports: 1_000),804 ], recentBlockhash: blockhash))805 try await h.service.setColdMode(true)806 guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.signColdTransaction(["qyvtx1|u|solana|\(try payment.base64())"]) }) else {807 Issue.record("no price on the cold device, no signature")808 return809 }810 // and what is not a plain payment is refused on mainnet whatever is allowed811 let unknown = SolanaInstruction(programID: solanaStranger(90), accounts: [SolanaAccountMeta(me, isSigner: true, isWritable: true)], data: [9])812 let blind = try SolanaTransaction(message: SolanaMessage(feePayer: me, instructions: [unknown], recentBlockhash: blockhash))813 guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.signColdTransaction(["qyvtx1|u|solana|\(try blind.base64())"], allowBlindSigning: true) }) else {814 Issue.record("no blind signing on an unaudited mainnet")815 return816 }817 }818819 @Test func tronLimitsApplyWhenPreparingAndWhenSigning() async throws {820 Self.reset()821 defer { Self.reset() }822 let h = try await Self.mainnetMultiWallet(chains: [.tron], prices: [("tron", "0.25"), ("tether", "1")])823 defer { h.cleanup() }824 let node = h.backend.tron825 let me = try #require(TronAddress(MultiHarness.tronAddress))826 let recipient = tronStranger()827 node.balances[me.hex] = 10_000 * MultiChainSendTests.trx828 node.balances[recipient.hex] = 1829 try await h.service.refreshMarket()830 func send(_ sun: UInt64) async throws -> SendReview {831 try await h.service.prepareSend(chain: .tron, asset: .native, to: recipient.base58, amount: UInt256(sun))832 }833 // 150 USD at 0.25 USD per TRX: 600 TRX834 #expect(await walletError { try await send(600_000_001) } == .tron(.amountAboveLimit(limitSun: 600_000_000)))835 #expect(WalletError.tron(.amountAboveLimit(limitSun: 600_000_000)).userMessage == "Above the limit of this unaudited build: 600 TRX per transaction.")836 let review = try await send(600_000_000)837 #expect(review.unauditedMainnet && review.warnings.contains { $0.id == "unaudited-mainnet" && $0.isCritical })838839 // the price moved before the signature: refused, nothing is broadcast840 h.backend.base.markets = ServiceTests.market([("tron", "0.5"), ("tether", "1")])841 try await h.service.refreshMarket()842 #expect(await walletError { try await h.service.signAndBroadcast(review) }843 == .exceedsUnauditedLimit(limit: "150 USD of TRX per transaction (300 TRX at the current price)"))844 #expect(node.broadcasts.isEmpty)845 h.backend.base.markets = ServiceTests.market([("tron", "0.25"), ("tether", "1")])846 try await h.service.refreshMarket()847 _ = try await h.service.signAndBroadcast(review)848 #expect(node.broadcasts.count == 1)849850 // USDT (built in): 150 USD per transfer; the fee limit never above 100 TRX851 let usdt = try #require(await h.service.knownTronTokens(.mainnet).first { $0.symbol == "USDT" })852 let contract = try #require(TronAddress(usdt.address))853 node.tokens[contract.hex] = .init(decimals: 6, symbol: "USDT", name: "Tether USD", balances: [Hex.encode(me.hash): UInt256(900_000_000)])854 #expect(await walletError { try await h.service.prepareSend(chain: .tron, asset: .token(usdt), to: recipient.base58, amount: UInt256(150_000_001)) }855 == .exceedsUnauditedLimit(limit: "150 USD per token transfer"))856 let tokenReview = try await h.service.prepareSend(chain: .tron, asset: .token(usdt), to: recipient.base58, amount: UInt256(150_000_000))857 #expect(tokenReview.fee.maximum <= UInt256(100 * MultiChainSendTests.trx))858 node.tokens[contract.hex]?.transferEnergy = 900_000859 #expect(await walletError { try await h.service.prepareSend(chain: .tron, asset: .token(usdt), to: recipient.base58, amount: UInt256(1_000)) }860 == .tron(.feeLimitTooHigh(requiredSun: 112_500_000, capSun: 100_000_000)))861 node.tokens[contract.hex]?.transferEnergy = 29_650862 // a token without price863 let other = tronStranger(0x51)864 node.tokens[other.hex] = .init(decimals: 6, symbol: "ODD", name: "Odd", balances: [Hex.encode(me.hash): UInt256(5_000)])865 let unpriced = try await h.service.addCustomToken(chain: .tron, address: other.base58)866 guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.prepareSend(chain: .tron, asset: .token(unpriced), to: recipient.base58, amount: UInt256(1)) }) else {867 Issue.record("a token without price must be refused on mainnet")868 return869 }870 // what is not a payment is not signed on mainnet: an approval built elsewhere and brought to the device871 let reference = try #require(TronBlockReference(number: node.headNumber, id: Endian.be64(node.headNumber) + Bytes(repeating: 0xab, count: 24), timestamp: node.headTimestamp))872 let approval = try TronTransaction(refBlockBytes: reference.refBlockBytes, refBlockHash: reference.refBlockHash, expiration: node.headTimestamp + 60_000,873 timestamp: node.headTimestamp, feeLimit: 5_000_000,874 contract: .triggerSmartContract(TronTriggerSmartContract(owner: me, contract: contract, data: ERC20.approve(spender: recipient.evm, amount: UInt256(5)))))875 guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.signColdTransaction(["qyvtx1|u|tron|\(Hex.encode(approval.rawData))"]) }) else {876 Issue.record("an approval must be refused on an unaudited mainnet")877 return878 }879880 // no fresh price of TRX: no transaction881 h.backend.base.markets = "[]"882 h.clock.advance(WalletService.quoteFreshness + 1)883 node.headTimestamp = UInt64(h.clock.now.timeIntervalSince1970 * 1000)884 try await h.service.unlock(password: Harness.password)885 guard case .unauditedLimitUnverifiable? = await walletError({ try await send(1_000_000) }) else {886 Issue.record("no price, no transaction")887 return888 }889 }890}891892// MARK: - Live, read-only893894/// Opt-in: `QYVORA_LIVE=1 swift test --filter MultiChainLiveTests`. Synchronizes a watch-only wallet (public data of895/// the published test phrase "abandon … about") on five test networks through the built-in endpoints, and prints896/// what was read. Read-only requests about public chain data: no key, no signature, no broadcast.897@Suite(.enabled(if: ProcessInfo.processInfo.environment["QYVORA_LIVE"] == "1"), .serialized, .readsMainnetPolicy)898struct MultiChainLiveTests {899 @Test func aWatchOnlyWalletOnFiveTestNetworks() async throws {900 // public account data, derived offline901 let offline = try await MultiHarness.make(configure: false)902 defer { offline.cleanup() }903 try await offline.service.setColdMode(true)904 try await offline.service.importWallet(words: Harness.abandon, password: Harness.password)905 let package = try await offline.service.exportWatchOnlyPackage()906907 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("qy-live-\(UUID().uuidString)")908 defer { try? FileManager.default.removeItem(at: directory) }909 let store = try FileStore(root: directory)910 let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting))911 let service = try WalletService(vault: vault, fileStore: store, transport: URLSessionTransport(timeout: 30))912 try await service.importWatchOnly(package: package.frames)913 try await service.setEnabledChains([.bitcoin, .ethereum, .base, .solana, .tron])914 let started = Date()915 let results = await service.synchronize()916 print("LIVE multi-chain watch-only synchronization (\(String(format: "%.1f", Date().timeIntervalSince(started))) s, \(await service.networkRequestCount()) requests):")917 for chain in await service.chainSnapshots() {918 let outcome = results.first { $0.chain == chain.id }919 guard let data = chain.data.value else {920 print("LIVE \(chain.chain.displayName): FAILED — \(outcome?.error ?? chain.syncError ?? "no data")")921 continue922 }923 let balance = BaseUnits.format(data.native.total, decimals: data.native.decimals)924 let history = data.history.value.map { "\($0.count) history entries" } ?? "history unavailable (\(data.historyUnavailableReason ?? "?"))"925 print("LIVE \(chain.chain.displayName): height \(data.height), \(balance) \(data.native.symbol), \(data.tokens.count) listed + \(data.detectedTokens.count) detected tokens, \(history), key exposed: \(data.exposure.publicKeyExposed.map(String.init) ?? "not measured")")926 for note in data.notes { print("LIVE note: \(note)") }927 #expect(data.height > 1_000 && !data.isFromPreviousSession)928 }929 #expect(results.count == 5)930 #expect(results.filter(\.succeeded).count >= 4, "at most one public endpoint may be down")931 }932}933