Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/EthereumTests.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//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 QyvoraEthereum46import QyvoraNetworking47import QyvoraVault48@testable import QyvoraWallet4950@Suite(.readsMainnetPolicy) struct EthereumWalletTests {51 static let owner = Harness.abandonEthereumAddress.lowercased()52 static let recipient = "0x70997970C51812dc3A010C7d01b50e0d17dc79C8"53 static let usdc = "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"54 static let spender = "0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad"55 static let oneEther = UInt256(1_000_000_000_000_000_000)56 static let gwei = UInt256(1_000_000_000)5758 static func hash(_ n: UInt8) -> String { "0x" + String(repeating: String(format: "%02x", n), count: 32) }5960 /// Two ether, nonce 3, and a USDC contract holding 5 USDC for the account.61 static func funded() async throws -> Harness {62 let h = try await Harness.abandonWallet()63 h.backend.balances[owner] = oneEther + oneEther64 h.backend.latestNonce[owner] = 365 var token = FakeBackend.TokenContract(symbol: "USDC", name: "USD Coin", decimals: UInt256(6))66 token.balances[owner] = UInt256(5_000_000)67 h.backend.tokens[usdc.lowercased()] = token68 return h69 }7071 static func nativeItem(hash: String, from: String, to: String, value: String, method: String? = nil, status: String = "ok", time: String = "2026-11-01T10:00:00.000000Z") -> String {72 "{\"hash\":\"\(hash)\",\"from\":{\"hash\":\"\(from)\"},\"to\":{\"hash\":\"\(to)\"},\"value\":\"\(value)\",\"fee\":{\"type\":\"actual\",\"value\":\"21000000000000\"},\"status\":\"\(status)\",\"result\":\"success\",\"timestamp\":\"\(time)\",\"block_number\":4999000,\"method\":\(method.map { "\"\($0)\"" } ?? "null"),\"raw_input\":\"0x\"}"73 }7475 @Test func syncReadsBalancesTokensHistoryAndApprovals() async throws {76 let h = try await Self.funded()77 defer { h.cleanup() }78 let backend = h.backend79 let token = try await h.service.addCustomToken(address: Self.usdc)80 #expect(token.symbol == "USDC" && token.name == "USD Coin" && token.decimals == 6 && token.custom && token.network == .sepolia)8182 // indexer hints: a spam token whose indexer metadata lies, one with absurd decimals, one with no balance83 let spam = "0x" + String(repeating: "a1", count: 20), absurd = "0x" + String(repeating: "b2", count: 20), empty = "0x" + String(repeating: "c3", count: 20)84 var spamToken = FakeBackend.TokenContract(symbol: "FREE-MONEY", name: "Visit evil.example", decimals: UInt256(18))85 spamToken.balances[Self.owner] = UInt256(777)86 backend.tokens[spam] = spamToken87 var absurdToken = FakeBackend.TokenContract(symbol: "ABS", name: "Absurd", decimals: UInt256(77))88 absurdToken.balances[Self.owner] = UInt256(1)89 backend.tokens[absurd] = absurdToken90 backend.tokens[empty] = FakeBackend.TokenContract(symbol: "NIL", name: "Nothing", decimals: UInt256(18))91 func holding(_ a: String, _ symbol: String, _ decimals: String) -> String {92 "{\"token\":{\"address_hash\":\"\(a)\",\"symbol\":\"\(symbol)\",\"name\":\"\(symbol)\",\"decimals\":\"\(decimals)\",\"type\":\"ERC-20\"},\"token_id\":null,\"value\":\"999999999\"}"93 }94 backend.indexerTokens = "{\"items\":[\(holding(spam, "USDT", "6")),\(holding(absurd, "ABS", "18")),\(holding(empty, "NIL", "18")),\(holding(Self.usdc, "USDC", "6")),\(holding("0xnot-an-address", "X", "18"))],\"next_page_params\":null}"9596 // history: one incoming payment, one outgoing, two approvals, one token transfer97 let spender2 = "0x" + String(repeating: "d4", count: 20)98 backend.indexerTransactions = "{\"items\":[" + [99 Self.nativeItem(hash: Self.hash(1), from: Self.recipient, to: Harness.abandonEthereumAddress, value: "1000000000000000000", time: "2026-11-01T10:00:00.000000Z"),100 Self.nativeItem(hash: Self.hash(2), from: Harness.abandonEthereumAddress, to: Self.recipient, value: "500000000000000000", time: "2026-11-02T10:00:00.000000Z"),101 Self.nativeItem(hash: Self.hash(3), from: Harness.abandonEthereumAddress, to: Self.usdc, value: "0", method: "approve", time: "2026-11-03T10:00:00.000000Z"),102 Self.nativeItem(hash: Self.hash(4), from: Harness.abandonEthereumAddress, to: Self.usdc, value: "0", method: "approve", time: "2026-11-04T10:00:00.000000Z"),103 Self.nativeItem(hash: Self.hash(9), from: Self.recipient, to: Self.spender, value: "5", time: "2026-11-05T10:00:00.000000Z"),104 "{\"hash\":17,\"from\":null}",105 ].joined(separator: ",") + "],\"next_page_params\":null}"106 backend.indexerTokenTransfers = "{\"items\":[{\"transaction_hash\":\"\(Self.hash(5))\",\"from\":{\"hash\":\"\(Self.recipient)\"},\"to\":{\"hash\":\"\(Harness.abandonEthereumAddress)\"},\"total\":{\"decimals\":\"18\",\"value\":\"5000000\"},\"token\":{\"address_hash\":\"\(Self.usdc)\",\"symbol\":\"FAKE\",\"decimals\":\"18\",\"name\":\"x\",\"type\":\"ERC-20\"},\"timestamp\":\"2026-10-30T10:00:00.000000Z\",\"block_number\":4998000,\"method\":\"transfer\",\"type\":\"token_transfer\"}],\"next_page_params\":null}"107 let ownerAddress = try #require(EthereumAddress(Self.owner)), spenderAddress = try #require(EthereumAddress(Self.spender))108 let spender2Address = try #require(EthereumAddress(spender2))109 func approveTx(_ spender: EthereumAddress, _ amount: UInt256) -> String {110 "{\"hash\":\"0x\",\"from\":\"\(Self.owner)\",\"to\":\"\(Self.usdc.lowercased())\",\"input\":\"0x\(Hex.encode(ERC20.approve(spender: spender, amount: amount)))\",\"value\":\"0x0\"}"111 }112 backend.transactionsByHash[Self.hash(3)] = approveTx(spenderAddress, .max)113 backend.transactionsByHash[Self.hash(4)] = approveTx(spender2Address, UInt256(100))114 backend.tokens[Self.usdc.lowercased()]?.allowances["\(Self.owner)|\(Self.spender)"] = .max115 // spender2 was approved once but its allowance is back to zero: not reported116117 let snapshot = try await h.service.syncEthereum()118 #expect(snapshot.network == .sepolia && snapshot.address == ownerAddress && snapshot.blockNumber == 5_000_000)119 #expect(snapshot.balance == Self.oneEther + Self.oneEther)120 #expect(snapshot.latestNonce == 3 && snapshot.pendingNonce == 3 && !snapshot.hasPendingTransaction)121 #expect(snapshot.tokens == [TokenBalance(token: token, balance: .available(UInt256(5_000_000)))])122123 // quarantine: detected tokens are separate, and described by the chain, not by the indexer124 #expect(snapshot.detectedTokens.count == 1)125 let detected = try #require(snapshot.detectedTokens.first)126 #expect(detected.token.address == EthereumAddress(spam) && detected.token.symbol == "FREE-MONEY" && detected.token.decimals == 18)127 #expect(detected.balance == .available(UInt256(777)))128 #expect(await h.service.currentProfile().customTokens == [token])129130 let history = try #require(snapshot.history.value)131 #expect(history.count == 5)132 #expect(history.map(\.hash) == [Self.hash(4), Self.hash(3), Self.hash(2), Self.hash(1), Self.hash(5)])133 #expect(history[0].kind == .approval(token: Self.usdc) && history[0].direction == .sent)134 #expect(history[2].kind == .ether && history[2].direction == .sent && history[2].counterparty == Self.recipient)135 #expect(history[2].amount == UInt256(500_000_000_000_000_000) && history[2].fee == UInt256(21_000_000_000_000) && history[2].succeeded)136 #expect(history[3].direction == .received && history[3].fee == nil && history[3].counterparty == Self.recipient)137 #expect(history[3].time == ISO8601DateFormatter().date(from: "2026-11-01T10:00:00Z"))138 // the token transfer is labelled from the wallet's verified list, not from the indexer's claims139 #expect(history[4].kind == .token(address: Self.usdc, symbol: "USDC", decimals: 6, verified: true))140 #expect(history[4].direction == .received && history[4].amount == UInt256(5_000_000))141142 let approvals = try #require(snapshot.approvals.value)143 #expect(approvals.count == 1)144 #expect(approvals[0].token == token && approvals[0].spender == spenderAddress && approvals[0].isUnlimited && approvals[0].allowance == .max)145146 // accepting a detected token moves it to the list; hiding removes it from the next synchronization147 try await h.service.acceptDetectedToken(detected.token)148 #expect(await h.service.latestEthereumSnapshot()?.detectedTokens.isEmpty == true)149 #expect(await h.service.latestEthereumSnapshot()?.tokens.count == 2)150 #expect(await h.service.currentProfile().customTokens.count == 2)151 try await h.service.setTokenHidden(true, token: detected.token)152 let second = try await h.service.syncEthereum()153 #expect(second.tokens.map(\.token) == [token] && second.detectedTokens.isEmpty)154 try await h.service.removeCustomToken(detected.token)155 #expect(await h.service.currentProfile().customTokens == [token])156157 // without the indexer: balances still come from the node, history and approvals say why they are missing158 backend.indexerStatus = 503159 let third = try await h.service.syncEthereum()160 #expect(third.balance == Self.oneEther + Self.oneEther && third.tokens.count == 1)161 guard case .unavailable(let reason) = third.history, case .unavailable = third.approvals else {162 Issue.record("history should be unavailable")163 return164 }165 #expect(reason.contains("503"))166 try await h.service.setEndpoints(FakeBackend.endpoints.with { $0.ethereumIndexer = [:] })167 guard case .unavailable(let none) = try await h.service.syncEthereum().history else {168 Issue.record("history should be unavailable")169 return170 }171 #expect(none.contains("No indexer"))172 }173174 @Test func customTokenValidation() async throws {175 let h = try await Self.funded()176 defer { h.cleanup() }177 #expect(await walletError { try await h.service.addCustomToken(address: "0x1234") } == .ethereum(.invalidAddress))178 #expect(await walletError { try await h.service.addCustomToken(address: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7239") } == .ethereum(.invalidAddress))179 // an address without code180 #expect(await walletError { try await h.service.addCustomToken(address: Self.recipient) } == .ethereum(.tokenContractMissing))181 // decimals above 36182 let big = "0x" + String(repeating: "e5", count: 20)183 h.backend.tokens[big] = FakeBackend.TokenContract(symbol: "BIG", name: "Big", decimals: UInt256(37))184 guard case .untrustedResponse? = await walletError({ try await h.service.addCustomToken(address: big) }) else {185 Issue.record("expected untrustedResponse")186 return187 }188 h.backend.tokens[big]?.decimals = .max189 guard case .untrustedResponse? = await walletError({ try await h.service.addCustomToken(address: big) }) else {190 Issue.record("expected untrustedResponse")191 return192 }193 // control characters and an over-long symbol are cleaned194 h.backend.tokens[big] = FakeBackend.TokenContract(symbol: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", name: "", decimals: UInt256(36))195 let token = try await h.service.addCustomToken(address: big)196 #expect(token.symbol == "ABCDEFGHIJKLMNOP" && token.decimals == 36 && token.name == token.symbol)197 #expect(await h.service.currentProfile().customTokens.count == 1)198 // adding it again changes nothing199 _ = try await h.service.addCustomToken(address: big)200 #expect(await h.service.currentProfile().customTokens.count == 1)201 }202203 @Test func wrongChainAndHostileRPCAnswers() async throws {204 let h = try await Self.funded()205 defer { h.cleanup() }206 h.backend.chainID = 1 // a mainnet node behind the Sepolia URL207 guard case .wrongChain(let text)? = await walletError({ try await h.service.syncEthereum() }) else {208 Issue.record("expected wrongChain")209 return210 }211 #expect(text.contains("11155111"))212 #expect(await h.service.latestEthereumSnapshot() == nil)213 #expect(h.backend.requests == ["POST rpc.test"])214 guard case .wrongChain? = await walletError({ try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: UInt256(1)) }) else {215 Issue.record("expected wrongChain")216 return217 }218 h.backend.chainID = 11_155_111219220 let hostile: [(String, String)] = [221 ("eth_getBalance", "\"0x" + String(repeating: "f", count: 70) + "\""),222 ("eth_getBalance", "12345"),223 ("eth_getBalance", "\"-0x5\""),224 ("eth_getBalance", "null"),225 ("eth_getBalance", "{\"balance\":\"0x1\"}"),226 ("eth_getTransactionCount", "\"0x" + String(repeating: "f", count: 20) + "\""),227 ("eth_getTransactionCount", "\"three\""),228 ("eth_blockNumber", "[]"),229 ("eth_chainId", "\"0xaa36a7 \""),230 ]231 for (method, answer) in hostile {232 let fresh = try await Self.funded()233 defer { fresh.cleanup() }234 fresh.backend.rpcResultOverride[method] = answer235 let error = await walletError({ try await fresh.service.syncEthereum() })236 switch error {237 case .untrustedResponse?, .network?, .wrongChain?: break238 default: Issue.record("\(method) = \(answer): unexpected outcome \(String(describing: error))")239 }240 #expect(await fresh.service.latestEthereumSnapshot() == nil)241 #expect(fresh.backend.broadcastEthereum.isEmpty)242 }243 // a pending nonce below the latest one is impossible244 h.backend.pendingNonce[Self.owner] = 1245 guard case .untrustedResponse? = await walletError({ try await h.service.syncEthereum() }) else {246 Issue.record("expected untrustedResponse")247 return248 }249 h.backend.pendingNonce[Self.owner] = nil250251 // absurd fee figures never produce a review252 for (method, answer) in [("eth_getBlockByNumber", "{\"baseFeePerGas\":\"0x56bc75e2d63100000\"}"), ("eth_getBlockByNumber", "{\"number\":\"0x1\"}"),253 ("eth_getBlockByNumber", "null"), ("eth_maxPriorityFeePerGas", "\"0x56bc75e2d63100000\""),254 ("eth_getCode", "\"0xzz\""), ("eth_getCode", "7")] {255 h.backend.rpcResultOverride = [method: answer]256 let error = await walletError({ try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: UInt256(1_000)) })257 switch error {258 case .untrustedResponse?, .network?, .ethereum(.feeOutOfRange)?: break259 default: Issue.record("\(method) = \(answer): unexpected outcome \(String(describing: error))")260 }261 }262 // a token balance that is not one ABI word is reported as unavailable, not as zero263 h.backend.rpcResultOverride = [:]264 let token = try await h.service.addCustomToken(address: Self.usdc)265 h.backend.rpcResultOverride["eth_call"] = "\"0x01\""266 let snapshot = try await h.service.syncEthereum()267 guard case .unavailable? = snapshot.tokens.first(where: { $0.token == token })?.balance else {268 Issue.record("the token balance should be unavailable")269 return270 }271 let valuation = await h.service.portfolioValuation()272 #expect(!valuation.lines.contains { $0.symbol == "USDC" })273 }274275 @Test func sendEtherReviewSignBroadcast() async throws {276 let h = try await Self.funded()277 defer { h.cleanup() }278 let amount = UInt256(250_000_000_000_000_000)279 let review = try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: amount)280 let tx = review.transaction281 #expect(tx.chainID == 11_155_111 && tx.nonce == 3 && tx.gasLimit == 21_000 && tx.data.isEmpty && tx.accessList.isEmpty)282 #expect(tx.to == EthereumAddress(Self.recipient) && tx.value == amount)283 // maxFee = 2 × base + tip284 #expect(tx.maxPriorityFeePerGas == Self.gwei)285 #expect(tx.maxFeePerGas == UInt256(21_000_000_000))286 #expect(review.baseFee == UInt256(10_000_000_000))287 #expect(review.maximumFee == UInt256(21_000 * 21_000_000_000))288 #expect(review.maximumTotalCost == review.maximumFee + amount)289 // the only warning: this account never paid this recipient (QYV-APP-010)290 #expect(review.call == .etherTransfer && review.asset == .ether && review.amount == amount && review.warnings == [.firstPaymentToRecipient])291 #expect(review.from.checksummed == Harness.abandonEthereumAddress && review.nonce == 3 && review.gasLimit == 21_000)292293 // fee tiers294 let slow = try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: amount, feeTier: .slow)295 let fast = try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: amount, feeTier: .fast)296 #expect(slow.transaction.maxPriorityFeePerGas == UInt256(500_000_000) && slow.transaction.maxFeePerGas == UInt256(20_500_000_000))297 #expect(fast.transaction.maxPriorityFeePerGas == UInt256(2_000_000_000) && fast.transaction.maxFeePerGas == UInt256(22_000_000_000))298299 await h.service.lock()300 #expect(await walletError { try await h.service.signAndBroadcastEthereum(review) } == .vaultLocked)301 #expect(h.backend.broadcastEthereum.isEmpty)302 try await h.service.unlock(password: Harness.password)303 let result = try await h.service.signAndBroadcastEthereum(review)304 #expect(result.nonce == 3)305 let raw = try #require(h.backend.broadcastEthereum.first)306 #expect("0x" + Hex.encode(raw) == result.rawHex)307 // independent check of what reached the network308 let decoded = try SignedEIP1559Transaction.decode(raw)309 #expect(decoded.transaction == tx)310 #expect(try decoded.sender().checksummed == Harness.abandonEthereumAddress)311 #expect(decoded.hashHex == result.hash)312313 // tracking314 #expect(try await h.service.trackEthereumTransaction(hash: result.hash) == .pending)315 h.backend.receipts[result.hash] = "{\"blockNumber\":\"0x4c4b41\",\"status\":\"0x1\",\"gasUsed\":\"0x5208\",\"effectiveGasPrice\":\"0x2540be400\"}"316 #expect(try await h.service.trackEthereumTransaction(hash: result.hash) == .confirmed(blockNumber: 5_000_001, gasUsed: 21_000, feePaid: UInt256(210_000_000_000_000)))317 h.backend.receipts[result.hash] = "{\"blockNumber\":\"0x4c4b41\",\"status\":\"0x0\",\"gasUsed\":\"0x5208\"}"318 #expect(try await h.service.trackEthereumTransaction(hash: result.hash) == .failed(blockNumber: 5_000_001, gasUsed: 21_000, feePaid: nil))319 guard case .invalidInput? = await walletError({ try await h.service.trackEthereumTransaction(hash: "0x1234") }) else {320 Issue.record("expected invalidInput")321 return322 }323324 // the endpoint must report the hash computed locally325 h.backend.ethereumBroadcastAnswer = Self.hash(0xaa)326 #expect(await walletError { try await h.service.signAndBroadcastEthereum(review) } == .broadcastMismatch(local: result.hash, remote: Self.hash(0xaa)))327 }328329 @Test func sendEtherRefusalRules() async throws {330 let h = try await Self.funded()331 defer { h.cleanup() }332 let service = h.service333 let amount = UInt256(1_000_000_000_000_000)334 func refusal(_ to: String, _ value: UInt256 = amount, sendMax: Bool = false, replace: Bool = false, allow: Bool = false) async -> WalletError? {335 await walletError { try await service.prepareEthereumSend(asset: .ether, to: to, amount: value, sendMax: sendMax, replacePending: replace, allowContractRecipient: allow) }336 }337 // EIP-55338 #expect(await refusal("0x70997970C51812dc3A010C7d01b50e0d17dc79c8") == .ethereum(.invalidAddress))339 #expect(await refusal("70997970C51812dc3A010C7d01b50e0d17dc79C8") == .ethereum(.invalidAddress))340 #expect(await refusal("0x70997970C51812dc3A010C7d01b50e0d17dc79") == .ethereum(.invalidAddress))341 #expect(await refusal("0x0000000000000000000000000000000000000000") == .ethereum(.zeroAddress))342 // nothing was asked to the network for a refused address343 #expect(h.backend.requests.isEmpty)344 let lower = try await service.prepareEthereumSend(asset: .ether, to: Self.recipient.lowercased(), amount: amount)345 #expect(lower.warnings.contains(.recipientWithoutChecksum))346 // amounts347 #expect(await refusal(Self.recipient, .zero) == .ethereum(.zeroAmount))348 #expect(await refusal(Self.recipient, Self.oneEther + Self.oneEther + UInt256(1))349 == .ethereum(.insufficientBalance(available: Self.oneEther + Self.oneEther, required: Self.oneEther + Self.oneEther + UInt256(1))))350 // the whole balance cannot be sent without leaving the fee351 guard case .ethereum(.insufficientBalance)? = await refusal(Self.recipient, Self.oneEther + Self.oneEther) else {352 Issue.record("expected insufficientBalance")353 return354 }355 let max = try await service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: .zero, sendMax: true)356 #expect(max.isSendMax && max.amount == Self.oneEther + Self.oneEther - max.maximumFee && max.maximumTotalCost == Self.oneEther + Self.oneEther)357358 // destination with code359 let contract = "0x" + String(repeating: "c0", count: 20)360 h.backend.code[contract] = [0x60, 0x80]361 #expect(await refusal(contract) == .ethereum(.recipientIsContract))362 h.backend.gasEstimate = 40_000363 let allowed = try await service.prepareEthereumSend(asset: .ether, to: contract, amount: amount, allowContractRecipient: true)364 #expect(allowed.warnings.contains(.recipientIsContract))365 #expect(allowed.gasLimit == 40_000 * 13 / 10 + 5_000)366 h.backend.gasEstimate = 180_000367 #expect(await refusal(contract, allow: true) == .ethereum(.gasLimitTooHigh(estimated: 239_000, limit: 200_000)))368369 // a pending transaction blocks a new one370 h.backend.pendingNonce[Self.owner] = 5371 #expect(await refusal(Self.recipient) == .ethereum(.pendingTransaction(latestNonce: 3, pendingNonce: 5)))372 let replacement = try await service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: amount, feeTier: .fast, replacePending: true)373 #expect(replacement.nonce == 3 && replacement.warnings.contains(.replacesPendingTransaction(nonce: 3)))374 h.backend.pendingNonce[Self.owner] = nil375376 // own address and a high fee share are warnings377 let own = try await service.prepareEthereumSend(asset: .ether, to: Harness.abandonEthereumAddress, amount: UInt256(1_000_000_000_000))378 #expect(own.warnings.contains(.recipientIsOwnAddress))379 #expect(own.warnings.contains { if case .highFeeShare(let bp) = $0 { return bp > 500 } else { return false } })380 for w in own.warnings + allowed.warnings + replacement.warnings + lower.warnings { #expect(!w.message.isEmpty) }381382 // not enough ether for the fee alone383 h.backend.balances[Self.owner] = UInt256(1_000)384 guard case .ethereum(.insufficientFundsForFee)? = await refusal(Self.recipient, sendMax: true) else {385 Issue.record("expected insufficientFundsForFee")386 return387 }388 #expect(h.backend.broadcastEthereum.isEmpty)389 }390391 @Test func sendTokenRulesSignAndRevoke() async throws {392 let h = try await Self.funded()393 defer { h.cleanup() }394 let service = h.service395 let token = try await service.addCustomToken(address: Self.usdc)396 let recipient = try #require(EthereumAddress(Self.recipient))397 func refusal(_ to: String = Self.recipient, _ value: UInt256 = UInt256(1_500_000), sendMax: Bool = false,398 at location: SourceLocation = #_sourceLocation) async -> WalletError? {399 await walletError({ try await service.prepareEthereumSend(asset: .token(token), to: to, amount: value, sendMax: sendMax) }, sourceLocation: location)400 }401402 let review = try await service.prepareEthereumSend(asset: .token(token), to: Self.recipient, amount: UInt256(1_500_000))403 let tx = review.transaction404 // the transaction goes to the contract, carries no ether, and its data is transfer(recipient, amount)405 #expect(tx.to == token.address && tx.value.isZero && tx.nonce == 3)406 #expect(ERC20.decodeCall(tx.data) == .transfer(to: recipient, amount: UInt256(1_500_000)))407 #expect(review.recipient == recipient && review.amount == UInt256(1_500_000) && review.asset == .token(token))408 #expect(review.call == .tokenTransfer(token: token, contract: token.address, to: recipient, amount: UInt256(1_500_000)))409 // gas = estimate × 1.3 + 5 000410 #expect(tx.gasLimit == 70_000)411 #expect(review.maximumFee == UInt256(70_000 * 21_000_000_000) && review.maximumTotalCost == review.maximumFee)412413 // refusals414 #expect(await refusal(Self.usdc) == .ethereum(.recipientIsTokenContract))415 #expect(await refusal("0x0000000000000000000000000000000000000000") == .ethereum(.zeroAddress))416 #expect(await refusal(Self.recipient, .zero) == .ethereum(.zeroAmount))417 #expect(await refusal(Self.recipient, UInt256(5_000_001)) == .ethereum(.insufficientBalance(available: UInt256(5_000_000), required: UInt256(5_000_001))))418 h.backend.gasEstimate = 150_001419 #expect(await refusal() == .ethereum(.gasLimitTooHigh(estimated: 200_001, limit: 200_000)))420 h.backend.gasEstimate = 150_000421 #expect(try await service.prepareEthereumSend(asset: .token(token), to: Self.recipient, amount: UInt256(1)).gasLimit == 200_000)422 h.backend.gasEstimate = 50_000423 h.backend.gasEstimateError = "execution reverted: ERC20: transfer amount exceeds balance"424 #expect(await refusal() == .ethereum(.simulationFailed("execution reverted: ERC20: transfer amount exceeds balance")))425 h.backend.gasEstimateError = nil426 // the simulated call must return nothing or true427 h.backend.tokens[Self.usdc.lowercased()]?.transferReturn = UInt256.zero.bytes32428 #expect(await refusal() == .ethereum(.unexpectedTokenReturn))429 h.backend.tokens[Self.usdc.lowercased()]?.transferReturn = UInt256(2).bytes32430 #expect(await refusal() == .ethereum(.unexpectedTokenReturn))431 h.backend.tokens[Self.usdc.lowercased()]?.transferReturn = [0x01]432 #expect(await refusal() == .ethereum(.unexpectedTokenReturn))433 h.backend.tokens[Self.usdc.lowercased()]?.transferReturn = [] // old tokens return nothing434 _ = try await service.prepareEthereumSend(asset: .token(token), to: Self.recipient, amount: UInt256(1_500_000))435 h.backend.tokens[Self.usdc.lowercased()]?.transferReturn = UInt256(1).bytes32436 // a token of another network437 let foreign = TokenInfo(network: .mainnet, address: token.address, symbol: "USDC", name: "USD Coin", decimals: 6)438 #expect(await walletError { try await service.prepareEthereumSend(asset: .token(foreign), to: Self.recipient, amount: UInt256(1)) } == .ethereum(.tokenNetworkMismatch))439 // a token address without code440 let ghost = TokenInfo(network: .sepolia, address: recipient, symbol: "GHOST", name: "Ghost", decimals: 18)441 #expect(await walletError { try await service.prepareEthereumSend(asset: .token(ghost), to: Self.spender, amount: UInt256(1)) } == .ethereum(.tokenContractMissing))442 // ether needed for gas443 h.backend.balances[Self.owner] = UInt256(1_000_000)444 guard case .ethereum(.insufficientFundsForFee)? = await refusal() else {445 Issue.record("expected insufficientFundsForFee")446 return447 }448 h.backend.balances[Self.owner] = Self.oneEther449 #expect(h.backend.broadcastEthereum.isEmpty)450451 // send max: the whole token balance452 let max = try await service.prepareEthereumSend(asset: .token(token), to: Self.recipient, amount: .zero, sendMax: true)453 #expect(max.amount == UInt256(5_000_000) && ERC20.decodeCall(max.transaction.data) == .transfer(to: recipient, amount: UInt256(5_000_000)))454455 let result = try await service.signAndBroadcastEthereum(review)456 let decoded = try SignedEIP1559Transaction.decode(try #require(h.backend.broadcastEthereum.first))457 #expect(decoded.transaction == tx && decoded.hashHex == result.hash)458 #expect(try decoded.sender().checksummed == Harness.abandonEthereumAddress)459460 // revoke = approve(spender, 0) through the same flow461 let spender = try #require(EthereumAddress(Self.spender))462 let revoke = try await service.revokeApproval(token: token, spender: spender)463 #expect(revoke.transaction.to == token.address && revoke.transaction.value.isZero)464 #expect(ERC20.decodeCall(revoke.transaction.data) == .approve(spender: spender, amount: .zero))465 #expect(revoke.call == .tokenApproval(token: token, contract: token.address, spender: spender, amount: .zero))466 #expect(revoke.warnings == [.revokesApproval] && revoke.gasLimit == 70_000)467 _ = try await service.signAndBroadcastEthereum(revoke)468 #expect(h.backend.broadcastEthereum.count == 2)469 }470471 @Test func coldEthereumSigningRoundTrip() async throws {472 let coldBackend = FakeBackend()473 coldBackend.forbidAllRequests = true474 let cold = try await Harness.make(backend: coldBackend)475 defer { cold.cleanup() }476 try await cold.service.setColdMode(true)477 try await cold.service.importWallet(words: Harness.abandon, password: Harness.password)478479 let online = try await Self.funded() // stands for the online device; made watch-only below480 defer { online.cleanup() }481 try await online.service.deleteWallet()482 try await online.service.setEndpoints(FakeBackend.endpoints)483 try await online.service.importWatchOnly(package: try await cold.service.exportWatchOnlyPackage().frames)484 let token = try await online.service.addCustomToken(address: Self.usdc)485 let review = try await online.service.prepareEthereumSend(asset: .token(token), to: Self.recipient, amount: UInt256(2_000_000))486 #expect(await walletError { try await online.service.signAndBroadcastEthereum(review) } == .watchOnly)487 let unsigned = try await online.service.exportUnsignedEthereum(review)488 #expect(unsigned.text.hasPrefix("0x02"))489490 // the cold device does not know the token: the call is decoded, the contract is flagged as unknown491 let coldReview = try await cold.service.reviewColdEthereumPayload(unsigned.frames)492 let recipient = try #require(EthereumAddress(Self.recipient))493 #expect(coldReview.transaction == review.transaction && coldReview.network == .sepolia)494 #expect(coldReview.call == .tokenTransfer(token: nil, contract: token.address, to: recipient, amount: UInt256(2_000_000)))495 #expect(coldReview.warnings == [.unknownTokenContract])496 #expect(coldReview.maximumFee == review.maximumFee && coldReview.maximumTotalCost == review.maximumTotalCost)497 #expect(coldReview.summary.contains("Token transfer of 2000000 base units to \(Self.recipient)"))498 #expect(coldReview.summary.contains("Token contract: \(Self.usdc)"))499 #expect(coldReview.summary.first == "Network: Ethereum Sepolia (chain 11155111)")500501 await cold.service.lock()502 #expect(await walletError { try await cold.service.signColdEthereumPayload(unsigned.frames) } == .vaultLocked)503 try await cold.service.unlock(password: Harness.password)504 let signed = try await cold.service.signColdEthereumPayload(unsigned.frames)505 #expect(signed.export.text.hasPrefix("0x02") && signed.review == coldReview)506507 let result = try await online.service.broadcastSignedEthereum(signed.export.frames)508 #expect(result.hash == signed.hash && result.nonce == 3)509 let decoded = try SignedEIP1559Transaction.decode(try #require(online.backend.broadcastEthereum.first))510 #expect(decoded.transaction == review.transaction)511 #expect(try decoded.sender().checksummed == Harness.abandonEthereumAddress)512513 // a used nonce is refused before broadcasting514 online.backend.latestNonce[Self.owner] = 4515 guard case .ethereum(.unsupportedTransaction(let why))? = await walletError({ try await online.service.broadcastSignedEthereum([signed.export.text]) }) else {516 Issue.record("expected a nonce refusal")517 return518 }519 #expect(why.contains("already used"))520 #expect(online.backend.broadcastEthereum.count == 1)521522 // payloads the cold device refuses or flags523 let base = review.transaction524 func payload(_ change: (inout EIP1559Transaction) -> Void) -> String {525 var tx = base526 change(&tx)527 return "0x" + Hex.encode(tx.unsignedPayload)528 }529 #expect(await walletError { try await cold.service.reviewColdEthereumPayload([payload { $0.chainID = 1 }]) }530 == .ethereum(.chainMismatch(expected: 11_155_111, found: 1)))531 #expect(await walletError { try await cold.service.reviewColdEthereumPayload([payload { $0.gasLimit = 5_000_000 }]) }532 == .ethereum(.gasLimitTooHigh(estimated: 5_000_000, limit: 200_000)))533 #expect(await walletError { try await cold.service.reviewColdEthereumPayload([payload { $0.maxFeePerGas = UInt256(1_000_000_000_000_000_000) }]) }534 == .ethereum(.feeOutOfRange))535 #expect(await walletError { try await cold.service.reviewColdEthereumPayload([payload { $0.maxPriorityFeePerGas = UInt256(900_000_000_000) }]) }536 == .ethereum(.feeOutOfRange))537 guard case .ethereum(.unsupportedTransaction)? = await walletError({ try await cold.service.reviewColdEthereumPayload([payload { $0.to = nil }]) }) else {538 Issue.record("contract creation must be refused")539 return540 }541 #expect(await walletError { try await cold.service.reviewColdEthereumPayload([payload { $0.data = ERC20.transfer(to: token.address, amount: UInt256(1)) }]) }542 == .ethereum(.recipientIsTokenContract))543 for garbage in ["0x", "0x02", "0x01f8", "hello", "0x02c0", unsigned.text + "00"] {544 guard case .invalidPayload? = await walletError({ try await cold.service.reviewColdEthereumPayload([garbage]) }) else {545 Issue.record("expected invalidPayload for \(garbage)")546 continue547 }548 }549 // an approval without limit is spelled out550 let spender = try #require(EthereumAddress(Self.spender))551 let approval = try await cold.service.reviewColdEthereumPayload([payload { $0.data = ERC20.approve(spender: spender, amount: .max) }])552 #expect(approval.warnings.contains(.unlimitedApproval))553 #expect(approval.summary.contains { $0.contains("UNLIMITED") })554 // unknown call data: raw hexadecimal, explicit blind-signing warning, refused unless allowed555 let blind = payload { $0.data = [0xde, 0xad, 0xbe, 0xef, 0x01] }556 let blindReview = try await cold.service.reviewColdEthereumPayload([blind])557 #expect(blindReview.call == .unknown(dataHex: "0xdeadbeef01") && blindReview.warnings == [.blindSigning])558 #expect(blindReview.summary.contains { $0.contains("0xdeadbeef01") } && blindReview.summary.contains { $0.contains("Blind signing") })559 guard case .ethereum(.unsupportedTransaction)? = await walletError({ try await cold.service.signColdEthereumPayload([blind]) }) else {560 Issue.record("blind signing must be explicit")561 return562 }563 #expect(try await cold.service.signColdEthereumPayload([blind], allowBlindSigning: true).hash.count == 66)564565 // a transaction signed by another key is not broadcast for this account566 let strangerKey = Bytes(repeating: 0x42, count: 32)567 let foreign = try base.sign(privateKey: strangerKey)568 #expect(await walletError { try await online.service.broadcastSignedEthereum(["0x" + Hex.encode(foreign.raw)]) } == .ethereum(.foreignSender))569 #expect(online.backend.broadcastEthereum.count == 1)570 #expect(coldBackend.requests.isEmpty)571 }572}573