SPB Git

Repository Public

EVMNetworkingTests.swift 38.1 KB 610 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraNetworkingTests/EVMNetworkingTests.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/// A JSON-RPC server in memory: each request is answered by `answer(host, method, params)`; nil is a JSON-RPC49/// "method not found" error. Every call is recorded, so a test can check what was asked, and what was not.50final class ScriptedRPCTransport: HTTPTransport, @unchecked Sendable {51    struct Call: Equatable {52        let host: String53        let method: String54        let params: [JSONValue]55    }5657    private let lock = NSLock()58    private var recorded = [Call]()59    private let answer: @Sendable (String, String, [JSONValue]) -> JSONValue?6061    init(_ answer: @escaping @Sendable (String, String, [JSONValue]) -> JSONValue?) { self.answer = answer }6263    var calls: [Call] {64        lock.lock()65        defer { lock.unlock() }66        return recorded67    }6869    func methods(_ host: String? = nil) -> [String] { calls.filter { host == nil || $0.host == host }.map(\.method) }7071    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {72        guard let url = request.url, let body = request.httpBody, let json = try? JSONDecoder().decode(JSONValue.self, from: body),73              let method = json["method"]?.string, let params = json["params"]?.array,74              let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) else {75            throw NetworkError.invalidURL76        }77        let host = url.host ?? ""78        lock.withLock { recorded.append(Call(host: host, method: method, params: params)) }79        let envelope: JSONValue80        if let result = answer(host, method, params) {81            envelope = .object(["jsonrpc": .string("2.0"), "id": .number(1), "result": result])82        } else {83            envelope = .object(["jsonrpc": .string("2.0"), "id": .number(1),84                                "error": .object(["code": .number(-32601), "message": .string("the method \(method) does not exist")])])85        }86        return (try JSONEncoder().encode(envelope), response)87    }88}8990private func q(_ n: UInt64) -> JSONValue { .string(UInt256(n).hexQuantity) }91private func word(_ n: UInt64) -> JSONValue { .string("0x" + Hex.encode(UInt256(n).bytes32)) }92private func gwei(_ n: UInt64) -> UInt256 { UInt256(n * 1_000_000_000) }9394private func configuration(_ network: EthereumNetwork, hosts: [String] = ["a.invalid", "b.invalid"]) -> EndpointConfiguration {95    var c = EndpointConfiguration.default96    c.ethereumRPC = [network.rawValue: hosts.map { "https://\($0)" }]97    return c98}99100/// A node of `network` with the given fee figures.101private func node(_ network: EthereumNetwork, baseFee: UInt64, tip: UInt64?, gasPrice: UInt64? = nil, head: UInt64 = 1_000_000,102                  finalized: UInt64? = nil, estimate: UInt64? = nil, l1Fee: JSONValue? = nil) -> ScriptedRPCTransport {103    ScriptedRPCTransport { _, method, params in104        switch method {105        case "eth_chainId": return q(network.chainID)106        case "eth_blockNumber": return q(head)107        case "eth_getBlockByNumber":108            if params.first == .string("finalized") { return finalized.map { JSONValue.object(["number": q($0)]) } }109            return .object(["number": q(head), "baseFeePerGas": q(baseFee)])110        case "eth_maxPriorityFeePerGas": return tip.map(q)111        case "eth_gasPrice": return gasPrice.map(q)112        case "eth_estimateGas": return estimate.map(q)113        case "eth_call": return l1Fee114        default: return nil115        }116    }117}118119/// Fee data, L1 data fee, transfer gas and finality per network, against a scripted node. No network access.120@Suite struct EVMFeeDataTests {121    @Test func ethereumAndRollupsReadBaseFeeAndTipOnly() async throws {122        for network in [EthereumNetwork.mainnet, .sepolia, .base, .optimism, .arbitrum, .avalanche] {123            let transport = node(network, baseFee: 10_000_000_000, tip: 2_000_000_000, gasPrice: 999)124            let rpc = EthereumRPC(network: network, configuration: configuration(network), transport: transport)125            let fees = try await rpc.feeData()126            #expect(fees == EthereumRPC.FeeData(network: network, baseFee: gwei(10), priorityFee: gwei(2), gasPrice: nil))127            #expect(try fees.gasFees() == EVMGasFees(baseFee: gwei(10), maxPriorityFeePerGas: gwei(2), maxFeePerGas: gwei(22)))128            #expect(fees.maxFee == gwei(22))129            // eth_gasPrice is not asked where it decides nothing130            #expect(transport.methods() == ["eth_getBlockByNumber", "eth_maxPriorityFeePerGas"], "\(network)")131        }132    }133134    @Test func polygonMinimumTipIsApplied() async throws {135        for network in [EthereumNetwork.polygon, .polygonAmoy] {136            let rpc = EthereumRPC(network: network, configuration: configuration(network), transport: node(network, baseFee: 254_543_923_285, tip: 25_000_000_000))137            let fees = try await rpc.feeData()138            // the endpoint's own figure is kept as reported …139            #expect(fees.priorityFee == gwei(25))140            // … and the transaction carries the network minimum141            let normal = try fees.gasFees()142            #expect(normal.maxPriorityFeePerGas == gwei(30))143            #expect(normal.maxFeePerGas == UInt256(2 * 254_543_923_285 + 30_000_000_000))144            #expect(try fees.gasFees(speed: .slow).maxPriorityFeePerGas == gwei(30))145            #expect(try fees.gasFees(speed: .fast).maxPriorityFeePerGas == gwei(50))146            #expect(fees.maxFee == normal.maxFeePerGas)147        }148    }149150    @Test func bnbZeroBaseFeeReadsTheGasPrice() async throws {151        for network in [EthereumNetwork.bsc, .bscTestnet] {152            let transport = node(network, baseFee: 0, tip: 50_000_000, gasPrice: 50_000_000)153            let rpc = EthereumRPC(network: network, configuration: configuration(network), transport: transport)154            let fees = try await rpc.feeData()155            #expect(fees.baseFee == .zero && fees.gasPrice == UInt256(50_000_000))156            #expect(transport.methods() == ["eth_getBlockByNumber", "eth_maxPriorityFeePerGas", "eth_gasPrice"])157            for speed in EVMFeeSpeed.allCases {158                let gas = try fees.gasFees(speed: speed)159                // never under the validators' minimum, whatever the speed160                #expect(gas.maxFeePerGas >= UInt256(50_000_000) && gas.maxPriorityFeePerGas >= UInt256(50_000_000))161                #expect(gas.maxPriorityFeePerGas <= gas.maxFeePerGas)162            }163            #expect(try fees.gasFees(speed: .slow).maxFeePerGas == UInt256(50_000_000))164            #expect(try fees.gasFees(speed: .fast).maxFeePerGas == UInt256(100_000_000))165166            // a node that suggests no tip: the gas price still sets the floor167            let noTip = EthereumRPC(network: network, configuration: configuration(network), transport: node(network, baseFee: 0, tip: nil, gasPrice: 3_000_000_000))168            #expect(try await noTip.feeData().gasFees().maxFeePerGas == gwei(3))169170            // no gas price, a zero one or an absurd one: the fee data is refused171            for bad in [nil, 0, 10_000_000_000_000] as [UInt64?] {172                let broken = EthereumRPC(network: network, configuration: configuration(network), transport: node(network, baseFee: 0, tip: 1, gasPrice: bad))173                await #expect(throws: NetworkError.self) { try await broken.feeData() }174            }175        }176    }177178    @Test func absurdFeeFiguresAreRefusedOnEveryNetwork() async throws {179        for network in EthereumNetwork.allCases {180            let hugeBase = EthereumRPC(network: network, configuration: configuration(network), transport: node(network, baseFee: 10_000_000_000_000, tip: 1, gasPrice: 1))181            await #expect(throws: NetworkError.invalidResponse("fee out of range")) { try await hugeBase.feeData() }182            let hugeTip = EthereumRPC(network: network, configuration: configuration(network), transport: node(network, baseFee: 1, tip: 10_000_000_000_000, gasPrice: 1))183            await #expect(throws: NetworkError.invalidResponse("fee out of range")) { try await hugeTip.feeData() }184        }185        // a block without base fee is not a network QYVORA can price186        let legacy = ScriptedRPCTransport { _, method, _ in method == "eth_getBlockByNumber" ? .object(["number": q(1)]) : nil }187        let rpc = EthereumRPC(network: .mainnet, configuration: configuration(.mainnet), transport: legacy)188        await #expect(throws: NetworkError.invalidResponse("baseFeePerGas")) { try await rpc.feeData() }189    }190191    // MARK: OP-Stack L1 data fee192193    static let payload: Bytes = EIP1559Transaction(chainID: 8_453, nonce: 1, maxPriorityFeePerGas: UInt256(1_000_000), maxFeePerGas: UInt256(11_000_000),194                                                   gasLimit: 21_000, to: EthereumAddress("0x70997970C51812dc3A010C7d01b50e0d17dc79C8")!,195                                                   value: UInt256(1_000_000_000_000_000)).unsignedPayload196197    @Test func opStackL1FeeIsReadFromTheOracle() async throws {198        for network in [EthereumNetwork.base, .baseSepolia, .optimism, .optimismSepolia] {199            let transport = node(network, baseFee: 5_000_000, tip: 1_000_000, l1Fee: word(7_314_461_274))200            let rpc = EthereumRPC(network: network, configuration: configuration(network), transport: transport)201            #expect(try await rpc.l1DataFee(unsignedPayload: Self.payload) == UInt256(7_314_461_274))202            // one eth_call, to the GasPriceOracle predeploy, with getL1Fee(bytes) over the serialized transaction203            let calls = transport.calls204            #expect(calls.count == 1 && calls[0].method == "eth_call")205            let tx = try #require(calls[0].params.first)206            #expect(tx["to"]?.string == "0x420000000000000000000000000000000000000F")207            #expect(tx["data"]?.string == "0x" + Hex.encode(OPStackGasOracle.getL1FeeCall(Self.payload)))208            #expect(tx["data"]?.string?.hasPrefix("0x49948e0e") == true)209            #expect(calls[0].params.last == .string("latest"))210        }211    }212213    @Test func l1FeeIsZeroWithoutAnyRequestElsewhere() async throws {214        for network in EthereumNetwork.allCases where !network.isOPStack {215            let transport = node(network, baseFee: 1, tip: 1, l1Fee: word(123))216            let rpc = EthereumRPC(network: network, configuration: configuration(network), transport: transport)217            #expect(try await rpc.l1DataFee(unsignedPayload: Self.payload) == .zero, "\(network)")218            #expect(transport.calls.isEmpty)219        }220    }221222    @Test func implausibleOracleAnswersAreRefused() async throws {223        let answers: [JSONValue] = [224            .string("0x"),                                                        // no contract at the address225            .string("0x" + String(repeating: "00", count: 31)),                   // short word226            .string("0x" + String(repeating: "00", count: 64)),                   // two words227            .string("0x" + Hex.encode(OPStackGasOracle.feeCeiling.bytes32)),      // 0.1 ETH for one transaction228            .string("0x" + String(repeating: "ff", count: 32)),229            .string("not hexadecimal"),230        ]231        for answer in answers {232            let rpc = EthereumRPC(network: .base, configuration: configuration(.base), transport: node(.base, baseFee: 1, tip: 1, l1Fee: answer))233            await #expect(throws: NetworkError.self) { try await rpc.l1DataFee(unsignedPayload: Self.payload) }234        }235        // an oracle that reverts is a JSON-RPC error, reported as such236        let reverting = EthereumRPC(network: .optimism, configuration: configuration(.optimism), transport: node(.optimism, baseFee: 1, tip: 1, l1Fee: nil))237        await #expect(throws: NetworkError.self) { try await reverting.l1DataFee(unsignedPayload: Self.payload) }238    }239240    /// The cost shown and capped on an OP-Stack network is gas × price + L1 fee with its margin.241    @Test func opStackMaximumCostIncludesTheL1Fee() async throws {242        let rpc = EthereumRPC(network: .base, configuration: configuration(.base), transport: node(.base, baseFee: 5_000_000, tip: 1_000_000, l1Fee: word(8_000_000_000)))243        let gas = try await rpc.feeData().gasFees()244        #expect(gas.maxFeePerGas == UInt256(11_000_000))245        let to = EthereumAddress("0x70997970C51812dc3A010C7d01b50e0d17dc79C8")!246        let tx = EIP1559Transaction(chainID: 8_453, nonce: 0, maxPriorityFeePerGas: gas.maxPriorityFeePerGas, maxFeePerGas: gas.maxFeePerGas,247                                    gasLimit: 21_000, to: to, value: UInt256(1_000_000_000_000_000))248        let l1 = OPStackGasOracle.withMargin(try await rpc.l1DataFee(unsignedPayload: tx.unsignedPayload))249        #expect(l1 == UInt256(10_000_000_000))250        #expect(EVMFeeRules.maximumFee(gasLimit: tx.gasLimit, maxFeePerGas: tx.maxFeePerGas, l1DataFee: l1) == UInt256(241_000_000_000))251        #expect(EVMFeeRules.maximumCost(tx, l1DataFee: l1) == UInt256(1_000_241_000_000_000))252        // sending everything: what is left after gas and L1 fee, so that the three add up to the balance253        let balance = UInt256(1_000_000_000_000_000)254        let value = try #require(EVMFeeRules.sendMaxValue(balance: balance, gasLimit: 21_000, maxFeePerGas: gas.maxFeePerGas, l1DataFee: l1))255        #expect(value + UInt256(241_000_000_000) == balance)256    }257258    // MARK: Gas of a native transfer259260    @Test func arbitrumAlwaysEstimatesTheTransferGas() async throws {261        let from = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", to = "0x70997970C51812dc3A010C7d01b50e0d17dc79C8"262        for network in [EthereumNetwork.arbitrum, .arbitrumSepolia] {263            let transport = node(network, baseFee: 20_000_000, tip: 0, estimate: 21_815)264            let rpc = EthereumRPC(network: network, configuration: configuration(network), transport: transport)265            #expect(try await rpc.nativeTransferGas(from: from, to: to, value: UInt256(1)) == 21_815)266            #expect(transport.methods() == ["eth_estimateGas"])267            // an estimate under 21 000 or absurdly high is not used268            for bad in [20_999, 30_000_001] as [UInt64] {269                let broken = EthereumRPC(network: network, configuration: configuration(network), transport: node(network, baseFee: 1, tip: 0, estimate: bad))270                await #expect(throws: NetworkError.invalidResponse("eth_estimateGas")) { try await broken.nativeTransferGas(from: from, to: to, value: UInt256(1)) }271            }272            // no estimate, no fallback to 21 000273            let silent = EthereumRPC(network: network, configuration: configuration(network), transport: node(network, baseFee: 1, tip: 0, estimate: nil))274            await #expect(throws: NetworkError.self) { try await silent.nativeTransferGas(from: from, to: to, value: UInt256(1)) }275        }276    }277278    @Test func otherNetworksUseTheConstantWithoutAsking() async throws {279        for network in EthereumNetwork.allCases where !network.isArbitrum {280            let transport = node(network, baseFee: 1, tip: 1, estimate: 99_999)281            let rpc = EthereumRPC(network: network, configuration: configuration(network), transport: transport)282            #expect(try await rpc.nativeTransferGas(from: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", to: "0x70997970C51812dc3A010C7d01b50e0d17dc79C8", value: UInt256(1)) == 21_000)283            #expect(transport.calls.isEmpty, "\(network)")284        }285    }286287    // MARK: Finality288289    @Test func finalizedTagIsUsedWhenServed() async throws {290        for network in EthereumNetwork.allCases {291            let rpc = EthereumRPC(network: network, configuration: configuration(network), transport: node(network, baseFee: 1, tip: 1, head: 1_000_000, finalized: 999_990))292            #expect(try await rpc.finalizedBlockNumber() == 999_990)293        }294    }295296    @Test func finalityFallsBackToTheNetworkHint() async throws {297        for network in EthereumNetwork.allCases {298            // the tag is unknown to the endpoint (JSON-RPC error)299            let unknown = EthereumRPC(network: network, configuration: configuration(network), transport: node(network, baseFee: 1, tip: 1, head: 1_000_000, finalized: nil))300            #expect(try await unknown.finalizedBlockNumber() == 1_000_000 - network.finalityConfirmations, "\(network)")301            // a "finalized" block above the head is not believed302            let ahead = EthereumRPC(network: network, configuration: configuration(network), transport: node(network, baseFee: 1, tip: 1, head: 1_000_000, finalized: 1_000_001))303            #expect(try await ahead.finalizedBlockNumber() == 1_000_000 - network.finalityConfirmations)304            // a young chain: never below zero305            let young = EthereumRPC(network: network, configuration: configuration(network), transport: node(network, baseFee: 1, tip: 1, head: 1, finalized: nil))306            #expect(try await young.finalizedBlockNumber() == 0)307        }308        // the answer is null (tag known, nothing finalized yet)309        let null = ScriptedRPCTransport { _, method, params in310            switch method {311            case "eth_blockNumber": return q(5_000)312            case "eth_getBlockByNumber": return .null313            default: return nil314            }315        }316        let rpc = EthereumRPC(network: .bsc, configuration: configuration(.bsc), transport: null)317        #expect(try await rpc.finalizedBlockNumber() == 5_000 - 15)318        // the fallback of Ethereum is not the fallback of the others319        #expect(EthereumNetwork.mainnet.finalityConfirmations != EthereumNetwork.avalanche.finalityConfirmations)320    }321322    @Test func confirmationsCount() {323        #expect(EthereumRPC.confirmations(of: 100, head: 100) == 1)324        #expect(EthereumRPC.confirmations(of: 90, head: 100) == 11)325        #expect(EthereumRPC.confirmations(of: 101, head: 100) == 0)326        #expect(EthereumRPC.confirmations(of: 0, head: .max) == .max)327    }328}329330/// Chain identity: every endpoint must serve the chain the wallet believes it is on.331@Suite struct EVMChainIdentityTests {332    @Test func theRightChainIsAccepted() async throws {333        for network in EthereumNetwork.allCases {334            let transport = node(network, baseFee: 1, tip: 1)335            let rpc = EthereumRPC(network: network, configuration: configuration(network), transport: transport)336            try await rpc.verifyChain()337            // both endpoints were asked338            #expect(Set(transport.calls.map(\.host)) == ["a.invalid", "b.invalid"])339        }340    }341342    /// An endpoint that serves another chain is refused, including the main network of the same family, the343    /// test network, and Ethereum itself: a transaction signed for one chain must never be prepared from another's data.344    @Test func aWrongChainIsRefused() async throws {345        for network in EthereumNetwork.allCases {346            let others: [EthereumNetwork] = [network.isTest ? network.mainCounterpart : network.testCounterpart, network == .mainnet ? .base : .mainnet]347            for other in others {348                let rpc = EthereumRPC(network: network, configuration: configuration(network), transport: node(other, baseFee: 1, tip: 1))349                await #expect(throws: NetworkError.disagreement("endpoint serves chain \(other.chainID), expected \(network.chainID)")) { try await rpc.verifyChain() }350            }351        }352    }353354    @Test func endpointsThatDisagreeAreRefused() async throws {355        // one honest Base endpoint, one that answers Ethereum's identifier356        let transport = ScriptedRPCTransport { host, method, _ in357            method == "eth_chainId" ? q(host == "a.invalid" ? 8_453 : 1) : nil358        }359        let rpc = EthereumRPC(network: .base, configuration: configuration(.base), transport: transport)360        await #expect(throws: NetworkError.disagreement("eth_chainId: a.invalid and b.invalid differ")) { try await rpc.verifyChain() }361        // a network without endpoint has no identity362        var empty = EndpointConfiguration.default363        empty.ethereumRPC = [:]364        let none = EthereumRPC(network: .polygon, configuration: empty, transport: transport)365        #expect(!none.isConfigured)366        await #expect(throws: NetworkError.self) { try await none.verifyChain() }367    }368}369370/// Default endpoints and the compatibility of stored configurations.371@Suite struct EVMEndpointConfigurationTests {372    @Test func everyNetworkHasTwoAcceptableRPCEndpoints() {373        let defaults = EndpointConfiguration.default374        #expect(Set(defaults.ethereumRPC.keys) == Set(EthereumNetwork.allCases.map(\.rawValue)))375        #expect(Set(defaults.ethereumIndexer.keys) == Set(EthereumNetwork.allCases.map(\.rawValue)))376        var hosts = Set<String>()377        for network in EthereumNetwork.allCases {378            let list = defaults.ethereumRPC[network.rawValue] ?? []379            #expect(list.count >= 2, "\(network)")380            #expect(list.allSatisfy { $0.hasPrefix("https://") && EndpointConfiguration.isAcceptable($0) })381            // two different operators (different registrable hosts), so that the quorum means something382            let operators = Set(list.compactMap { URL(string: $0)?.host?.split(separator: ".").suffix(2).joined(separator: ".") })383            #expect(operators.count == list.count, "\(network)")384            for url in list { #expect(hosts.insert(url).inserted, "endpoint used twice: \(url)") }385            #expect(EthereumRPC(network: network, transport: FixedBodyTransport(body: "")).isConfigured)386            // no key, token or credential in a default387            #expect(list.allSatisfy { !$0.contains("?") && !$0.lowercased().contains("key") })388        }389    }390391    @Test func indexersAreDeclaredOnlyWhereOneWasVerified() {392        let with: Set<EthereumNetwork> = [.mainnet, .sepolia, .baseSepolia, .optimism, .optimismSepolia, .avalanche, .avalancheFuji]393        for network in EthereumNetwork.allCases {394            let list = EndpointConfiguration.default.ethereumIndexer[network.rawValue] ?? []395            #expect(list.isEmpty == !with.contains(network), "\(network)")396            #expect(EVMEndpointDefaults.hasDefaultIndexer(network) == with.contains(network))397            #expect(list.allSatisfy(EndpointConfiguration.isAcceptable))398            #expect(EthereumIndexer(network: network, transport: FixedBodyTransport(body: "")).isConfigured == with.contains(network))399        }400        #expect(EVMEndpointDefaults.noKeylessIndexerReason == "no keyless indexer for this network")401        #expect(EVMEndpointDefaults.checkedOn == "2026-12-05")402    }403404    /// The configuration a profile of version 1.0 holds: two Bitcoin test networks, Ethereum and Sepolia.405    static let storedByVersion1 = """406    {"esplora":{"mainnet":["https://mempool.space/api","https://blockstream.info/api"],407                "testnet":["https://mempool.space/testnet/api"],408                "signet":["https://my-node.local:3002/api"]},409     "ethereumRPC":{"mainnet":["https://my-own-node.example/rpc"],410                    "sepolia":["https://ethereum-sepolia-rpc.publicnode.com","https://sepolia.gateway.tenderly.co"]},411     "ethereumIndexer":{"mainnet":[],"sepolia":["https://eth-sepolia.blockscout.com"]},412     "priceAPI":""}413    """414415    @Test func aStoredConfigurationKeepsItsChoicesAndGainsTheNewNetworks() throws {416        let decoded = try JSONDecoder().decode(EndpointConfiguration.self, from: Data(Self.storedByVersion1.utf8))417        // what the user had set is untouched: a personal node, a disabled indexer, a disabled price source418        #expect(decoded.ethereumRPC["mainnet"] == ["https://my-own-node.example/rpc"])419        #expect(decoded.ethereumRPC["sepolia"] == ["https://ethereum-sepolia-rpc.publicnode.com", "https://sepolia.gateway.tenderly.co"])420        #expect(decoded.ethereumIndexer["mainnet"] == [])421        #expect(decoded.ethereumIndexer["sepolia"] == ["https://eth-sepolia.blockscout.com"])422        #expect(decoded.priceAPI == "")423        #expect(decoded.esplora["signet"] == ["https://my-node.local:3002/api"])424        #expect(decoded.esplora["testnet"] == ["https://mempool.space/testnet/api"])425        // the networks it did not know receive their defaults426        for network in EthereumNetwork.allCases where network != .mainnet && network != .sepolia {427            #expect(decoded.ethereumRPC[network.rawValue] == EndpointConfiguration.default.ethereumRPC[network.rawValue], "\(network)")428            #expect(decoded.ethereumIndexer[network.rawValue] == EndpointConfiguration.default.ethereumIndexer[network.rawValue], "\(network)")429            #expect(EthereumRPC(network: network, configuration: decoded, transport: FixedBodyTransport(body: "")).isConfigured)430        }431    }432433    @Test func encodingRoundTripsAndMissingFieldsTakeDefaults() throws {434        let defaults = EndpointConfiguration.default435        #expect(try JSONDecoder().decode(EndpointConfiguration.self, from: try JSONEncoder().encode(defaults)) == defaults)436        var custom = defaults437        custom.ethereumRPC["base"] = []438        custom.ethereumIndexer["avalanche"] = ["https://indexer.example/api"]439        custom.priceAPI = "https://prices.example/api/v3"440        #expect(try JSONDecoder().decode(EndpointConfiguration.self, from: try JSONEncoder().encode(custom)) == custom)441        // an emptied list stays empty: the user's choice is not overwritten by a default442        #expect(try JSONDecoder().decode(EndpointConfiguration.self, from: try JSONEncoder().encode(custom)).ethereumRPC["base"] == [])443        // a configuration written by this version is read back exactly, also when it names fewer networks: nothing444        // is added to what the user (or a test harness) decided445        let partial = EndpointConfiguration(esplora: [:], ethereumRPC: ["sepolia": ["https://rpc.example"]], ethereumIndexer: [:], priceAPI: "")446        let stored = try JSONEncoder().encode(partial)447        #expect(try JSONDecoder().decode(EndpointConfiguration.self, from: stored) == partial)448        #expect((try JSONDecoder().decode(JSONValue.self, from: stored))["schema"] == .number(2))449        // the same lists without the schema marker are a version 1.0 value: the new networks are added450        let legacy = try JSONDecoder().decode(EndpointConfiguration.self, from: Data(#"{"esplora":{},"ethereumRPC":{"sepolia":["https://rpc.example"]},"ethereumIndexer":{},"priceAPI":""}"#.utf8))451        #expect(legacy.ethereumRPC["sepolia"] == ["https://rpc.example"] && legacy.ethereumRPC["base"] == defaults.ethereumRPC["base"])452        #expect(legacy.ethereumRPC.count == 14 && legacy.priceAPI == "")453        // an object without any field is the default configuration454        #expect(try JSONDecoder().decode(EndpointConfiguration.self, from: Data("{}".utf8)) == defaults)455        // a field of the wrong type is still an error456        #expect(throws: (any Error).self) { try JSONDecoder().decode(EndpointConfiguration.self, from: Data(#"{"ethereumRPC":"x"}"#.utf8)) }457    }458}459460/// The Etherscan dialect of the indexer client (Routescan for Avalanche).461@Suite struct EtherscanDialectTests {462    static let owner = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045"463464    /// Records the URL asked and answers a fixed body.465    final class RecordingTransport: HTTPTransport, @unchecked Sendable {466        private let lock = NSLock()467        private var seen = [URL]()468        let body: @Sendable (URL) -> (Int, String)469        init(_ body: @escaping @Sendable (URL) -> (Int, String)) { self.body = body }470        var urls: [URL] {471            lock.lock()472            defer { lock.unlock() }473            return seen474        }475        func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {476            guard let url = request.url else { throw NetworkError.invalidURL }477            lock.withLock { seen.append(url) }478            let (status, text) = body(url)479            return (Data(text.utf8), HTTPURLResponse(url: url, statusCode: status, httpVersion: nil, headerFields: nil)!)480        }481    }482483    static func indexer(_ transport: HTTPTransport, bases: [String] = ["https://api.routescan.io/v2/network/mainnet/evm/43114/etherscan/api"]) -> EthereumIndexer {484        var c = EndpointConfiguration.default485        c.ethereumIndexer = ["avalanche": bases]486        return EthereumIndexer(network: .avalanche, configuration: c, transport: transport)487    }488489    @Test func dialectFollowsTheBasePath() {490        func d(_ s: String) -> EthereumIndexer.Dialect { EthereumIndexer.dialect(of: URL(string: s)!) }491        #expect(d("https://eth.blockscout.com") == .blockscout)492        #expect(d("https://explorer.optimism.io") == .blockscout)493        #expect(d("https://explorer.example/") == .blockscout)494        #expect(d("https://api.routescan.io/v2/network/mainnet/evm/43114/etherscan/api") == .etherscan)495        #expect(d("https://eth.blockscout.com/api") == .etherscan)496        #expect(d("https://eth.blockscout.com/api/") == .etherscan)497        #expect(d("https://indexer.example/api?apikey=mine") == .etherscan)498        // every default is in the dialect its host was checked with499        for network in [EthereumNetwork.avalanche, .avalancheFuji] {500            #expect((EndpointConfiguration.default.ethereumIndexer[network.rawValue] ?? []).allSatisfy { d($0) == .etherscan })501        }502        for network in [EthereumNetwork.mainnet, .sepolia, .baseSepolia, .optimism, .optimismSepolia] {503            #expect((EndpointConfiguration.default.ethereumIndexer[network.rawValue] ?? []).allSatisfy { d($0) == .blockscout })504        }505    }506507    /// Rows in the shape Routescan returned on 2026-12-05 (values shortened).508    @Test func nativeTransactionsAreParsed() async throws {509        let hash = "0x193b5926782f2eb24f985b8ddecbeb77da196cf264d4800077538ce12792fcc0"510        let transport = RecordingTransport { _ in (200, """511        {"status":"1","message":"OK","result":[512          {"blockNumber":"93681382","timeStamp":"1787695223","hash":"\(hash)","nonce":"4","from":"0x9719c66f4f425203812c2ce665eba045c636cd9a",513           "to":"\(Self.owner)","value":"1360534962347194","gas":"21000","gasPrice":"2065031586","input":"0x","methodId":"0x","functionName":"",514           "contractAddress":"","txreceipt_status":"1","gasUsed":"21000","isError":"0"},515          {"blockNumber":"93681383","timeStamp":"1787695224","hash":"\(hash)","from":"\(Self.owner)","to":"","value":"0","gasPrice":"1000","gasUsed":"50000",516           "functionName":"approve(address spender, uint256 amount)","txreceipt_status":"0","isError":"1"},517          {"hash":"\(hash)","from":"not an address","to":"\(Self.owner)","value":"1"},518          {"hash":"\(hash)","from":"\(Self.owner)","to":"\(Self.owner)","value":"-1"}519        ]}520        """) }521        let txs = try await Self.indexer(transport).transactions(of: Self.owner)522        #expect(txs.count == 2)523        #expect(txs[0].kind == .native && txs[0].hash == hash && txs[0].to == Self.owner && txs[0].value == UInt256(1_360_534_962_347_194))524        #expect(txs[0].blockNumber == 93_681_382 && txs[0].success && txs[0].method == nil)525        #expect(txs[0].timestamp == Date(timeIntervalSince1970: 1_787_695_223))526        #expect(txs[0].fee == UInt256(21_000 * 2_065_031_586))527        #expect(!txs[1].success && txs[1].to == "" && txs[1].method == "approve" && txs[1].fee == UInt256(50_000_000))528        let url = try #require(transport.urls.first)529        #expect(url.absoluteString == "https://api.routescan.io/v2/network/mainnet/evm/43114/etherscan/api?module=account&action=txlist&address=\(Self.owner)&page=1&offset=50&sort=desc")530    }531532    @Test func tokenTransfersAndHoldingsAreParsed() async throws {533        let hash = "0x907a30dd685e889c593638dfa6df548c8aaa73bdf5e5e166c51a0db57410263a"534        let transport = RecordingTransport { url in535            if url.absoluteString.contains("action=tokentx") {536                return (200, """537                {"status":"1","message":"OK","result":[538                  {"blockNumber":"100987121","timeStamp":"1795272349","hash":"\(hash)","from":"0xbbba8fe166f661863fe032b6f89c8952f4954451",539                   "contractAddress":"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E","to":"\(Self.owner)","value":"1043756","tokenName":"USD Coin",540                   "tokenSymbol":"USDC","tokenDecimal":"6"},541                  {"hash":"\(hash)","from":"\(Self.owner)","to":"\(Self.owner)","value":"1","contractAddress":""},542                  {"hash":"\(hash)","from":"\(Self.owner)","to":"\(Self.owner)","value":"5","contractAddress":"\(Self.owner)","tokenDecimal":"1e9","timeStamp":"99999999999999"}543                ]}544                """)545            }546            return (200, """547            {"status":"1","message":"OK","result":[548              {"TokenAddress":"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7","TokenName":"TetherToken","TokenSymbol":"USDt","TokenQuantity":"2002129","TokenDivisor":"6"},549              {"TokenAddress":"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E","TokenName":"USD Coin","TokenSymbol":"USDC","TokenQuantity":"1043756","TokenDivisor":"6"},550              {"TokenAddress":"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E","TokenQuantity":"1","TokenDivisor":"77"},551              {"TokenAddress":"nope","TokenQuantity":"1","TokenDivisor":"6"}552            ]}553            """)554        }555        let indexer = Self.indexer(transport)556        let transfers = try await indexer.tokenTransfers(of: Self.owner)557        #expect(transfers.count == 2)558        #expect(transfers[0].kind == .token && transfers[0].tokenAddress == "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E" && transfers[0].value == UInt256(1_043_756))559        #expect(transfers[0].tokenSymbol == "USDC" && transfers[0].tokenDecimals == 6 && transfers[0].blockNumber == 100_987_121)560        // hostile figures give nil, never a trap561        #expect(transfers[1].tokenDecimals == nil && transfers[1].timestamp == nil && transfers[1].blockNumber == nil)562        let holdings = try await indexer.tokenHoldings(of: Self.owner)563        #expect(holdings.count == 2)564        #expect(holdings[0] == EthereumIndexer.TokenHolding(address: "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7", symbol: "USDt", name: "TetherToken", decimals: 6, balance: UInt256(2_002_129)))565        #expect(transport.urls.last?.query == "module=account&action=addresstokenbalance&address=\(Self.owner)&page=1&offset=100")566    }567568    @Test func emptyAccountsAndRefusals() async throws {569        // an account without rows: status "0" with an empty list is an empty history, not an error570        let empty = RecordingTransport { _ in (200, #"{"status":"0","message":"No transactions found","result":[]}"#) }571        #expect(try await Self.indexer(empty).transactions(of: Self.owner).isEmpty)572        #expect(try await Self.indexer(empty).tokenTransfers(of: Self.owner).isEmpty)573        // a refusal carries no list: it is an error, never an empty history574        for body in [#"{"status":"0","message":"chain not supported"}"#, #"{"status":"0","message":"NOTOK","result":"Max rate limit reached"}"#,575                     "<!DOCTYPE html><html><head><title>Just a moment...</title>", #"{"status":"0","message":"NOTOK","result":[{"hash":"0x00"}]}"#] {576            let refused = RecordingTransport { _ in (200, body) }577            await #expect(throws: NetworkError.self) { try await Self.indexer(refused).transactions(of: Self.owner) }578        }579        // HTTP 403 (a browser challenge) is an error too580        let challenged = RecordingTransport { _ in (403, "<!DOCTYPE html>") }581        await #expect(throws: NetworkError.self) { try await Self.indexer(challenged).transactions(of: Self.owner) }582        // the address is checked before anything is sent583        await #expect(throws: NetworkError.invalidURL) { try await Self.indexer(empty).transactions(of: "0x12&apikey=x") }584    }585586    @Test func aBaseWithAQueryKeepsItAndBlockscoutFallbackStillWorks() async throws {587        let transport = RecordingTransport { url in588            url.host == "down.example" ? (500, "") : (200, #"{"items":[]}"#)589        }590        // first base (Etherscan dialect, with the user's own key) is down; the second is a Blockscout host591        let indexer = Self.indexer(transport, bases: ["https://down.example/api?apikey=mine", "https://blockscout.example"])592        #expect(try await indexer.transactions(of: Self.owner).isEmpty)593        #expect(transport.urls.map(\.absoluteString) == [594            "https://down.example/api?apikey=mine&module=account&action=txlist&address=\(Self.owner)&page=1&offset=50&sort=desc",595            "https://blockscout.example/api/v2/addresses/\(Self.owner)/transactions",596        ])597    }598599    /// A network without indexer asks nothing and invents nothing.600    @Test func noIndexerMeansNoRequest() async throws {601        let transport = RecordingTransport { _ in (200, #"{"items":[]}"#) }602        for network in [EthereumNetwork.base, .arbitrum, .arbitrumSepolia, .polygon, .polygonAmoy, .bsc, .bscTestnet] {603            let indexer = EthereumIndexer(network: network, transport: transport)604            #expect(!indexer.isConfigured)605            await #expect(throws: NetworkError.allEndpointsFailed(["no endpoint configured"])) { try await indexer.transactions(of: Self.owner) }606        }607        #expect(transport.urls.isEmpty)608    }609}610
Files main
Menu

Theme