Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/EVMNetworkTests.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 QyvoraEthereum46import QyvoraNetworking47@testable import QyvoraWallet4849/// The service on EVM networks other than Ethereum: the fee rules of each network reach the transaction that is50/// reviewed and signed. Test networks only, so the suite does not depend on the process-wide mainnet policy.51@Suite(.readsMainnetPolicy) struct EVMNetworkWalletTests {52 static let owner = EthereumWalletTests.owner53 static let recipient = EthereumWalletTests.recipient54 static let oneEther = EthereumWalletTests.oneEther55 static let gwei = EthereumWalletTests.gwei5657 static func quantity(_ n: UInt64) -> String { "\"\(UInt256(n).hexQuantity)\"" }58 static func word(_ n: UInt64) -> String { "\"0x\(Hex.encode(UInt256(n).bytes32))\"" }5960 /// A funded wallet whose active EVM network is `network`, served by the fake node.61 static func wallet(on network: EthereumNetwork, served: EthereumNetwork? = nil) async throws -> Harness {62 let h = try await Harness.abandonWallet()63 var endpoints = FakeBackend.endpoints64 endpoints.ethereumRPC[network.rawValue] = ["https://rpc.test"]65 try await h.service.setEndpoints(endpoints)66 h.backend.chainID = (served ?? network).chainID67 try await h.service.setEthereumNetwork(network)68 h.backend.balances[owner] = oneEther + oneEther69 return h70 }7172 @Test func opStackSendShowsAndReservesTheL1DataFee() async throws {73 for network in [EthereumNetwork.baseSepolia, .optimismSepolia] {74 let h = try await Self.wallet(on: network)75 defer { h.cleanup() }76 // the GasPriceOracle quotes 8 gwei-units for this transaction; the wallet reserves a quarter more77 h.backend.rpcResultOverride["eth_call"] = Self.word(8_000_000_000)78 let gasFee = UInt256(21_000 * 21_000_000_000) // 21 000 gas × (2 × 10 gwei + 1 gwei)79 let l1 = UInt256(10_000_000_000)80 let half = UInt256(500_000_000_000_000_000)8182 let review = try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: half)83 #expect(review.network == network && review.transaction.chainID == network.chainID && review.gasLimit == 21_000)84 #expect(review.l1DataFee == l1)85 #expect(review.maximumFee == gasFee + l1)86 #expect(review.maximumTotalCost == half + gasFee + l1)87 #expect(review.transaction.value == half)8889 // sending everything leaves exactly the gas fee and the reserved L1 fee behind90 let all = try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: .zero, sendMax: true)91 #expect(all.l1DataFee == l1 && all.maximumFee == gasFee + l1)92 #expect(all.amount + all.maximumFee == Self.oneEther + Self.oneEther)93 #expect(all.maximumTotalCost == Self.oneEther + Self.oneEther && all.transaction.value == all.amount)9495 // a balance that covers the gas but not the L1 fee cannot be swept96 h.backend.balances[Self.owner] = gasFee + UInt256(5_000_000_000)97 guard case .ethereum(.insufficientFundsForFee)? = await walletError({ try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: .zero, sendMax: true) }) else {98 Issue.record("\(network): the L1 fee must be covered")99 continue100 }101 h.backend.balances[Self.owner] = Self.oneEther + Self.oneEther102103 // the reviewed transaction is signed for this chain and broadcast104 let sent = try await h.service.signAndBroadcastEthereum(review)105 let raw = try #require(h.backend.broadcastEthereum.first)106 let decoded = try SignedEIP1559Transaction.decode(raw)107 #expect(decoded.transaction.chainID == network.chainID && decoded.hashHex == sent.hash)108 #expect(try decoded.sender().checksummed == Harness.abandonEthereumAddress)109110 // without a quote from the oracle nothing is prepared: the cost would be understated111 h.backend.latestNonce[Self.owner] = 1112 h.backend.rpcResultOverride["eth_call"] = "\"0x\""113 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: half) } != nil)114 // an absurd quote (0.1 ETH for one transfer) is refused as well115 h.backend.rpcResultOverride["eth_call"] = Self.word(100_000_000_000_000_000)116 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: half) } != nil)117 }118 }119120 @Test func noL1FeeOutsideOPStack() async throws {121 for network in [EthereumNetwork.sepolia, .avalancheFuji] {122 let h = try await Self.wallet(on: network)123 defer { h.cleanup() }124 // an answer to eth_call that would be a fee on an OP-Stack network is never asked for here125 h.backend.rpcResultOverride["eth_call"] = Self.word(8_000_000_000)126 let review = try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: Self.oneEther)127 #expect(review.l1DataFee == .zero && review.gasLimit == 21_000)128 #expect(review.maximumFee == UInt256(21_000 * 21_000_000_000))129 #expect(review.maximumTotalCost == Self.oneEther + review.maximumFee)130 let all = try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: .zero, sendMax: true)131 #expect(all.amount + all.maximumFee == Self.oneEther + Self.oneEther)132 }133 }134135 /// Arbitrum: a plain transfer is not 21 000 gas, the limit comes from the estimate (with the usual margin).136 @Test func arbitrumTransferGasIsEstimated() async throws {137 let h = try await Self.wallet(on: .arbitrumSepolia)138 defer { h.cleanup() }139 h.backend.gasEstimate = 21_815140 h.backend.baseFee = UInt256(20_000_000)141 h.backend.priorityFee = .zero142 let review = try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: Self.oneEther)143 #expect(review.gasLimit == 21_815 * 13 / 10 + 5_000)144 #expect(review.gasLimit == 33_359 && review.l1DataFee == .zero)145 // the node's zero tip becomes 1 wei146 #expect(review.transaction.maxPriorityFeePerGas == UInt256(1) && review.transaction.maxFeePerGas == UInt256(40_000_001))147 #expect(review.maximumFee == UInt256(33_359 * 40_000_001))148 let all = try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: .zero, sendMax: true)149 #expect(all.gasLimit == 33_359 && all.amount + all.maximumFee == Self.oneEther + Self.oneEther)150 // no estimate, no transaction: 21 000 is not assumed151 h.backend.gasEstimateError = "execution reverted"152 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: Self.oneEther) }153 == .ethereum(.simulationFailed("execution reverted")))154 // the same estimate on Sepolia is not even asked for155 let sepolia = try await Self.wallet(on: .sepolia)156 defer { sepolia.cleanup() }157 sepolia.backend.gasEstimateError = "execution reverted"158 #expect(try await sepolia.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: Self.oneEther).gasLimit == 21_000)159 }160161 @Test func bnbZeroBaseFeeUsesTheGasPriceFloor() async throws {162 let h = try await Self.wallet(on: .bscTestnet)163 defer { h.cleanup() }164 h.backend.baseFee = .zero165 h.backend.priorityFee = UInt256(50_000_000)166 h.backend.rpcResultOverride["eth_gasPrice"] = Self.quantity(50_000_000)167 for (tier, expected) in [(EthereumFeeTier.slow, UInt64(50_000_000)), (.normal, 50_000_000), (.fast, 100_000_000)] {168 let review = try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: Self.oneEther, feeTier: tier)169 #expect(review.transaction.maxFeePerGas == UInt256(expected) && review.transaction.maxPriorityFeePerGas == UInt256(expected), "\(tier)")170 #expect(review.baseFee == .zero && review.transaction.chainID == 97 && review.gasLimit == 21_000)171 #expect(review.maximumFee == UInt256(21_000 * expected))172 }173 // a node that suggests a tip under its gas price: the price wins174 h.backend.priorityFee = UInt256(1)175 h.backend.rpcResultOverride["eth_gasPrice"] = Self.quantity(3_000_000_000)176 #expect(try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: Self.oneEther).transaction.maxFeePerGas == UInt256(3_000_000_000))177 // no gas price (the fake node does not know the method): refused rather than priced at zero plus a tip178 h.backend.rpcResultOverride["eth_gasPrice"] = nil179 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: Self.oneEther) } != nil)180 #expect(h.backend.broadcastEthereum.isEmpty)181 }182183 @Test func polygonMinimumTipReachesTheTransaction() async throws {184 let h = try await Self.wallet(on: .polygonAmoy)185 defer { h.cleanup() }186 h.backend.baseFee = UInt256(100_000_000_000)187 h.backend.priorityFee = UInt256(25_000_000_000)188 for tier in EthereumFeeTier.allCases {189 let review = try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: Self.oneEther, feeTier: tier)190 let tip: UInt64 = tier == .fast ? 50_000_000_000 : 30_000_000_000191 #expect(review.transaction.maxPriorityFeePerGas == UInt256(tip), "\(tier)")192 #expect(review.transaction.maxFeePerGas == UInt256(200_000_000_000 + tip))193 #expect(review.transaction.chainID == 80_002)194 }195 // the same node figures on Sepolia keep the node's 25 gwei196 let sepolia = try await Self.wallet(on: .sepolia)197 defer { sepolia.cleanup() }198 sepolia.backend.priorityFee = UInt256(25_000_000_000)199 #expect(try await sepolia.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: Self.oneEther).transaction.maxPriorityFeePerGas == UInt256(25_000_000_000))200 }201202 /// An endpoint that serves another chain than the active network is refused before anything is read from it.203 @Test func wrongChainIsRefusedOnEveryTestNetwork() async throws {204 for network in EthereumNetwork.testNetworks {205 let other: EthereumNetwork = network == .sepolia ? .baseSepolia : .sepolia206 let h = try await Self.wallet(on: network, served: other)207 defer { h.cleanup() }208 guard case .wrongChain(let text)? = await walletError({ try await h.service.syncEthereum() }) else {209 Issue.record("\(network): an endpoint of chain \(other.chainID) was accepted")210 continue211 }212 #expect(text.contains("\(other.chainID)") && text.contains("\(network.chainID)"))213 guard case .wrongChain? = await walletError({ try await h.service.prepareEthereumSend(asset: .ether, to: Self.recipient, amount: Self.oneEther) }) else {214 Issue.record("\(network): a send was prepared on the wrong chain")215 continue216 }217 // the right chain is then accepted218 h.backend.chainID = network.chainID219 #expect(try await h.service.syncEthereum().network == network)220 }221 }222223 /// A transaction for another chain than the active one is never signed, whatever its origin.224 @Test func aPayloadOfAnotherChainIsNotSigned() async throws {225 let h = try await Self.wallet(on: .baseSepolia)226 defer { h.cleanup() }227 let foreign = EIP1559Transaction(chainID: EthereumNetwork.optimismSepolia.chainID, nonce: 0, maxPriorityFeePerGas: UInt256(1_000_000),228 maxFeePerGas: UInt256(11_000_000), gasLimit: 21_000, to: EthereumAddress(Self.recipient)!, value: UInt256(1))229 #expect(await walletError { try await h.service.signColdEthereumPayload(["0x" + Hex.encode(foreign.unsignedPayload)]) }230 == .ethereum(.chainMismatch(expected: 84_532, found: 11_155_420)))231 }232233 /// Without indexer (Base, Arbitrum, Polygon, BNB Smart Chain by default) the balance is read and the history is234 /// reported as unavailable: nothing is invented.235 @Test func balanceWithoutIndexerAndHonestHistory() async throws {236 let h = try await Self.wallet(on: .polygonAmoy)237 defer { h.cleanup() }238 let snapshot = try await h.service.syncEthereum()239 #expect(snapshot.network == .polygonAmoy)240 guard case .unavailable(let reason) = snapshot.history else {241 Issue.record("a history appeared without any indexer")242 return243 }244 #expect(reason.contains("No indexer"))245 #expect(!h.backend.requests.contains { $0.contains("indexer.test") })246 }247}248249/// Mainnet gate and per-transaction ceilings on the EVM networks. In the serialized suite: `MainnetPolicy` is process-wide.250extension MainnetPolicyTests {251 /// An internal build with mainnet on, the active EVM network being `network`.252 static func evmMainnetWallet(_ network: EthereumNetwork) async throws -> Harness {253 let h = try await mainnetWallet()254 var endpoints = FakeBackend.endpoints255 endpoints.ethereumRPC[network.rawValue] = ["https://rpc.test"]256 try await h.service.setEndpoints(endpoints)257 h.backend.chainID = network.chainID258 try await h.service.setEthereumNetwork(network)259 return h260 }261262 @Test func everyEVMMainNetworkIsBehindTheGate() async throws {263 Self.reset()264 defer { Self.reset() }265 let h = try await Harness.abandonWallet()266 defer { h.cleanup() }267 for network in EthereumNetwork.mainNetworks {268 guard case .mainnetDisabled? = await walletError({ try await h.service.setEthereumNetwork(network) }) else {269 Issue.record("\(network) was accepted without the mainnet switch")270 continue271 }272 guard case .mainnetDisabled? = await walletError({ try await h.service.setActiveNetworks(bitcoin: .signet, ethereum: network) }) else {273 Issue.record("\(network) was accepted without the mainnet switch")274 continue275 }276 }277 #expect(await h.service.currentProfile().ethereumNetwork == .sepolia)278 for network in EthereumNetwork.testNetworks {279 try await h.service.setEthereumNetwork(network)280 #expect(await h.service.currentProfile().ethereumNetwork == network)281 }282 }283284 @Test func switchingMainnetOffReturnsToTheTestNetworkOfTheSameChain() async throws {285 Self.reset()286 defer { Self.reset() }287 for network in [EthereumNetwork.polygon, .base, .avalanche] {288 let h = try await Self.evmMainnetWallet(network)289 defer { h.cleanup() }290 #expect(await h.service.currentProfile().ethereumNetwork == network)291 #expect(try await h.service.setMainnetOptIn(false) == false)292 #expect(await h.service.currentProfile().ethereumNetwork == network.testCounterpart)293 guard case .mainnetDisabled? = await walletError({ try await h.service.setEthereumNetwork(network) }) else {294 Issue.record("\(network) is still usable after the switch was turned off")295 continue296 }297 Self.reset()298 }299 }300301 /// Ether's ceilings (0.05 ETH, maximum fee 0.01 ETH) apply on a rollup whose native coin is ether, without any price.302 @Test func etherCeilingsApplyOnBase() async throws {303 Self.reset()304 defer { Self.reset() }305 let h = try await Self.evmMainnetWallet(.base)306 defer { h.cleanup() }307 h.backend.priceStatus = 500308 h.backend.balances[EthereumWalletTests.owner] = EthereumWalletTests.oneEther309 h.backend.baseFee = UInt256(5_000_000)310 h.backend.priorityFee = UInt256(1_000_000)311 h.backend.rpcResultOverride["eth_call"] = EVMNetworkWalletTests.word(8_000_000_000)312 let recipient = EthereumWalletTests.recipient, limit = UInt256(50_000_000_000_000_000)313314 let review = try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: limit)315 #expect(review.network == .base && review.transaction.chainID == 8_453 && review.warnings.contains(.unauditedMainnet))316 #expect(review.l1DataFee == UInt256(10_000_000_000))317 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: limit + UInt256(1)) }318 == .exceedsUnauditedLimit(limit: "0.05 ETH per transaction"))319 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: .zero, sendMax: true) }320 == .exceedsUnauditedLimit(limit: "0.05 ETH per transaction"))321 // at sign, through the cold path322 var bigger = review.transaction323 bigger.value = limit + limit324 #expect(await walletError { try await h.service.signColdEthereumPayload(["0x" + Hex.encode(bigger.unsignedPayload)]) }325 == .exceedsUnauditedLimit(limit: "0.05 ETH per transaction"))326327 // the L1 data fee counts in the capped fee: 0.009 ETH quoted, 0.01125 ETH reserved, above 0.01 ETH328 h.backend.rpcResultOverride["eth_call"] = EVMNetworkWalletTests.word(9_000_000_000_000_000)329 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: UInt256(1_000)) }330 == .exceedsUnauditedLimit(limit: "a maximum fee of 0.01 ETH per transaction"))331 // 0.007 ETH quoted, 0.00875 ETH reserved: allowed332 h.backend.rpcResultOverride["eth_call"] = EVMNetworkWalletTests.word(7_000_000_000_000_000)333 #expect(try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: UInt256(1_000)).maximumFee < UInt256(10_000_000_000_000_000))334335 h.backend.rpcResultOverride["eth_call"] = EVMNetworkWalletTests.word(8_000_000_000)336 _ = try await h.service.signAndBroadcastEthereum(review)337 #expect(h.backend.broadcastEthereum.count == 1)338 }339340 /// POL, BNB and AVAX: 150 USD per transaction and a maximum fee of 5 USD, both at a fresh price; no price, no send.341 @Test func dollarCeilingsApplyToOtherNativeCoins() async throws {342 Self.reset()343 defer { Self.reset() }344 let recipient = EthereumWalletTests.recipient345 let coin = EthereumWalletTests.oneEther346 for network in [EthereumNetwork.polygon, .bsc, .avalanche] {347 let h = try await Self.evmMainnetWallet(network)348 defer { h.cleanup() }349 let symbol = network.nativeSymbol350 h.backend.balances[EthereumWalletTests.owner] = coin.multipliedReportingOverflow(by: 1_000).0351 h.backend.baseFee = network.hasZeroBaseFee ? .zero : UInt256(100_000_000_000)352 h.backend.priorityFee = UInt256(30_000_000_000)353 h.backend.rpcResultOverride["eth_gasPrice"] = EVMNetworkWalletTests.quantity(30_000_000_000)354355 // no price and the source is down: the value cannot be checked, nothing is prepared356 h.backend.priceStatus = 500357 guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: coin) }) else {358 Issue.record("\(network): a native coin without a fresh price must be refused")359 continue360 }361362 // at 500 USD a coin (above every floor of MainnetPolicy.minimumPlausibleUSDPrice): 0.3 coin passes, 0.32 does363 // not; the fee (at most 0.00483 coin) is under 5 USD. The second price source of the model agrees.364 h.backend.priceStatus = 200365 h.backend.markets = ServiceTests.market([(network.priceID, "500.0")])366 let allowed = UInt256(300_000_000_000_000_000), refused = UInt256(320_000_000_000_000_000)367 let review = try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: allowed)368 #expect(review.network == network && review.transaction.chainID == network.chainID && review.warnings.contains(.unauditedMainnet))369 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: refused) }370 == .exceedsUnauditedLimit(limit: "150 USD of \(symbol) per transaction"))371 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: .zero, sendMax: true) }372 == .exceedsUnauditedLimit(limit: "150 USD of \(symbol) per transaction"))373 // at sign, through the cold path: the reviewed transaction with a larger value374 var bigger = review.transaction375 bigger.value = refused376 #expect(await walletError { try await h.service.signColdEthereumPayload(["0x" + Hex.encode(bigger.unsignedPayload)]) }377 == .exceedsUnauditedLimit(limit: "150 USD of \(symbol) per transaction"))378379 // the ceilings follow the price: at 2 000 USD a coin, 0.3 coin is 600 USD …380 h.clock.advance(700)381 try await h.service.unlock(password: Harness.password)382 h.backend.markets = ServiceTests.market([(network.priceID, "2000.0")])383 #expect(await walletError { try await h.service.signAndBroadcastEthereum(review) } == .exceedsUnauditedLimit(limit: "150 USD of \(symbol) per transaction"))384 // … and a fee of 21 000 gas × 230 gwei (30 on BNB Smart Chain) costs 9.66 USD (1.26 USD): above 5 USD on the first two385 let small = UInt256(1_000_000_000_000_000)386 if network.hasZeroBaseFee {387 #expect(try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: small).maximumFee == UInt256(21_000 * 30_000_000_000))388 } else {389 #expect(await walletError { try await h.service.prepareEthereumSend(asset: .ether, to: recipient, amount: small) }390 == .exceedsUnauditedLimit(limit: "a maximum fee of 5 USD of \(symbol) per transaction"))391 }392 #expect(h.backend.broadcastEthereum.isEmpty)393394 // a stale price is not used: with the source down again, nothing is signed395 h.clock.advance(700)396 try await h.service.unlock(password: Harness.password)397 h.backend.priceStatus = 503398 guard case .unauditedLimitUnverifiable? = await walletError({ try await h.service.signAndBroadcastEthereum(review) }) else {399 Issue.record("\(network): a stale price must not be used for the limit")400 continue401 }402 #expect(h.backend.broadcastEthereum.isEmpty)403 Self.reset()404 }405 }406}407