Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraEthereumTests/EVMTests.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 Testing42import QyvoraMath43import QyvoraKeccak44import QyvoraSecp256k145import QyvoraCore46@testable import QyvoraEthereum4748private func g(_ n: UInt64) -> UInt256 { UInt256(n * 1_000_000_000) }4950/// Fee rules per EVM network (pure arithmetic: every endpoint figure is an argument).51@Suite struct EVMFeeRulesTests {52 @Test func standardNetworksUseTwiceTheBaseFeePlusTheTip() throws {53 for network in [EthereumNetwork.mainnet, .sepolia, .base, .baseSepolia, .optimism, .optimismSepolia, .avalanche, .avalancheFuji, .arbitrum, .arbitrumSepolia] {54 let fees = try EVMFeeRules.gasFees(network: network, baseFee: g(10), suggestedPriorityFee: g(2), gasPrice: nil)55 #expect(fees == EVMGasFees(baseFee: g(10), maxPriorityFeePerGas: g(2), maxFeePerGas: g(22)), "\(network)")56 #expect(try EVMFeeRules.gasFees(network: network, baseFee: g(10), suggestedPriorityFee: g(2), gasPrice: nil, speed: .slow).maxPriorityFeePerGas == g(1))57 #expect(try EVMFeeRules.gasFees(network: network, baseFee: g(10), suggestedPriorityFee: g(2), gasPrice: nil, speed: .fast).maxFeePerGas == g(24))58 // an endpoint without eth_maxPriorityFeePerGas: 0.001 gwei59 #expect(try EVMFeeRules.gasFees(network: network, baseFee: g(10), suggestedPriorityFee: nil, gasPrice: nil).maxPriorityFeePerGas == UInt256(1_000_000))60 }61 }6263 /// Arbitrum's node answers a zero tip (the sequencer ignores it): the transaction carries 1 wei, never zero.64 @Test func aZeroTipBecomesOneWei() throws {65 let fees = try EVMFeeRules.gasFees(network: .arbitrum, baseFee: UInt256(20_000_000), suggestedPriorityFee: .zero, gasPrice: nil)66 #expect(fees.maxPriorityFeePerGas == UInt256(1) && fees.maxFeePerGas == UInt256(40_000_001))67 let slow = try EVMFeeRules.gasFees(network: .mainnet, baseFee: g(1), suggestedPriorityFee: UInt256(1), gasPrice: nil, speed: .slow)68 #expect(slow.maxPriorityFeePerGas == UInt256(1))69 }7071 @Test func polygonNeverGoesUnderItsMinimumTip() throws {72 for network in [EthereumNetwork.polygon, .polygonAmoy] {73 // the node suggests 25 gwei: raised to 3074 let low = try EVMFeeRules.gasFees(network: network, baseFee: g(100), suggestedPriorityFee: g(25), gasPrice: nil)75 #expect(low.maxPriorityFeePerGas == g(30) && low.maxFeePerGas == g(230))76 // "slow" halves the suggestion and is raised too77 let slow = try EVMFeeRules.gasFees(network: network, baseFee: g(100), suggestedPriorityFee: g(40), gasPrice: nil, speed: .slow)78 #expect(slow.maxPriorityFeePerGas == g(30))79 // a higher suggestion is kept80 let high = try EVMFeeRules.gasFees(network: network, baseFee: g(100), suggestedPriorityFee: g(45), gasPrice: nil)81 #expect(high.maxPriorityFeePerGas == g(45) && high.maxFeePerGas == g(245))82 // no suggestion at all still gives the minimum83 #expect(try EVMFeeRules.gasFees(network: network, baseFee: g(100), suggestedPriorityFee: nil, gasPrice: nil).maxPriorityFeePerGas == g(30))84 }85 // the minimum is Polygon's alone86 #expect(try EVMFeeRules.gasFees(network: .mainnet, baseFee: g(100), suggestedPriorityFee: g(1), gasPrice: nil).maxPriorityFeePerGas == g(1))87 }8889 /// BNB Smart Chain: base fee zero, so 2 × base + tip would be the tip alone, and a halved or missing tip would be90 /// under the validators' minimum. `eth_gasPrice` is the floor.91 @Test func bnbZeroBaseFeeUsesTheGasPriceAsFloor() throws {92 let price = UInt256(50_000_000) // 0.05 gwei, as observed on 2026-12-0593 for network in [EthereumNetwork.bsc, .bscTestnet] {94 let normal = try EVMFeeRules.gasFees(network: network, baseFee: .zero, suggestedPriorityFee: price, gasPrice: price)95 #expect(normal == EVMGasFees(baseFee: .zero, maxPriorityFeePerGas: price, maxFeePerGas: price))96 // slow would be half the minimum: kept at the floor97 let slow = try EVMFeeRules.gasFees(network: network, baseFee: .zero, suggestedPriorityFee: price, gasPrice: price, speed: .slow)98 #expect(slow.maxPriorityFeePerGas == price && slow.maxFeePerGas == price)99 let fast = try EVMFeeRules.gasFees(network: network, baseFee: .zero, suggestedPriorityFee: price, gasPrice: price, speed: .fast)100 #expect(fast.maxFeePerGas == UInt256(100_000_000))101 // a node that suggests a tip under its own gas price102 let under = try EVMFeeRules.gasFees(network: network, baseFee: .zero, suggestedPriorityFee: UInt256(1), gasPrice: g(1))103 #expect(under.maxPriorityFeePerGas == g(1) && under.maxFeePerGas == g(1))104 // without a gas price no floor is known: refused, not guessed105 #expect(throws: EVMFeeError.missingGasPrice) { try EVMFeeRules.gasFees(network: network, baseFee: .zero, suggestedPriorityFee: price, gasPrice: nil) }106 #expect(throws: EVMFeeError.missingGasPrice) { try EVMFeeRules.gasFees(network: network, baseFee: .zero, suggestedPriorityFee: price, gasPrice: .zero) }107 #expect(throws: EVMFeeError.outOfRange) {108 try EVMFeeRules.gasFees(network: network, baseFee: .zero, suggestedPriorityFee: price, gasPrice: EVMFeeRules.endpointFeePerGasCeiling)109 }110 }111 // the gas price is not read on the other networks112 #expect(try EVMFeeRules.gasFees(network: .mainnet, baseFee: g(1), suggestedPriorityFee: g(1), gasPrice: g(500)).maxFeePerGas == g(3))113 }114115 @Test func endpointFiguresAreBounded() throws {116 let ceiling = EVMFeeRules.endpointFeePerGasCeiling117 #expect(ceiling == g(10_000))118 for network in EthereumNetwork.allCases {119 let price: UInt256? = network.hasZeroBaseFee ? g(1) : nil120 #expect(throws: EVMFeeError.outOfRange) { try EVMFeeRules.gasFees(network: network, baseFee: ceiling, suggestedPriorityFee: g(1), gasPrice: price) }121 #expect(throws: EVMFeeError.outOfRange) { try EVMFeeRules.gasFees(network: network, baseFee: g(1), suggestedPriorityFee: ceiling, gasPrice: price) }122 #expect(throws: EVMFeeError.outOfRange) { try EVMFeeRules.gasFees(network: network, baseFee: .max, suggestedPriorityFee: .max, gasPrice: price) }123 // the largest accepted figures give a maxFeePerGas under 100 000 gwei, and the tip never exceeds it124 let top = ceiling - UInt256(1)125 let fees = try EVMFeeRules.gasFees(network: network, baseFee: top, suggestedPriorityFee: top, gasPrice: price, speed: .fast)126 #expect(fees.maxFeePerGas < EVMFeeRules.maxFeePerGasCeiling && fees.maxPriorityFeePerGas <= fees.maxFeePerGas)127 }128 }129130 @Test func fixedTransferGasOnlyWhereItIsTrue() {131 for network in EthereumNetwork.allCases {132 #expect(EVMFeeRules.fixedNativeTransferGas(network) == (network.isArbitrum ? nil : 21_000), "\(network)")133 }134 }135136 @Test func maximumCostCountsTheL1Fee() throws {137 let to = EthereumAddress("0x70997970C51812dc3A010C7d01b50e0d17dc79C8")!138 let tx = EIP1559Transaction(chainID: 8_453, nonce: 0, maxPriorityFeePerGas: UInt256(1_000_000), maxFeePerGas: UInt256(11_000_000),139 gasLimit: 21_000, to: to, value: UInt256(1_000_000_000_000_000))140 #expect(EVMFeeRules.maximumCost(tx) == tx.maximumCost)141 #expect(EVMFeeRules.maximumCost(tx, l1DataFee: UInt256(9_000_000_000))?.description == "1000240000000000")142 #expect(EVMFeeRules.maximumFee(gasLimit: 21_000, maxFeePerGas: UInt256(11_000_000), l1DataFee: UInt256(9_000_000_000))?.description == "240000000000")143 #expect(EVMFeeRules.maximumCost(tx, l1DataFee: .max) == nil)144 #expect(EVMFeeRules.maximumFee(gasLimit: .max, maxFeePerGas: .max) == nil)145 }146147 @Test func sendMaxLeavesRoomForGasAndL1Fee() {148 let balance = UInt256(1_000_000_000_000_000), price = UInt256(11_000_000)149 // gas only: 21 000 × 0.011 gwei = 231 000 000 000 wei150 #expect(EVMFeeRules.sendMaxValue(balance: balance, gasLimit: 21_000, maxFeePerGas: price)?.description == "999769000000000")151 // with an L1 fee of 9 gwei-units reserved152 let l1 = OPStackGasOracle.withMargin(UInt256(8_000_000_000))153 #expect(l1 == UInt256(10_000_000_000))154 let value = EVMFeeRules.sendMaxValue(balance: balance, gasLimit: 21_000, maxFeePerGas: price, l1DataFee: l1)155 #expect(value?.description == "999759000000000")156 // value + gas + L1 fee is the whole balance, never more157 #expect(value! + UInt256(231_000_000_000) + l1 == balance)158 // a balance that only covers the fees leaves nothing to send159 #expect(EVMFeeRules.sendMaxValue(balance: UInt256(241_000_000_000), gasLimit: 21_000, maxFeePerGas: price, l1DataFee: l1) == nil)160 #expect(EVMFeeRules.sendMaxValue(balance: UInt256(241_000_000_001), gasLimit: 21_000, maxFeePerGas: price, l1DataFee: l1) == UInt256(1))161 #expect(EVMFeeRules.sendMaxValue(balance: .zero, gasLimit: 21_000, maxFeePerGas: price) == nil)162 }163}164165/// The OP-Stack GasPriceOracle: call encoding and bounded decoding.166@Suite struct OPStackGasOracleTests {167 @Test func addressAndSelector() {168 #expect(OPStackGasOracle.address.checksummed == "0x420000000000000000000000000000000000000F")169 #expect(OPStackGasOracle.address.checksummed == EVMPredeploys.opStackGasPriceOracle)170 // bytes4(keccak256("getL1Fee(bytes)"))171 #expect(Hex.encode(OPStackGasOracle.getL1FeeSelector) == "49948e0e")172 }173174 @Test func callIsAnABIEncodedBytesArgument() {175 let payload = Bytes(hex: "02e7822105808307a120830f4240825208940000000000000000000000000000000000dead87038d7ea4c6800080c0")!176 let n = payload.count177 let call = OPStackGasOracle.getL1FeeCall(payload)178 #expect(n > 32 && n < 64 && call.count == 4 + 32 + 32 + 64)179 #expect(Bytes(call[0..<4]) == OPStackGasOracle.getL1FeeSelector)180 #expect(UInt256(bigEndian: Bytes(call[4..<36])) == UInt256(32))181 #expect(UInt256(bigEndian: Bytes(call[36..<68])) == UInt256(UInt64(n)))182 #expect(Bytes(call[68..<(68 + n)]) == payload)183 #expect(call[(68 + n)...].allSatisfy { $0 == 0 })184 // a payload that fills its last word gets no padding; an empty one is two words185 #expect(OPStackGasOracle.getL1FeeCall(Bytes(repeating: 1, count: 64)).count == 4 + 64 + 64)186 #expect(OPStackGasOracle.getL1FeeCall([]).count == 4 + 64)187 }188189 @Test func feeIsOneBoundedWord() {190 #expect(OPStackGasOracle.decodeFee(UInt256(7_314_461_274).bytes32) == UInt256(7_314_461_274))191 #expect(OPStackGasOracle.decodeFee(UInt256.zero.bytes32) == .zero)192 #expect(OPStackGasOracle.decodeFee([]) == nil)193 #expect(OPStackGasOracle.decodeFee(Bytes(repeating: 0, count: 31)) == nil)194 #expect(OPStackGasOracle.decodeFee(Bytes(repeating: 0, count: 64)) == nil)195 // 0.1 ETH or more for the data of one transaction is not believed196 #expect(OPStackGasOracle.decodeFee(OPStackGasOracle.feeCeiling.bytes32) == nil)197 #expect(OPStackGasOracle.decodeFee((OPStackGasOracle.feeCeiling - UInt256(1)).bytes32) != nil)198 #expect(OPStackGasOracle.decodeFee(UInt256.max.bytes32) == nil)199 }200201 @Test func marginIsOneQuarterAndNeverWraps() {202 #expect(OPStackGasOracle.withMargin(.zero) == .zero)203 #expect(OPStackGasOracle.withMargin(UInt256(100)) == UInt256(125))204 #expect(OPStackGasOracle.withMargin(UInt256(7)) == UInt256(8))205 #expect(OPStackGasOracle.withMargin(.max) == .max)206 }207}208209/// The chain identifier is inside the signed payload: one transaction, two chains, two unrelated signatures.210@Suite struct EVMChainSigningTests {211 static let key = Bytes(hex: "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80")!212 static let account = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"213214 static func transaction(chainID: UInt64) -> EIP1559Transaction {215 EIP1559Transaction(chainID: chainID, nonce: 7, maxPriorityFeePerGas: UInt256(30_000_000_000), maxFeePerGas: UInt256(230_000_000_000),216 gasLimit: 21_000, to: EthereumAddress("0x70997970C51812dc3A010C7d01b50e0d17dc79C8")!,217 value: UInt256(decimal: "250000000000000000")!)218 }219220 @Test func sameTransactionOnBaseAndPolygon() throws {221 let base = Self.transaction(chainID: EthereumNetwork.base.chainID), polygon = Self.transaction(chainID: EthereumNetwork.polygon.chainID)222 #expect(base.chainID == 8_453 && polygon.chainID == 137)223 // the payloads differ only by the chain identifier, the first RLP item224 #expect(base.unsignedPayload != polygon.unsignedPayload)225 #expect(base.signingHash != polygon.signingHash)226 #expect(try EIP1559Transaction.decodeUnsigned(base.unsignedPayload).chainID == 8_453)227 #expect(try EIP1559Transaction.decodeUnsigned(polygon.unsignedPayload).chainID == 137)228229 let signedBase = try base.sign(privateKey: Self.key), signedPolygon = try polygon.sign(privateKey: Self.key)230 #expect(try signedBase.sender().checksummed == Self.account)231 #expect(try signedPolygon.sender().checksummed == Self.account)232 #expect(signedBase.hash != signedPolygon.hash && signedBase.raw != signedPolygon.raw)233 #expect(signedBase.r != signedPolygon.r)234 #expect(try SignedEIP1559Transaction.decode(signedBase.raw) == signedBase)235 #expect(try SignedEIP1559Transaction.decode(signedPolygon.raw).transaction.chainID == 137)236237 // replay: Base's signature placed on the Polygon transaction does not recover this account238 let replayed = SignedEIP1559Transaction(transaction: polygon, yParity: signedBase.yParity, r: signedBase.r, s: signedBase.s)239 #expect((try? replayed.sender())?.checksummed != Self.account)240 }241242 /// Deterministic signatures (RFC 6979): the same input signs to the same bytes, on every supported chain, and243 /// all fourteen hashes are different.244 @Test func everySupportedChainSignsToItsOwnHash() throws {245 var hashes = Set<Bytes>()246 for network in EthereumNetwork.allCases {247 let tx = Self.transaction(chainID: network.chainID)248 let signed = try tx.sign(privateKey: Self.key)249 #expect(try signed.sender().checksummed == Self.account, "\(network)")250 #expect(try tx.sign(privateKey: Self.key) == signed)251 #expect(try SignedEIP1559Transaction.decode(signed.raw).transaction == tx)252 hashes.insert(signed.hash)253 }254 #expect(hashes.count == EthereumNetwork.allCases.count)255 }256}257258/// Integrity of the built-in token lists.259@Suite struct BuiltInTokenListTests {260 @Test func countsPerNetwork() {261 let expected: [EthereumNetwork: Int] = [.mainnet: 24, .base: 14, .arbitrum: 16, .optimism: 11, .polygon: 12, .bsc: 12, .avalanche: 9]262 for network in EthereumNetwork.mainNetworks {263 #expect(BuiltInTokens.tokens(for: network).count == expected[network], "\(network)")264 // no row was dropped for a bad address or checksum265 #expect(BuiltInTokens.tokens(for: network).count == BuiltInTokens.table(for: network).count)266 }267 for network in EthereumNetwork.testNetworks {268 #expect(BuiltInTokens.tokens(for: network).isEmpty && BuiltInTokens.table(for: network).isEmpty)269 }270 #expect(BuiltInTokens.tokens(for: .mainnet) == BuiltInTokens.mainnet)271 }272273 @Test func everyAddressIsWrittenWithItsEIP55Checksum() throws {274 for network in EthereumNetwork.mainNetworks {275 for row in BuiltInTokens.table(for: network) {276 let address = try #require(EthereumAddress(row.3), "\(network) \(row.0)")277 #expect(address.checksummed == row.3, "\(network) \(row.0)")278 #expect(!address.isZero)279 }280 }281 }282283 @Test func addressesAndSymbolsAreUniquePerNetwork() {284 for network in EthereumNetwork.mainNetworks {285 let tokens = BuiltInTokens.tokens(for: network)286 #expect(Set(tokens.map(\.address)).count == tokens.count, "\(network): duplicate address")287 #expect(Set(tokens.map(\.symbol)).count == tokens.count, "\(network): duplicate symbol")288 #expect(Set(tokens.map(\.id)).count == tokens.count)289 for token in tokens {290 #expect(token.network == network && !token.custom)291 #expect(!token.symbol.isEmpty && token.symbol.count <= 16 && !token.name.isEmpty && token.name.count <= 48, "\(network) \(token.symbol)")292 #expect((0...18).contains(token.decimals))293 if let id = token.priceID {294 #expect(!id.isEmpty && id.utf8.allSatisfy { ($0 >= 0x61 && $0 <= 0x7a) || ($0 >= 0x30 && $0 <= 0x39) || $0 == 0x2d }, "\(network) \(token.symbol)")295 }296 }297 }298 // identifiers are unique across networks too, although a contract may sit at the same address on two chains299 let all = EthereumNetwork.mainNetworks.flatMap(BuiltInTokens.tokens(for:))300 #expect(Set(all.map(\.id)).count == all.count)301 #expect(all.count == 98)302 }303304 @Test func nativeAndBridgedUSDCAreDistinct() throws {305 // Circle's own token, per network (Circle's contract list)306 let native: [EthereumNetwork: String] = [307 .mainnet: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", .base: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",308 .arbitrum: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", .optimism: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",309 .polygon: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", .avalanche: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",310 ]311 for (network, address) in native {312 let usdc = try #require(BuiltInTokens.tokens(for: network).first { $0.symbol == "USDC" })313 #expect(usdc.address.checksummed == address && usdc.decimals == 6 && usdc.name == "USD Coin" && usdc.priceID == "usd-coin")314 }315 for network in [EthereumNetwork.arbitrum, .optimism, .polygon, .avalanche] {316 let bridged = try #require(BuiltInTokens.tokens(for: network).first { $0.symbol == "USDC.e" })317 #expect(bridged.name.hasPrefix("Bridged USDC") && bridged.decimals == 6)318 #expect(bridged.address != BuiltInTokens.tokens(for: network).first { $0.symbol == "USDC" }?.address)319 #expect(bridged.priceID != "usd-coin")320 }321 // BNB Smart Chain has no Circle-issued USDC: the token there is Binance's, with 18 decimals, and says so322 let peg = try #require(BuiltInTokens.tokens(for: .bsc).first { $0.symbol == "USDC" })323 #expect(peg.name == "Binance-Peg USD Coin" && peg.decimals == 18 && peg.priceID != "usd-coin")324 }325326 @Test func wrappedNativeCoins() throws {327 let wrapped: [EthereumNetwork: (String, String)] = [328 .mainnet: ("WETH", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"), .base: ("WETH", "0x4200000000000000000000000000000000000006"),329 .optimism: ("WETH", "0x4200000000000000000000000000000000000006"), .arbitrum: ("WETH", "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"),330 .polygon: ("WPOL", "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270"), .bsc: ("WBNB", "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"),331 .avalanche: ("WAVAX", "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7"),332 ]333 for (network, (symbol, address)) in wrapped {334 let token = try #require(BuiltInTokens.tokens(for: network).first { $0.symbol == symbol }, "\(network)")335 #expect(token.address.checksummed == address && token.decimals == 18)336 }337 }338339 /// The identifier of a token names its network: the same contract address on two chains is two tokens.340 @Test func tokenInfoIdentifierIsNetworkScoped() throws {341 let a = try #require(EthereumAddress("0x0555E30da8f98308EdB960aa94C0Db47230d2B9c"))342 let onBase = TokenInfo(network: .base, address: a, symbol: "WBTC", name: "Wrapped Bitcoin", decimals: 8)343 let onBSC = TokenInfo(network: .bsc, address: a, symbol: "WBTC", name: "Wrapped Bitcoin", decimals: 8)344 #expect(onBase.id == "base:0x0555E30da8f98308EdB960aa94C0Db47230d2B9c" && onBase.id != onBSC.id)345 }346}347