SPB Git

Repository Public

EthereumRPC.swift 19.6 KB 371 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraNetworking/EthereumRPC.swift8// Module           : Qyvora Networking9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// 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 QyvoraMath43import QyvoraCore44import QyvoraEthereum4546/// JSON-RPC 2.0 client of one EVM network (Ethereum, Base, Arbitrum, OP Mainnet, Polygon, BNB Smart Chain, Avalanche47/// and their test networks) over one or several endpoints. Nothing here assumes Ethereum: what differs between48/// networks (fee rules, L1 data fee, gas of a transfer, finality) is read from `network`.49public struct EthereumRPC: Sendable {50    let endpoints: [URL]51    let transport: HTTPTransport52    public let network: EthereumNetwork5354    public init(network: EthereumNetwork, configuration: EndpointConfiguration = .default, transport: HTTPTransport) {55        self.network = network56        endpoints = urls(configuration.ethereumRPC[network.rawValue] ?? [])57        self.transport = transport58    }5960    public var isConfigured: Bool { !endpoints.isEmpty }6162    private struct Envelope: Decodable {63        struct RPCError: Decodable { let code: Int; let message: String }64        let result: JSONValue?65        let error: RPCError?66    }6768    func call(_ method: String, _ params: [JSONValue], on endpoint: URL) async throws -> JSONValue {69        var r = URLRequest(url: endpoint)70        r.httpMethod = "POST"71        r.setValue("application/json", forHTTPHeaderField: "Content-Type")72        r.httpBody = try JSONEncoder().encode(JSONValue.object([73            "jsonrpc": .string("2.0"), "id": .number(1), "method": .string(method), "params": .array(params),74        ]))75        let (data, response) = try await transport.send(r)76        guard (200...299).contains(response.statusCode) else {77            throw NetworkError.http(status: response.statusCode, body: String(decoding: data.prefix(300), as: UTF8.self))78        }79        guard let env = try? JSONDecoder().decode(Envelope.self, from: data) else { throw NetworkError.invalidResponse(method) }80        if let e = env.error { throw NetworkError.rpc(code: e.code, message: String(e.message.prefix(300))) }81        return env.result ?? .null82    }8384    /// First endpoint that answers. A JSON-RPC error is an answer and is not retried elsewhere.85    public func call(_ method: String, _ params: [JSONValue] = []) async throws -> JSONValue {86        try await transport.firstSuccess(endpoints) { try await call(method, params, on: $0) }87    }8889    /// Asks every endpoint; all those that answer must agree, and at least one must answer.90    /// Used for values a single faulty endpoint must not decide alone (chain id, nonce).91    public func quorum(_ method: String, _ params: [JSONValue] = []) async throws -> JSONValue {92        guard !endpoints.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }93        var reference: (value: JSONValue, host: String)?94        var failures = [String]()95        for e in endpoints {96            do {97                let v = try await call(method, params, on: e)98                if let r = reference {99                    guard v == r.value else { throw NetworkError.disagreement("\(method): \(r.host) and \(e.host ?? "?") differ") }100                } else {101                    reference = (v, e.host ?? "?")102                }103            } catch let d as NetworkError {104                if case .disagreement = d { throw d }105                if case .rpc = d, reference == nil, e == endpoints.last { throw d }106                failures.append("\(e.host ?? "?"): \(d.summary)")107            } catch {108                failures.append("\(e.host ?? "?"): \(NetworkError.transportSummary(error))")109            }110        }111        guard let reference else { throw NetworkError.allEndpointsFailed(failures) }112        return reference.value113    }114115    static func quantity(_ v: JSONValue, _ what: String) throws -> UInt256 {116        guard let s = v.string, s.hasPrefix("0x"), let q = UInt256(hex: s) else { throw NetworkError.invalidResponse(what) }117        return q118    }119120    static func data(_ v: JSONValue, _ what: String) throws -> Bytes {121        guard let s = v.string, s.hasPrefix("0x"), let b = Hex.decode(String(s.dropFirst(2))) else { throw NetworkError.invalidResponse(what) }122        return b123    }124125    static func hex(_ b: Bytes) -> JSONValue { .string("0x" + Hex.encode(b)) }126127    /// Checks that every endpoint serves the expected chain.128    public func verifyChain() async throws {129        let id = try Self.quantity(try await quorum("eth_chainId"), "eth_chainId")130        guard id == UInt256(network.chainID) else { throw NetworkError.disagreement("endpoint serves chain \(id), expected \(network.chainID)") }131    }132133    public func blockNumber() async throws -> UInt64 {134        guard let n = try Self.quantity(try await call("eth_blockNumber"), "eth_blockNumber").uint64 else { throw NetworkError.invalidResponse("eth_blockNumber") }135        return n136    }137138    public func balance(of address: String) async throws -> UInt256 {139        try Self.quantity(try await call("eth_getBalance", [.string(address), .string("latest")]), "eth_getBalance")140    }141142    /// Transaction count at `tag` ("latest" or "pending"), agreed by all endpoints.143    public func transactionCount(of address: String, tag: String) async throws -> UInt64 {144        guard let n = try Self.quantity(try await quorum("eth_getTransactionCount", [.string(address), .string(tag)]), "eth_getTransactionCount").uint64 else {145            throw NetworkError.invalidResponse("eth_getTransactionCount")146        }147        return n148    }149150    /// What one endpoint answered.151    public struct EndpointCount: Equatable, Sendable {152        public let host: String153        public let count: UInt64154    }155156    /// Transaction count at `tag` as reported by each endpoint that answered (at least one), in configuration order.157    /// No agreement is required here: the caller decides what difference it accepts. Two honest endpoints can be a few158    /// transactions apart at the same instant on a busy account, because they are not at the same block.159    public func transactionCounts(of address: String, tag: String) async throws -> [EndpointCount] {160        guard !endpoints.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }161        var answers = [EndpointCount]()162        var failures = [String]()163        for e in endpoints {164            do {165                let v = try await call("eth_getTransactionCount", [.string(address), .string(tag)], on: e)166                guard let n = try Self.quantity(v, "eth_getTransactionCount").uint64 else { throw NetworkError.invalidResponse("eth_getTransactionCount") }167                answers.append(EndpointCount(host: e.host ?? "?", count: n))168            } catch let d as NetworkError {169                if case .offline = d { throw d }170                if case .rpc = d, answers.isEmpty, e == endpoints.last { throw d }171                failures.append("\(e.host ?? "?"): \(d.summary)")172            } catch {173                failures.append("\(e.host ?? "?"): \(NetworkError.transportSummary(error))")174            }175        }176        guard !answers.isEmpty else { throw NetworkError.allEndpointsFailed(failures) }177        return answers178    }179180    public func code(at address: String) async throws -> Bytes {181        try Self.data(try await call("eth_getCode", [.string(address), .string("latest")]), "eth_getCode")182    }183184    public func ethCall(to: String, data: Bytes, from: String? = nil) async throws -> Bytes {185        var tx: [String: JSONValue] = ["to": .string(to), "data": Self.hex(data)]186        if let from { tx["from"] = .string(from) }187        return try Self.data(try await call("eth_call", [.object(tx), .string("latest")]), "eth_call")188    }189190    public func estimateGas(from: String, to: String, value: UInt256, data: Bytes) async throws -> UInt64 {191        let tx: [String: JSONValue] = ["from": .string(from), "to": .string(to), "value": .string(value.hexQuantity), "data": Self.hex(data)]192        guard let g = try Self.quantity(try await call("eth_estimateGas", [.object(tx)]), "eth_estimateGas").uint64 else {193            throw NetworkError.invalidResponse("eth_estimateGas")194        }195        return g196    }197198    /// Fee figures as the endpoint reported them, bounded. `gasFees` turns them into the prices of a transaction199    /// with the rules of the network (`EVMFeeRules`).200    public struct FeeData: Equatable, Sendable {201        public let network: EthereumNetwork202        /// Base fee of the latest block (zero on BNB Smart Chain).203        public let baseFee: UInt256204        /// The endpoint's `eth_maxPriorityFeePerGas`, or 0.001 gwei when it does not implement the method.205        public let priorityFee: UInt256206        /// `eth_gasPrice`, read only on a network whose base fee is zero, where it is the floor of the price.207        public let gasPrice: UInt256?208209        public init(network: EthereumNetwork, baseFee: UInt256, priorityFee: UInt256, gasPrice: UInt256? = nil) {210            self.network = network211            self.baseFee = baseFee212            self.priorityFee = priorityFee213            self.gasPrice = gasPrice214        }215216        /// maxPriorityFeePerGas and maxFeePerGas for this network at the given speed: 2 × base fee + priority fee217        /// (covers five consecutive full blocks, +12.5 % each), the priority fee never below the network's minimum218        /// (Polygon) nor below `eth_gasPrice` where the base fee is zero (BNB Smart Chain).219        public func gasFees(speed: EVMFeeSpeed = .normal) throws -> EVMGasFees {220            do {221                return try EVMFeeRules.gasFees(network: network, baseFee: baseFee, suggestedPriorityFee: priorityFee, gasPrice: gasPrice, speed: speed)222            } catch EVMFeeError.missingGasPrice {223                throw NetworkError.invalidResponse("eth_gasPrice")224            } catch {225                throw NetworkError.invalidResponse("fee out of range")226            }227        }228229        /// maxFeePerGas at normal speed under the network's rules; the plain 2 × base fee + priority fee when the230        /// rules cannot be applied, saturating at 2^256 − 1 (a display figure: `gasFees` is what a transaction uses,231        /// and it refuses such values). Never traps, whatever the figures (QYV-SVC-083).232        public var maxFee: UInt256 {233            if let fees = try? gasFees() { return fees.maxFeePerGas }234            let (twice, o1) = baseFee.addingReportingOverflow(baseFee)235            let (sum, o2) = twice.addingReportingOverflow(priorityFee)236            return o1 || o2 ? .max : sum237        }238    }239240    public func feeData() async throws -> FeeData {241        let block = try await call("eth_getBlockByNumber", [.string("latest"), .bool(false)])242        guard let base = block["baseFeePerGas"] else { throw NetworkError.invalidResponse("baseFeePerGas") }243        let baseFee = try Self.quantity(base, "baseFeePerGas")244        var tip = EVMFeeRules.fallbackPriorityFee245        if let t = try? Self.quantity(try await call("eth_maxPriorityFeePerGas"), "eth_maxPriorityFeePerGas") { tip = t }246        // refuse absurd values from a faulty or hostile endpoint (above 10 000 gwei)247        let ceiling = EVMFeeRules.endpointFeePerGasCeiling248        guard baseFee < ceiling, tip < ceiling else { throw NetworkError.invalidResponse("fee out of range") }249        var gasPrice: UInt256?250        if network.hasZeroBaseFee {251            // BNB Smart Chain: validators refuse a price under their minimum, and the base fee (zero) says nothing about it252            let price = try Self.quantity(try await call("eth_gasPrice"), "eth_gasPrice")253            guard !price.isZero, price < ceiling else { throw NetworkError.invalidResponse("fee out of range") }254            gasPrice = price255        }256        return FeeData(network: network, baseFee: baseFee, priorityFee: tip, gasPrice: gasPrice)257    }258259    /// L1 data fee of a transaction on an OP-Stack network (Base, OP Mainnet and their test networks), in wei, read260    /// from the GasPriceOracle predeploy with the unsigned serialization (`EIP1559Transaction.unsignedPayload`).261    /// Zero, without any request, on a network that charges none: Ethereum, Polygon, BNB Smart Chain and Avalanche262    /// have no L1 fee, and on Arbitrum it is part of the gas estimate. The figure is a quote (it follows Ethereum's263    /// fees): reserve `OPStackGasOracle.withMargin` of it.264    public func l1DataFee(unsignedPayload: Bytes) async throws -> UInt256 {265        guard network.isOPStack else { return .zero }266        let returned = try await ethCall(to: OPStackGasOracle.address.checksummed, data: OPStackGasOracle.getL1FeeCall(unsignedPayload))267        guard let fee = OPStackGasOracle.decodeFee(returned) else { throw NetworkError.invalidResponse("L1 data fee") }268        return fee269    }270271    /// Gas of a transfer of the native coin to an account without code: 21 000 where that is a constant of the272    /// network, the endpoint's estimate on Arbitrum (it carries the L1 component and is higher). The estimate is273    /// returned as given, bounded to [21 000, 30 000 000]; the caller adds its margin.274    public func nativeTransferGas(from: String, to: String, value: UInt256) async throws -> UInt64 {275        if let fixed = EVMFeeRules.fixedNativeTransferGas(network) { return fixed }276        let estimate = try await estimateGas(from: from, to: to, value: value, data: [])277        guard estimate >= EVMFeeRules.nativeTransferGas, estimate <= 30_000_000 else { throw NetworkError.invalidResponse("eth_estimateGas") }278        return estimate279    }280281    /// Height of the last block the network holds final. The endpoint's "finalized" block is used when it serves282    /// the tag with a plausible answer (not above the head); otherwise, or when the tag is unknown to it, the head283    /// minus `EthereumNetwork.finalityConfirmations`. Never above the head, never negative.284    public func finalizedBlockNumber() async throws -> UInt64 {285        let head = try await blockNumber()286        let fallback = head > network.finalityConfirmations ? head - network.finalityConfirmations : 0287        do {288            let block = try await call("eth_getBlockByNumber", [.string("finalized"), .bool(false)])289            guard let number = block["number"], let n = try Self.quantity(number, "finalized block").uint64, n <= head else { return fallback }290            return n291        } catch let e as NetworkError {292            // an endpoint that does not know the tag answers a JSON-RPC error or something unreadable293            switch e {294            case .rpc, .invalidResponse: return fallback295            default: throw e296            }297        }298    }299300    /// Confirmations of a transaction mined in `blockNumber` when the head is `head` (1 for the head itself, 0 for a301    /// block the endpoint does not have yet). Saturates instead of overflowing on an absurd head.302    public static func confirmations(of blockNumber: UInt64, head: UInt64) -> UInt64 {303        guard head >= blockNumber else { return 0 }304        let (count, overflow) = (head - blockNumber).addingReportingOverflow(1)305        return overflow ? .max : count306    }307308    /// Broadcasts to every endpoint. Success when one accepts or already knows the transaction.309    public func sendRawTransaction(_ raw: Bytes) async throws -> String {310        guard !endpoints.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }311        var accepted: String?312        var failures = [String]()313        for e in endpoints {314            do {315                let v = try await call("eth_sendRawTransaction", [Self.hex(raw)], on: e)316                accepted = v.string ?? accepted ?? ""317            } catch NetworkError.rpc(_, let message)318                where message.range(of: "already known|already imported|ALREADY_EXISTS", options: [.regularExpression, .caseInsensitive]) != nil {319                accepted = accepted ?? ""320            } catch {321                failures.append("\(e.host ?? "?"): \(NetworkError.transportSummary(error))")322            }323        }324        guard let accepted else { throw NetworkError.allEndpointsFailed(failures) }325        return accepted326    }327328    public struct Receipt: Equatable, Sendable {329        public let blockNumber: UInt64330        public let success: Bool331        public let gasUsed: UInt64332        public let effectiveGasPrice: UInt256333    }334335    /// nil while the transaction is not mined.336    public func receipt(_ hash: String) async throws -> Receipt? {337        let v = try await call("eth_getTransactionReceipt", [.string(hash)])338        if v.isNull { return nil }339        guard let bn = v["blockNumber"], let st = v["status"], let gu = v["gasUsed"],340              let block = try Self.quantity(bn, "blockNumber").uint64, let gas = try Self.quantity(gu, "gasUsed").uint64 else {341            throw NetworkError.invalidResponse("receipt")342        }343        let price = (try? Self.quantity(v["effectiveGasPrice"] ?? .null, "effectiveGasPrice")) ?? .zero344        return Receipt(blockNumber: block, success: try Self.quantity(st, "status") == UInt256(1), gasUsed: gas, effectiveGasPrice: price)345    }346347    public struct Log: Equatable, Sendable {348        public let address: String349        public let topics: [Bytes]350        public let data: Bytes351        public let blockNumber: UInt64352        public let transactionHash: String353    }354355    public func logs(addresses: [String], topics: [Bytes?], fromBlock: UInt64, toBlock: UInt64) async throws -> [Log] {356        var filter: [String: JSONValue] = [357            "fromBlock": .string(UInt256(fromBlock).hexQuantity), "toBlock": .string(UInt256(toBlock).hexQuantity),358            "topics": .array(topics.map { $0.map(Self.hex) ?? .null }),359        ]360        if !addresses.isEmpty { filter["address"] = .array(addresses.map { .string($0) }) }361        guard let items = try await call("eth_getLogs", [.object(filter)]).array else { throw NetworkError.invalidResponse("eth_getLogs") }362        return try items.map { l in363            guard let a = l["address"]?.string, let t = l["topics"]?.array, let d = l["data"], let bn = l["blockNumber"],364                  let h = l["transactionHash"]?.string, let block = try Self.quantity(bn, "blockNumber").uint64 else {365                throw NetworkError.invalidResponse("log")366            }367            return Log(address: a, topics: try t.map { try Self.data($0, "topic") }, data: try Self.data(d, "data"), blockNumber: block, transactionHash: h)368        }369    }370}371
Files main
Menu

Theme