SPB Git

Repository Public

Indexers.swift 23.1 KB 397 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraNetworking/Indexers.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 QyvoraCore4344/// History and token discovery of an EVM account (public JSON-RPC endpoints cannot scan history).45///46/// Two dialects are spoken, chosen per base URL:47/// - Blockscout API v2 (`<base>/api/v2/addresses/…`): any base whose path does not end in "/api";48/// - Etherscan-compatible (`<base>?module=account&action=…`): a base whose path ends in "/api", for example49///   Routescan's `…/evm/43114/etherscan/api` (Avalanche) or a Blockscout host's own `/api`.50/// A network without any base has no history: `isConfigured` is false and nothing is requested or invented.51public struct EthereumIndexer: Sendable {52    public enum Dialect: String, Sendable { case blockscout, etherscan }5354    let bases: [URL]55    let transport: HTTPTransport5657    public init(network: EthereumNetwork, configuration: EndpointConfiguration = .default, transport: HTTPTransport) {58        bases = urls(configuration.ethereumIndexer[network.rawValue] ?? [])59        self.transport = transport60    }6162    /// The dialect a base URL is queried with.63    public static func dialect(of base: URL) -> Dialect {64        var path = base.path65        while path.hasSuffix("/") { path.removeLast() }66        return path.hasSuffix("/api") ? .etherscan : .blockscout67    }6869    public var isConfigured: Bool { !bases.isEmpty }7071    public struct Transfer: Equatable, Sendable, Identifiable {72        public enum Kind: String, Sendable { case native, token }73        public let kind: Kind74        public let hash: String75        public let from: String76        public let to: String77        /// Base units (wei or token units).78        public let value: UInt25679        public let timestamp: Date?80        public let blockNumber: UInt64?81        public let success: Bool82        /// Fee in wei, for native transactions sent by the account.83        public let fee: UInt256?84        public let tokenAddress: String?85        public let tokenSymbol: String?86        public let tokenDecimals: Int?87        /// 4-byte selector name reported by the indexer (e.g. "approve"), when any.88        public let method: String?89        public var id: String { "\(kind.rawValue):\(hash):\(tokenAddress ?? ""):\(from):\(to):\(value)" }90    }9192    public struct TokenHolding: Equatable, Sendable {93        public let address: String94        public let symbol: String95        public let name: String96        public let decimals: Int97        public let balance: UInt25698    }99100    private static func date(_ v: JSONValue?) -> Date? {101        guard let s = v?.string else { return nil }102        return (try? Date(s, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true))) ?? (try? Date(s, strategy: .iso8601))103    }104105    /// An unsigned integer given as a JSON number or as decimal text. A number that is negative, fractional beyond106    /// truncation range or too large for 64 bits gives nil: the conversion never traps on what a server sends.107    static func number(_ v: JSONValue?) -> UInt64? {108        switch v {109        case .number(let n)?: return n >= 0 && n < 18_446_744_073_709_551_616.0 ? UInt64(n) : nil110        case .string(let s)?: return UInt64(s)111        default: return nil112        }113    }114115    /// One page of rows from the first base that answers, with the dialect that base speaks.116    private func page(blockscout path: String, etherscan query: String) async throws -> (Dialect, [JSONValue]) {117        try await transport.firstSuccess(bases) { base in118            switch Self.dialect(of: base) {119            case .blockscout:120                guard let url = URL(string: base.absoluteString + path) else { throw NetworkError.invalidURL }121                let data = try await transport.get(url)122                guard let v = try? JSONDecoder().decode(JSONValue.self, from: data), let items = v["items"]?.array else {123                    throw NetworkError.invalidResponse(path)124                }125                return (.blockscout, items)126            case .etherscan:127                guard let url = URL(string: base.absoluteString + (base.query == nil ? "?" : "&") + query) else { throw NetworkError.invalidURL }128                let data = try await transport.get(url)129                // {"status":"1","message":"OK","result":[…]}; an account without rows answers status "0" with an empty130                // list; anything else (a refusal, a rate limit, "chain not supported") carries no list and is an error131                guard let v = try? JSONDecoder().decode(JSONValue.self, from: data), let items = v["result"]?.array else {132                    throw NetworkError.invalidResponse("indexer refused the request")133                }134                guard v["status"]?.string == "1" || items.isEmpty else { throw NetworkError.invalidResponse("indexer status") }135                return (.etherscan, items)136            }137        }138    }139140    /// Unix time in seconds, given as decimal text; nil outside 2015-01-01 … 2100-01-01.141    private static func unixDate(_ v: JSONValue?) -> Date? {142        guard let seconds = number(v), seconds >= 1_420_070_400, seconds < 4_102_444_800 else { return nil }143        return Date(timeIntervalSince1970: TimeInterval(seconds))144    }145146    /// "transfer(address,uint256)" → "transfer"; nil for an empty name.147    private static func methodName(_ v: JSONValue?) -> String? {148        guard let s = v?.string, let name = s.split(separator: "(").first, !name.isEmpty, name.count <= 64 else { return nil }149        return String(name)150    }151152    private static let pageQuery = "&page=1&offset=50&sort=desc"153154    private static func isAddress(_ s: String) -> Bool {155        s.hasPrefix("0x") && s.utf8.count == 42 && s.dropFirst(2).utf8.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x41 && $0 <= 0x46) || ($0 >= 0x61 && $0 <= 0x66) }156    }157158    /// Most recent native transactions of the account (first page, about 50).159    public func transactions(of address: String) async throws -> [Transfer] {160        guard Self.isAddress(address) else { throw NetworkError.invalidURL }161        let (dialect, rows) = try await page(blockscout: "/api/v2/addresses/\(address)/transactions",162                                             etherscan: "module=account&action=txlist&address=\(address)" + Self.pageQuery)163        switch dialect {164        case .blockscout:165            return rows.compactMap { t in166                guard let hash = t["hash"]?.string, let from = t["from"]?["hash"]?.string,167                      let value = UInt256(decimal: t["value"]?.string ?? "") else { return nil }168                let status = t["status"]?.string169                return Transfer(kind: .native, hash: hash, from: from, to: t["to"]?["hash"]?.string ?? "", value: value,170                                timestamp: Self.date(t["timestamp"]), blockNumber: Self.number(t["block_number"] ?? t["block"]),171                                success: status == nil || status == "ok",172                                fee: UInt256(decimal: t["fee"]?["value"]?.string ?? ""), tokenAddress: nil, tokenSymbol: nil, tokenDecimals: nil,173                                method: t["method"]?.string)174            }175        case .etherscan:176            return rows.compactMap { t in177                guard let hash = t["hash"]?.string, let from = t["from"]?.string, Self.isAddress(from),178                      let value = UInt256(decimal: t["value"]?.string ?? "") else { return nil }179                var fee: UInt256?180                if let used = UInt256(decimal: t["gasUsed"]?.string ?? ""), let price = UInt256(decimal: t["gasPrice"]?.string ?? "") {181                    let (product, overflow) = used.multipliedReportingOverflow(by: price)182                    if !overflow { fee = product }183                }184                let to = t["to"]?.string ?? ""185                return Transfer(kind: .native, hash: hash, from: from, to: Self.isAddress(to) ? to : "", value: value,186                                timestamp: Self.unixDate(t["timeStamp"]), blockNumber: Self.number(t["blockNumber"]),187                                success: t["isError"]?.string != "1" && t["txreceipt_status"]?.string != "0",188                                fee: fee, tokenAddress: nil, tokenSymbol: nil, tokenDecimals: nil, method: Self.methodName(t["functionName"]))189            }190        }191    }192193    /// Most recent ERC-20 transfers touching the account (first page).194    public func tokenTransfers(of address: String) async throws -> [Transfer] {195        guard Self.isAddress(address) else { throw NetworkError.invalidURL }196        let (dialect, rows) = try await page(blockscout: "/api/v2/addresses/\(address)/token-transfers?type=ERC-20",197                                             etherscan: "module=account&action=tokentx&address=\(address)" + Self.pageQuery)198        switch dialect {199        case .blockscout:200            return rows.compactMap { t in201                guard let hash = (t["transaction_hash"] ?? t["tx_hash"])?.string, let from = t["from"]?["hash"]?.string, let to = t["to"]?["hash"]?.string,202                      let value = UInt256(decimal: t["total"]?["value"]?.string ?? ""),203                      let token = t["token"], let tokenAddress = (token["address_hash"] ?? token["address"])?.string else { return nil }204                return Transfer(kind: .token, hash: hash, from: from, to: to, value: value, timestamp: Self.date(t["timestamp"]),205                                blockNumber: Self.number(t["block_number"]), success: true, fee: nil, tokenAddress: tokenAddress,206                                tokenSymbol: token["symbol"]?.string, tokenDecimals: Self.number(token["decimals"]).flatMap { Int(exactly: $0) }, method: t["method"]?.string)207            }208        case .etherscan:209            return rows.compactMap { t in210                guard let hash = t["hash"]?.string, let from = t["from"]?.string, Self.isAddress(from), let to = t["to"]?.string, Self.isAddress(to),211                      let value = UInt256(decimal: t["value"]?.string ?? ""),212                      let tokenAddress = t["contractAddress"]?.string, Self.isAddress(tokenAddress) else { return nil }213                return Transfer(kind: .token, hash: hash, from: from, to: to, value: value, timestamp: Self.unixDate(t["timeStamp"]),214                                blockNumber: Self.number(t["blockNumber"]), success: true, fee: nil, tokenAddress: tokenAddress,215                                tokenSymbol: t["tokenSymbol"]?.string, tokenDecimals: Self.number(t["tokenDecimal"]).flatMap { Int(exactly: $0) },216                                method: Self.methodName(t["functionName"]))217            }218        }219    }220221    /// ERC-20 tokens the indexer attributes to the account. The wallet re-reads each balance on chain before showing it.222    public func tokenHoldings(of address: String) async throws -> [TokenHolding] {223        guard Self.isAddress(address) else { throw NetworkError.invalidURL }224        let (dialect, rows) = try await page(blockscout: "/api/v2/addresses/\(address)/tokens?type=ERC-20",225                                             etherscan: "module=account&action=addresstokenbalance&address=\(address)&page=1&offset=100")226        switch dialect {227        case .blockscout:228            return rows.compactMap { t in229                guard let token = t["token"], let a = (token["address_hash"] ?? token["address"])?.string, Self.isAddress(a),230                      let decimals = Self.number(token["decimals"]), decimals <= 36,231                      let balance = UInt256(decimal: t["value"]?.string ?? "") else { return nil }232                return TokenHolding(address: a, symbol: String((token["symbol"]?.string ?? "?").prefix(16)),233                                    name: String((token["name"]?.string ?? "").prefix(48)), decimals: Int(decimals), balance: balance)234            }235        case .etherscan:236            return rows.compactMap { t in237                guard let a = t["TokenAddress"]?.string, Self.isAddress(a), let decimals = Self.number(t["TokenDivisor"]), decimals <= 36,238                      let balance = UInt256(decimal: t["TokenQuantity"]?.string ?? "") else { return nil }239                return TokenHolding(address: a, symbol: String((t["TokenSymbol"]?.string ?? "?").prefix(16)),240                                    name: String((t["TokenName"]?.string ?? "").prefix(48)), decimals: Int(decimals), balance: balance)241            }242        }243    }244}245246/// Market data. Two independent sources stand behind this type:247/// - the first, CoinGecko-compatible (`priceAPI`), gives quotes, changes and charts for display, and one of the two248///   prices a dollar ceiling is checked with;249/// - the second, Kraken-compatible (`priceCheckAPI`), is asked for the USD price of one asset at a time and nothing250///   else (`checkPrice`): it exists to cross-check the first when a dollar ceiling of an unaudited mainnet build is251///   converted into units (QYV-SVC-087).252/// The only request content is, for both, public asset identifiers.253public struct PriceClient: Sendable {254    let base: URL?255    let checkBase: URL?256    let transport: HTTPTransport257258    public init(configuration: EndpointConfiguration = .default, transport: HTTPTransport) {259        base = urls([configuration.priceAPI]).first260        checkBase = urls([configuration.priceCheckAPI]).first261        self.transport = transport262    }263264    /// True when a second source is configured and is not served by the host of the first: two addresses of one265    /// host are one source, whatever their paths.266    public var hasCheckSource: Bool {267        guard let checkBase, let checkHost = checkBase.host?.lowercased() else { return false }268        return checkHost != base?.host?.lowercased()269    }270271    /// True when the two price sources of a configuration are served by the same host.272    public static func sourcesShareHost(_ configuration: EndpointConfiguration) -> Bool {273        guard let first = urls([configuration.priceAPI]).first?.host?.lowercased(),274              let second = urls([configuration.priceCheckAPI]).first?.host?.lowercased() else { return false }275        return first == second276    }277278    /// Pair of the second source that prices each asset identifier in US dollars (Kraken's public names; every pair279    /// answered on 2026-12-05). An identifier that is absent has no second source: its dollar ceiling cannot be280    /// verified and an unaudited build refuses to send it on mainnet (maker, coinbase-wrapped-btc and the wstETH281    /// representations were not listed that day).282    ///283    /// A wrapped or bridged representation that is redeemable one for one (wrapped ether, wrapped bitcoin, the wrapped284    /// native coin) is checked against the pair of what it represents: the first source quotes the representation,285    /// the second the underlying, and the two must agree within the tolerance — a representation that lost its parity286    /// is refused, not valued. Dollar-pegged tokens are not here: they follow `MainnetPolicy.stablecoinCeilingPrice`.287    public static let checkPairs: [String: String] = [288        // native coins289        "solana": "SOLUSD", "tron": "TRXUSD", "litecoin": "LTCUSD", "dogecoin": "XDGUSD", "bitcoin-cash": "BCHUSD",290        "polygon-ecosystem-token": "POLUSD", "binancecoin": "BNBUSD", "avalanche-2": "AVAXUSD",291        "bitcoin": "XBTUSD", "ethereum": "ETHUSD",292        // wrapped native coins293        "wmatic": "POLUSD", "wbnb": "BNBUSD", "wrapped-avax": "AVAXUSD",294        // wrapped and bridged ether295        "weth": "ETHUSD", "l2-standard-bridged-weth-base": "ETHUSD", "arbitrum-bridged-weth-arbitrum-one": "ETHUSD",296        "l2-standard-bridged-weth-optimism": "ETHUSD", "polygon-pos-bridged-weth-polygon-pos": "ETHUSD",297        "binance-peg-weth": "ETHUSD", "avalanche-bridged-weth-avalanche": "ETHUSD",298        // wrapped and bridged bitcoin299        "wrapped-bitcoin": "WBTCUSD", "arbitrum-bridged-wbtc-arbitrum-one": "WBTCUSD", "polygon-bridged-wbtc-polygon-pos": "WBTCUSD",300        "binance-bitcoin": "XBTUSD", "bitcoin-avalanche-bridged-btc-b": "XBTUSD",301        // euro-pegged (rule b: two sources, like any token that is not pegged to the dollar)302        "euro-coin": "EURCUSD",303        // other tokens304        "chainlink": "LINKUSD", "uniswap": "UNIUSD", "aave": "AAVEUSD", "lido-dao": "LDOUSD", "pax-gold": "PAXGUSD",305        "arbitrum": "ARBUSD", "shiba-inu": "SHIBUSD", "pepe": "PEPEUSD", "curve-dao-token": "CRVUSD",306        "compound-governance-token": "COMPUSD", "ondo-finance": "ONDOUSD", "ethena": "ENAUSD",307        "aerodrome-finance": "AEROUSD", "pancakeswap-token": "CAKEUSD", "gmx": "GMXUSD", "optimism": "OPUSD",308    ]309310    /// Largest answer of the second source that is parsed (one ticker entry is a few hundred bytes).311    static let checkAnswerLimit = 16_384312313    /// USD price of `id` at the second source, or nil when it has none: no second source configured, an identifier314    /// without pair, an error answer, or an answer that is not exactly one usable ticker.315    ///316    /// Bounded reading: at most `checkAnswerLimit` bytes; exactly one entry in `result`; ask, bid and last trade must317    /// be decimal texts of positive finite numbers below 10^12 with bid ≤ ask; the price is the middle of bid and318    /// ask, and it is refused when the last trade is more than 10 % away from it (a pair nobody trades, whose last319    /// trade is old). Anything else is "no price", never a guess.320    public func checkPrice(id: String) async throws -> Double? {321        guard hasCheckSource, let checkBase, let pair = Self.checkPairs[id] else { return nil }322        var c = URLComponents(url: checkBase.appendingPathComponent("Ticker"), resolvingAgainstBaseURL: false)!323        c.queryItems = [.init(name: "pair", value: pair)]324        let data = try await transport.get(c.url!)325        return Self.parseCheckTicker(data)326    }327328    static func parseCheckTicker(_ data: Data) -> Double? {329        guard data.count <= checkAnswerLimit, let root = try? JSONDecoder().decode(JSONValue.self, from: data),330              (root["error"]?.array ?? []).isEmpty, case .object(let result)? = root["result"], result.count == 1,331              let ticker = result.values.first else { return nil }332        func first(_ key: String) -> Double? {333            guard let text = ticker[key]?.array?.first?.string, text.utf8.count <= 32,334                  text.utf8.allSatisfy({ ($0 >= 0x30 && $0 <= 0x39) || $0 == 0x2e }),335                  let value = Double(text), value.isFinite, value > 0, value < 1e12 else { return nil }336            return value337        }338        guard let ask = first("a"), let bid = first("b"), let last = first("c"), bid <= ask else { return nil }339        let middle = (ask + bid) / 2340        guard abs(last - middle) <= 0.10 * middle else { return nil }341        return middle342    }343344    public var isConfigured: Bool { base != nil }345346    public struct Quote: Codable, Equatable, Sendable {347        public let id: String348        public let price: Double349        public let change24h: Double?350        public let change7d: Double?351        public let sparkline7d: [Double]352        public let fetchedAt: Date353    }354355    public struct PricePoint: Codable, Equatable, Sendable, Identifiable {356        public let date: Date357        public let price: Double358        public var id: Date { date }359    }360361    private static func isID(_ s: String) -> Bool { !s.isEmpty && s.utf8.allSatisfy { ($0 >= 0x61 && $0 <= 0x7a) || ($0 >= 0x30 && $0 <= 0x39) || $0 == 0x2d } }362363    public func quotes(ids: [String], currency: String = "usd") async throws -> [String: Quote] {364        let clean = ids.filter(Self.isID)365        guard let base, !clean.isEmpty, Self.isID(currency) else { return [:] }366        var c = URLComponents(url: base.appendingPathComponent("coins/markets"), resolvingAgainstBaseURL: false)!367        c.queryItems = [368            .init(name: "vs_currency", value: currency), .init(name: "ids", value: clean.joined(separator: ",")),369            .init(name: "per_page", value: "250"), .init(name: "sparkline", value: "true"),370            .init(name: "price_change_percentage", value: "24h,7d"),371        ]372        let data = try await transport.get(c.url!)373        guard let rows = (try? JSONDecoder().decode(JSONValue.self, from: data))?.array else { throw NetworkError.invalidResponse("markets") }374        var out = [String: Quote]()375        for r in rows {376            guard let id = r["id"]?.string, case .number(let price)? = r["current_price"], price.isFinite, price >= 0 else { continue }377            func num(_ k: String) -> Double? { if case .number(let n)? = r[k], n.isFinite { return n }; return nil }378            let spark = (r["sparkline_in_7d"]?["price"]?.array ?? []).compactMap { v -> Double? in if case .number(let n) = v, n.isFinite { return n }; return nil }379            out[id] = Quote(id: id, price: price, change24h: num("price_change_percentage_24h_in_currency"),380                            change7d: num("price_change_percentage_7d_in_currency"), sparkline7d: spark, fetchedAt: Date())381        }382        return out383    }384385    public func chart(id: String, currency: String = "usd", days: Int) async throws -> [PricePoint] {386        guard let base, Self.isID(id), Self.isID(currency), days > 0 else { return [] }387        var c = URLComponents(url: base.appendingPathComponent("coins/\(id)/market_chart"), resolvingAgainstBaseURL: false)!388        c.queryItems = [.init(name: "vs_currency", value: currency), .init(name: "days", value: String(days))]389        let data = try await transport.get(c.url!)390        guard let prices = (try? JSONDecoder().decode(JSONValue.self, from: data))?["prices"]?.array else { throw NetworkError.invalidResponse("market_chart") }391        return prices.compactMap { p in392            guard let pair = p.array, pair.count == 2, case .number(let ms) = pair[0], case .number(let price) = pair[1], price.isFinite else { return nil }393            return PricePoint(date: Date(timeIntervalSince1970: ms / 1000), price: price)394        }395    }396}397
Files main
Menu

Theme