SPB Git

Repository Public

EVMChainsVectors.swift 17.9 KB 238 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/ConformanceAuditTests/EVMChainsVectors.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 AuditSupport42import Foundation43import QyvoraMath44import Testing4546@testable import QyvoraCore47@testable import QyvoraEthereum48@testable import QyvoraNetworking4950// The EVM network table against the public chain registry, written here by hand from the reviewer's knowledge of51// ethereum-lists/chains (chain identifier, native currency symbol and decimals, explorer) — the differential suite52// compares the same identifiers with the copy of that registry shipped in eth-utils. A wrong chain identifier signs53// for another chain; wrong decimals show another amount than the one signed.5455@Suite struct EVMChainsVectors {56    struct Row {57        let network: EthereumNetwork58        let chainID: UInt6459        let symbol: String60        let decimals: Int61        let isTest: Bool62        let explorer: String63    }6465    /// ethereum-lists/chains: `chainId`, `nativeCurrency.symbol` (the test networks of BNB Smart Chain name theirs66    /// "tBNB"; the wallet shows the main network's ticker and marks the network as a test one), `nativeCurrency.decimals`,67    /// and the explorer of each network's operator.68    static let registry: [Row] = [69        Row(network: .mainnet, chainID: 1, symbol: "ETH", decimals: 18, isTest: false, explorer: "https://etherscan.io"),70        Row(network: .sepolia, chainID: 11_155_111, symbol: "ETH", decimals: 18, isTest: true, explorer: "https://sepolia.etherscan.io"),71        Row(network: .base, chainID: 8_453, symbol: "ETH", decimals: 18, isTest: false, explorer: "https://basescan.org"),72        Row(network: .baseSepolia, chainID: 84_532, symbol: "ETH", decimals: 18, isTest: true, explorer: "https://sepolia.basescan.org"),73        Row(network: .arbitrum, chainID: 42_161, symbol: "ETH", decimals: 18, isTest: false, explorer: "https://arbiscan.io"),74        Row(network: .arbitrumSepolia, chainID: 421_614, symbol: "ETH", decimals: 18, isTest: true, explorer: "https://sepolia.arbiscan.io"),75        Row(network: .optimism, chainID: 10, symbol: "ETH", decimals: 18, isTest: false, explorer: "https://optimistic.etherscan.io"),76        Row(network: .optimismSepolia, chainID: 11_155_420, symbol: "ETH", decimals: 18, isTest: true, explorer: "https://sepolia-optimism.etherscan.io"),77        Row(network: .polygon, chainID: 137, symbol: "POL", decimals: 18, isTest: false, explorer: "https://polygonscan.com"),78        Row(network: .polygonAmoy, chainID: 80_002, symbol: "POL", decimals: 18, isTest: true, explorer: "https://amoy.polygonscan.com"),79        Row(network: .bsc, chainID: 56, symbol: "BNB", decimals: 18, isTest: false, explorer: "https://bscscan.com"),80        Row(network: .bscTestnet, chainID: 97, symbol: "BNB", decimals: 18, isTest: true, explorer: "https://testnet.bscscan.com"),81        Row(network: .avalanche, chainID: 43_114, symbol: "AVAX", decimals: 18, isTest: false, explorer: "https://snowtrace.io"),82        Row(network: .avalancheFuji, chainID: 43_113, symbol: "AVAX", decimals: 18, isTest: true, explorer: "https://testnet.snowtrace.io"),83    ]8485    @Test func networkTableMatchesTheChainRegistry() {86        var cases = 0, failed = 087        func check(_ ok: Bool, _ what: String) {88            cases += 189            if !ok {90                failed += 191                Issue.record("network table: \(what)")92            }93        }94        check(EthereumNetwork.allCases.count == Self.registry.count && Set(Self.registry.map(\.network)).count == 14, "fourteen networks")95        check(Set(EthereumNetwork.allCases.map(\.chainID)).count == 14, "chain identifiers are distinct")96        for row in Self.registry {97            let n = row.network98            check(n.chainID == row.chainID, "\(n) chain id \(n.chainID), registry \(row.chainID)")99            check(n.nativeSymbol == row.symbol, "\(n) symbol \(n.nativeSymbol)")100            check(n.nativeDecimals == row.decimals, "\(n) decimals \(n.nativeDecimals)")101            check(n.isTest == row.isTest, "\(n) test flag")102            check(n.explorerBaseURL == row.explorer, "\(n) explorer \(n.explorerBaseURL)")103            check(EthereumNetwork(chainID: row.chainID) == n, "\(n) lookup by chain id")104            check(n.nativeIsEther == (row.symbol == "ETH"), "\(n) ether flag")105            check(n.mainCounterpart.family == n.family && n.testCounterpart.family == n.family && !n.mainCounterpart.isTest && n.testCounterpart.isTest, "\(n) counterparts")106            check(MainnetPolicy.isMainnet(n) == !row.isTest, "\(n) is a mainnet for the gate")107            check(n.supportsEIP1559, "\(n) type-2 only")108            // an explorer link is built for a well-formed identifier only109            let hash = "0x" + String(repeating: "ab", count: 32)110            check(n.explorerTransactionURL(hash: hash)?.absoluteString == row.explorer + "/tx/" + hash, "\(n) transaction link")111            for bad in ["", "0x", hash + "0", String(hash.dropLast()), "0x" + String(repeating: "zz", count: 32), hash + "/../x", "0X" + String(repeating: "ab", count: 32), " " + hash] {112                check(n.explorerTransactionURL(hash: bad) == nil, "\(n) link for a malformed hash")113            }114            let address = "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed"115            check(n.explorerAddressURL(address: address)?.absoluteString == row.explorer + "/address/" + address, "\(n) address link")116            check(n.explorerAddressURL(address: address + "?x=1") == nil && n.explorerAddressURL(address: "0x") == nil, "\(n) link for a malformed address")117        }118        // an identifier the wallet does not support names no network119        for id in [0, 2, 3, 4, 5, 100, 250, 324, 1101, 5000, 59_144, 81_457, 534_352, 17_000, 80_001, 421_613, 1 << 31, 1 << 53, UInt64.max] as [UInt64] {120            check(EthereumNetwork(chainID: id) == nil, "chain \(id) must not name a network")121        }122        // the properties the fee rules read123        check(EthereumNetwork.allCases.filter(\.isOPStack).map(\.family).sorted { $0.rawValue < $1.rawValue } == [.base, .base, .optimism, .optimism], "OP-Stack networks")124        check(EthereumNetwork.allCases.filter(\.isArbitrum) == [.arbitrum, .arbitrumSepolia], "Arbitrum networks")125        check(EthereumNetwork.allCases.filter(\.hasZeroBaseFee) == [.bsc, .bscTestnet], "zero base fee networks")126        check(EthereumNetwork.allCases.filter { !$0.minimumPriorityFee.isZero } == [.polygon, .polygonAmoy], "minimum priority fee networks")127        check(EthereumNetwork.polygon.minimumPriorityFee == UInt256(30_000_000_000), "Polygon minimum tip")128        // the default endpoints: every network has two JSON-RPC endpoints of different hosts, all https, none with credentials129        for n in EthereumNetwork.allCases {130            let list = EVMEndpointDefaults.rpc[n.rawValue] ?? []131            let hosts = Set(list.compactMap { URL(string: $0)?.host })132            check(list.count == 2 && hosts.count == 2 && list.allSatisfy { $0.hasPrefix("https://") && EndpointConfiguration.isAcceptable($0) }, "\(n) default RPC endpoints")133            check((EVMEndpointDefaults.indexer[n.rawValue] ?? ["x"]).allSatisfy { $0.hasPrefix("https://") && EndpointConfiguration.isAcceptable($0) }, "\(n) default indexer")134        }135        check(Set(EVMEndpointDefaults.rpc.keys) == Set(EthereumNetwork.allCases.map(\.rawValue)), "no endpoint list for an unknown network")136        check(Set(EVMEndpointDefaults.indexer.keys) == Set(EthereumNetwork.allCases.map(\.rawValue)), "no indexer list for an unknown network")137        AuditRecorder.record(area: "conformance", name: "evm-network-table", algorithm: "EVM network table", parameterSet: "14 networks: chain id, native symbol, decimals, explorer, lookups, fee properties, default endpoints",138                             oracle: "ethereum-lists/chains, transcribed by the reviewer", cases: cases, failed: failed)139        #expect(failed == 0 && cases > 0)140    }141142    /// Constants of the OP-Stack fee oracle and of the ERC-20 calls, from the OP-Stack specification (predeploys) and143    /// from the Solidity ABI: the selector of `getL1Fee(bytes)` is 0x49948e0e and the oracle lives at144    /// 0x420000000000000000000000000000000000000F on every OP-Stack chain.145    @Test func opStackOracleAndSelectorConstants() {146        var cases = 0, failed = 0147        func check(_ ok: Bool, _ what: String) {148            cases += 1149            if !ok {150                failed += 1151                Issue.record("constants: \(what)")152            }153        }154        check(OPStackGasOracle.address.checksummed == "0x420000000000000000000000000000000000000F", "oracle address")155        check(EVMPredeploys.opStackGasPriceOracle == OPStackGasOracle.address.checksummed, "the two declarations of the oracle address agree")156        check(OPStackGasOracle.getL1FeeSelector == [0x49, 0x94, 0x8e, 0x0e], "getL1Fee(bytes) selector")157        check(ERC20.transferSelector == [0xa9, 0x05, 0x9c, 0xbb], "transfer selector")158        check(ERC20.approveSelector == [0x09, 0x5e, 0xa7, 0xb3], "approve selector")159        check(ERC20.balanceOfSelector == [0x70, 0xa0, 0x82, 0x31], "balanceOf selector")160        check(ERC20.allowanceSelector == [0xdd, 0x62, 0xed, 0x3e], "allowance selector")161        check(ERC20.decimalsSelector == [0x31, 0x3c, 0xe5, 0x67], "decimals selector")162        check(ERC20.symbolSelector == [0x95, 0xd8, 0x9b, 0x41], "symbol selector")163        check(ERC20.nameSelector == [0x06, 0xfd, 0xde, 0x03], "name selector")164        check(Hex.encode(ERC20.transferTopic) == "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "Transfer topic")165        check(Hex.encode(ERC20.approvalTopic) == "8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925", "Approval topic")166        // getL1Fee(0x02c0): selector, offset 32, length 2, the bytes padded to a word167        let call = OPStackGasOracle.getL1FeeCall([0x02, 0xc0])168        check(Hex.encode(call) == "49948e0e" + String(repeating: "0", count: 62) + "20" + String(repeating: "0", count: 63) + "2" + "02c0" + String(repeating: "0", count: 60), "getL1Fee call data")169        check(OPStackGasOracle.feeCeiling == UInt256(100_000_000_000_000_000), "L1 fee ceiling 0.1 ETH")170        check(EVMFeeRules.nativeTransferGas == 21_000, "gas of a transfer")171        check(EVMFeeRules.endpointFeePerGasCeiling == UInt256(10_000_000_000_000) && EVMFeeRules.maxFeePerGasCeiling == UInt256(100_000_000_000_000), "fee ceilings")172        // limits of an unaudited build: the figures the owner set, none raised173        let l = MainnetPolicy.limits174        check(l.etherWeiPerTransaction == UInt256(50_000_000_000_000_000) && l.etherFeeWeiPerTransaction == UInt256(10_000_000_000_000_000), "ether ceilings")175        check(l.tokenUSDPerTransaction == 150 && l.nativeUSDPerTransaction == 150 && MainnetPolicy.evmLimits.nativeFeeUSDPerTransaction == 5, "dollar ceilings")176        check(l.bitcoinSatoshisPerTransaction == 200_000 && l.bitcoinFeeSatoshisPerTransaction == 20_000 && l.bitcoinFeeRateSatPerVByte == 200, "bitcoin ceilings")177        check(!MainnetPolicy.auditCompleted, "the engine is not declared audited")178        AuditRecorder.record(area: "conformance", name: "evm-opstack-and-abi-constants", algorithm: "OP-Stack GasPriceOracle, ERC-20 ABI, policy constants",179                             oracle: "OP-Stack specification (predeploys), Solidity ABI, owner's limits", cases: cases, failed: failed)180        #expect(failed == 0 && cases > 0)181    }182183    /// Decimals of well-known tokens, pinned in the built-in lists: what the wallet shows next to the base units it signs.184    /// Expected values from each issuer's documentation as the reviewer knows them (Circle, Tether, Binance-Peg185    /// tokens with 18 decimals on BNB Smart Chain, wrapped bitcoin with 8, BTCB with 18).186    @Test func builtInTokenDecimals() {187        let expected: [(EthereumNetwork, String, String, Int)] = [188            (.base, "USDC", "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", 6), (.base, "WETH", "0x4200000000000000000000000000000000000006", 18),189            (.base, "cbBTC", "0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf", 8),190            (.arbitrum, "USDC", "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", 6), (.arbitrum, "USDC.e", "0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8", 6),191            (.arbitrum, "USDT0", "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9", 6), (.arbitrum, "WETH", "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1", 18),192            (.arbitrum, "WBTC", "0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f", 8), (.arbitrum, "ARB", "0x912CE59144191C1204E64559FE8253a0e49E6548", 18),193            (.optimism, "USDC", "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85", 6), (.optimism, "USDC.e", "0x7F5c764cBc14f9669B88837ca1490cCa17c31607", 6),194            (.optimism, "WETH", "0x4200000000000000000000000000000000000006", 18), (.optimism, "OP", "0x4200000000000000000000000000000000000042", 18),195            (.polygon, "USDC", "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", 6), (.polygon, "USDC.e", "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", 6),196            (.polygon, "USDT0", "0xc2132D05D31c914a87C6611C10748AEb04B58e8F", 6), (.polygon, "DAI", "0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063", 18),197            (.polygon, "WETH", "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619", 18), (.polygon, "WBTC", "0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6", 8),198            (.polygon, "WPOL", "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270", 18),199            (.bsc, "USDC", "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d", 18), (.bsc, "USDT", "0x55d398326f99059fF775485246999027B3197955", 18),200            (.bsc, "DAI", "0x1AF3F329e8BE154074D8769D1FFa4eE058B1DBc3", 18), (.bsc, "ETH", "0x2170Ed0880ac9A755fd29B2688956BD959F933F8", 18),201            (.bsc, "BTCB", "0x7130d2A12B9BCbFAe4f2634d864A1Ee1Ce3Ead9c", 18), (.bsc, "WBNB", "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c", 18),202            (.bsc, "CAKE", "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82", 18),203            (.avalanche, "USDC", "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E", 6), (.avalanche, "USDC.e", "0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664", 6),204            (.avalanche, "USDT", "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7", 6), (.avalanche, "WETH.e", "0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB", 18),205            (.avalanche, "BTC.b", "0x152b9d0FdC40C096757F570A51E494bd4b943E50", 8), (.avalanche, "WAVAX", "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7", 18),206            (.mainnet, "USDC", "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", 6), (.mainnet, "USDT", "0xdAC17F958D2ee523a2206206994597C13D831ec7", 6),207        ]208        var cases = 0, failed = 0209        func check(_ ok: Bool, _ what: String) {210            cases += 1211            if !ok {212                failed += 1213                Issue.record("built-in tokens: \(what)")214            }215        }216        for (network, symbol, address, decimals) in expected {217            let token = BuiltInTokens.tokens(for: network).first { $0.address.checksummed == address }218            check(token != nil, "\(network) \(symbol) at \(address) is not in the list")219            check(token?.decimals == decimals, "\(network) \(symbol): \(token?.decimals ?? -1) decimals, expected \(decimals)")220            check(token?.symbol == symbol, "\(network) \(address): symbol \(token?.symbol ?? "-"), expected \(symbol)")221        }222        for network in EthereumNetwork.allCases {223            let tokens = BuiltInTokens.tokens(for: network), rows = BuiltInTokens.table(for: network)224            // a row whose address is not written with its EIP-55 checksum is dropped: every row must have survived225            check(tokens.count == rows.count, "\(network): \(rows.count - tokens.count) row(s) dropped by the checksum rule")226            check(network.isTest ? tokens.isEmpty : !tokens.isEmpty, "\(network): built-in list presence")227            check(Set(tokens.map(\.address)).count == tokens.count && Set(tokens.map(\.symbol)).count == tokens.count, "\(network): one symbol, one contract")228            for t in tokens {229                check(t.network == network && !t.custom && !t.address.isZero && (0...18).contains(t.decimals), "\(network) \(t.symbol): shape")230                check(!t.symbol.isEmpty && t.symbol.count <= 16 && !t.name.isEmpty && t.name.count <= 48, "\(network) \(t.symbol): bounded text")231            }232        }233        AuditRecorder.record(area: "conformance", name: "evm-built-in-token-decimals", algorithm: "Built-in ERC-20 lists", parameterSet: "\(expected.count) pinned tokens on 7 main networks; every list checked for shape",234                             oracle: "issuers' documentation, transcribed by the reviewer", cases: cases, failed: failed)235        #expect(failed == 0 && cases > 0)236    }237}238
Files main
Menu

Theme