SPB Git

Repository Public

EVMLiveTests.swift 7.1 KB 134 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraNetworkingTests/EVMLiveTests.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 QyvoraEthereum46@testable import QyvoraNetworking4748/// Opt-in check of every default EVM endpoint: `QYVORA_LIVE=1 swift test --filter EVMLiveTests`.49/// Read-only requests about public chain data: no key, no signature, no broadcast.50@Suite(.enabled(if: ProcessInfo.processInfo.environment["QYVORA_LIVE"] == "1"), .serialized)51struct EVMLiveTests {52    let transport = URLSessionTransport(timeout: 20)53    /// A well-known public address (it exists on every EVM network, as any address does).54    static let address = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"5556    private func gwei(_ wei: UInt256) -> String { BaseUnits.format(wei, decimals: 9, maxFractionDigits: 6) }5758    @Test func everyNetwork() async throws {59        print("EVM live check, endpoints verified on \(EVMEndpointDefaults.checkedOn):")60        for network in EthereumNetwork.mainNetworks + EthereumNetwork.testNetworks {61            let rpc = EthereumRPC(network: network, transport: transport)62            #expect(rpc.endpoints.count >= 2, "\(network)")63            // every endpoint alone serves the expected chain …64            for endpoint in rpc.endpoints {65                let id = try EthereumRPC.quantity(try await rpc.call("eth_chainId", [], on: endpoint), "eth_chainId")66                #expect(id == UInt256(network.chainID), "\(network) \(endpoint.host ?? "")")67            }68            // … and they agree (the check the wallet makes before using a network)69            try await rpc.verifyChain()70            let head = try await rpc.blockNumber()71            #expect(head > 1_000)72            let finalized = try await rpc.finalizedBlockNumber()73            #expect(finalized <= head)74            let balance = try await rpc.balance(of: Self.address)75            let fees = try await rpc.feeData()76            let gas = try fees.gasFees()77            #expect(gas.maxPriorityFeePerGas <= gas.maxFeePerGas && gas.maxPriorityFeePerGas >= network.minimumPriorityFee)78            if network.hasZeroBaseFee { #expect(fees.gasPrice != nil && gas.maxFeePerGas >= fees.gasPrice!) }79            let transferGas = try await rpc.nativeTransferGas(from: Self.address, to: "0x000000000000000000000000000000000000dEaD", value: UInt256(1))80            #expect(transferGas >= 21_000)81            var line = "  \(network.rawValue) chain \(network.chainID) OK on \(rpc.endpoints.count) endpoints | head \(head), finalized \(head - finalized) behind"82            line += " | balance \(BaseUnits.format(balance, decimals: 18, maxFractionDigits: 6)) \(network.nativeSymbol)"83            line += " | base \(gwei(fees.baseFee)) tip \(gwei(fees.priorityFee))"84            if let price = fees.gasPrice { line += " gasPrice \(gwei(price))" }85            line += " -> maxFee \(gwei(gas.maxFeePerGas)) priority \(gwei(gas.maxPriorityFeePerGas)) gwei | transfer gas \(transferGas)"86            if network.isOPStack {87                let tx = EIP1559Transaction(chainID: network.chainID, nonce: 0, maxPriorityFeePerGas: gas.maxPriorityFeePerGas, maxFeePerGas: gas.maxFeePerGas,88                                            gasLimit: transferGas, to: EthereumAddress("0x000000000000000000000000000000000000dEaD")!, value: UInt256(1))89                let l1 = try await rpc.l1DataFee(unsignedPayload: tx.unsignedPayload)90                #expect(!l1.isZero)91                line += " | L1 data fee \(l1) wei"92            } else {93                #expect(try await rpc.l1DataFee(unsignedPayload: [0x02]) == .zero)94            }95            let indexer = EthereumIndexer(network: network, transport: transport)96            #expect(indexer.isConfigured == EVMEndpointDefaults.hasDefaultIndexer(network))97            if indexer.isConfigured {98                let txs = try await indexer.transactions(of: Self.address)99                let transfers = try await indexer.tokenTransfers(of: Self.address)100                #expect(txs.allSatisfy { $0.hash.hasPrefix("0x") })101                line += " | history: \(txs.count) transactions, \(transfers.count) token transfers (\(indexer.bases.first?.host ?? ""))"102            } else {103                line += " | history: \(EVMEndpointDefaults.noKeylessIndexerReason)"104            }105            print(line)106        }107    }108109    /// Every built-in token answers the decimals the list states, on its own network.110    @Test func builtInTokensMatchTheChain() async throws {111        for network in EthereumNetwork.mainNetworks {112            let rpc = EthereumRPC(network: network, transport: transport)113            var checked = 0114            for token in BuiltInTokens.tokens(for: network) {115                #expect(!(try await rpc.code(at: token.address.checksummed)).isEmpty, "\(network) \(token.symbol): no contract")116                let decimals = ERC20.decodeUInt(try await rpc.ethCall(to: token.address.checksummed, data: ERC20.decimalsSelector))117                #expect(decimals == UInt256(UInt64(token.decimals)), "\(network) \(token.symbol)")118                checked += 1119            }120            print("  \(network.rawValue): \(checked) built-in tokens, decimals confirmed on chain")121        }122    }123124    @Test func nativeCoinPrices() async throws {125        let ids = Array(Set(EthereumNetwork.mainNetworks.map(\.priceID))).sorted()126        let quotes = try await PriceClient(transport: transport).quotes(ids: ids)127        for id in ids {128            let quote = try #require(quotes[id], "no price for \(id)")129            #expect(quote.price > 0)130        }131        print("  native coin prices found for:", ids.joined(separator: ", "))132    }133}134
Files main
Menu

Theme