SPB Git

Repository Public

WalletService+Ethereum.swift 62.7 KB 996 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraWallet/WalletService+Ethereum.swift8// Module           : Qyvora Wallet9// 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 QyvoraEthereum45import QyvoraNetworking46import QyvoraVault4748extension WalletService {49    // MARK: Synchronization5051    /// Synchronizes the primary EVM network (`profile.ethereumNetwork`). **Network.** Works for full and watch-only52    /// wallets, locked or not. `synchronize(chains:)` does the same for every enabled chain.53    ///54    /// Chain identity check (chain id agreed by every endpoint), native balance, latest and pending nonce, token balances55    /// read on chain with `balanceOf`, history and approvals when an indexer is configured. A concurrent call joins the56    /// running one. Errors: `mainnetDisabled`, `offline`, `wrongChain`, `untrustedResponse`, `network`.57    @discardableResult58    public func syncEthereum() async throws(WalletError) -> EthereumSnapshot {59        try await run { try await syncEVM(profile.ethereumNetwork) }60    }6162    /// Synchronizes one EVM network: the primary one, or the network of an enabled chain.63    @discardableResult64    func syncEVM(_ network: EthereumNetwork) async throws -> EthereumSnapshot {65        guard usesEVM(network) else { throw WalletError.chainNotActive(network.displayName) }66        if let running = evmSyncTasks[network] { return try await running.value }67        let task = Task { try await self.performEthereumSync(network) }68        evmSyncTasks[network] = task69        let kind = ChainKind.evm(network)70        noteSyncStarted(kind)71        do {72            let snapshot = try await task.value73            evmSyncTasks[network] = nil74            evmErrors[network] = nil75            noteSyncFinished(kind)76            return snapshot77        } catch {78            evmSyncTasks[network] = nil79            let wrapped = WalletError.wrap(error, now: now())80            let reason = Self.describe(wrapped)81            evmErrors[network] = reason82            noteSyncFailed(kind, reason: reason)83            throw wrapped84        }85    }8687    /// True when the wallet works on this EVM network now: the primary network, or the network of an enabled chain.88    func usesEVM(_ network: EthereumNetwork) -> Bool {89        network == profile.ethereumNetwork || Self.activeKinds(profile).contains(.evm(network))90    }9192    /// The last snapshot of the primary EVM network, nil before its first successful synchronization.93    public func latestEthereumSnapshot() -> EthereumSnapshot? { ethereumSnapshot }9495    /// Tokens of the wallet's list for a network: built-in, then custom, hidden ones removed.96    func listedTokens(_ network: EthereumNetwork) -> [TokenInfo] {97        let hidden = Set(profile.hiddenTokens)98        var seen = Set<EthereumAddress>()99        return (BuiltInTokens.tokens(for: network) + profile.customTokens.filter { $0.network == network })100            .filter { !hidden.contains($0.id) && seen.insert($0.address).inserted }101    }102103    func knownToken(_ address: EthereumAddress, network: EthereumNetwork) -> TokenInfo? {104        (BuiltInTokens.tokens(for: network) + profile.customTokens.filter { $0.network == network }).first { $0.address == address }105    }106107    private func performEthereumSync(_ network: EthereumNetwork) async throws -> EthereumSnapshot {108        let address = try ethereumAccount(network)109        let kind = ChainKind.evm(network)110        let rpc = try await verifiedRPC(network)111        let owner = address.checksummed112        var notes = [String]()113114        noteProgress(kind, stage: "Reading the account", completed: 0, total: 4)115        let block = try await rpc.blockNumber()116        let balance = try await rpc.balance(of: owner)117        // read-only: endpoints a few transactions apart are both right; the highest count is shown, with a note118        let latest = try await observedTransactionCount(rpc, owner: owner, tag: "latest", notes: &notes)119        let pending = try await observedTransactionCount(rpc, owner: owner, tag: "pending", notes: &notes)120        guard pending >= latest, pending - latest <= 10_000 else { throw WalletError.untrustedResponse("pending nonce below latest nonce") }121122        // Listed tokens: balance on chain; decimals re-read on chain once per session123        noteProgress(kind, stage: "Reading token balances", completed: 1, total: 4)124        let listed = listedTokens(network)125        let alreadyVerified = verifiedTokens126        let tokenResults = try await boundedMap(listed) { token -> (TokenBalance, Bool) in127            do {128                var checked = alreadyVerified[token.id] != nil129                if !checked {130                    let decimals = try await Self.readDecimals(rpc, token: token.address)131                    guard decimals == token.decimals else {132                        return (TokenBalance(token: token, balance: .unavailable(reason: "The contract reports \(decimals) decimals, the token list says \(token.decimals).")), false)133                    }134                    checked = true135                }136                guard let value = ERC20.decodeUInt(try await rpc.ethCall(to: token.address.checksummed, data: ERC20.balanceOf(address))) else {137                    return (TokenBalance(token: token, balance: .unavailable(reason: "The contract did not return a balance.")), checked)138                }139                return (TokenBalance(token: token, balance: .available(value)), checked)140            } catch let e as NetworkError {141                if case .offline = e { throw e }142                return (TokenBalance(token: token, balance: .unavailable(reason: Self.describe(WalletError.from(e)))), false)143            } catch let e as WalletError {144                return (TokenBalance(token: token, balance: .unavailable(reason: Self.describe(e))), false)145            }146        }147        for (b, checked) in tokenResults where checked { verifiedTokens[b.token.id] = b.token }148        let tokens = tokenResults.map(\.0)149150        // Indexer: token discovery (a hint only), history, approvals151        noteProgress(kind, stage: "Reading history", completed: 2, total: 4)152        let indexer = EthereumIndexer(network: network, configuration: profile.endpoints, transport: gate)153        var detected = [TokenBalance]()154        // without an indexer nothing stands in for the history: the reason is shown instead155        let noIndexer = Self.noIndexerReason(network)156        var history: Availability<[EthereumHistoryEntry]> = .unavailable(reason: noIndexer)157        var approvals: Availability<[TokenApproval]> = .unavailable(reason: noIndexer)158        if indexer.isConfigured {159            do {160                let holdings = try await indexer.tokenHoldings(of: owner)161                detected = try await detectTokens(holdings, rpc: rpc, owner: address, network: network)162            } catch let e as NetworkError {163                if case .offline = e { throw e }164                notes.append("Token discovery is unavailable: \(Self.describe(WalletError.from(e)))")165            }166            do {167                let native = try await indexer.transactions(of: owner)168                let transfers = try await indexer.tokenTransfers(of: owner)169                history = .available(buildHistory(native: native, transfers: transfers, owner: address, network: network))170                noteProgress(kind, stage: "Checking token approvals", completed: 3, total: 4)171                do {172                    approvals = .available(try await findApprovals(native: native, rpc: rpc, owner: address, network: network, notes: &notes))173                } catch let e as NetworkError {174                    if case .offline = e { throw e }175                    approvals = .unavailable(reason: Self.describe(WalletError.from(e)))176                }177            } catch let e as NetworkError {178                if case .offline = e { throw e }179                let reason = Self.describe(WalletError.from(e))180                history = .unavailable(reason: reason)181                approvals = .unavailable(reason: reason)182            }183        }184185        let snapshot = EthereumSnapshot(network: network, address: address, synchronizedAt: now(), blockNumber: block, balance: balance,186                                        latestNonce: latest, pendingNonce: pending, tokens: tokens, detectedTokens: detected, history: history,187                                        approvals: approvals, notes: notes)188        guard profile.kind != nil, usesEVM(network), profile.ethereumAddress == address else {189            throw WalletError.stalePlan("the active network changed during synchronization")190        }191        evmSnapshots[network] = snapshot192        persistEVMSnapshot(network)193        return snapshot194    }195196    /// Why a network has no history: no indexer is configured for it. Seven EVM networks ship without one because no197    /// keyless public indexer could be verified for them; the user can enter one in the settings.198    static func noIndexerReason(_ network: EthereumNetwork) -> String {199        EVMEndpointDefaults.hasDefaultIndexer(network)200            ? "No indexer is configured for \(network.displayName)."201            : "No indexer is configured for \(network.displayName): no keyless public history source exists for this network. Balances, tokens and payments work; the history is not shown. You can enter an indexer of your own in the settings."202    }203204    // MARK: Nonce cross-check205206    private static func describe(_ answers: [EthereumRPC.EndpointCount]) -> String {207        answers.map { "\($0.host): \($0.count)" }.joined(separator: ", ")208    }209210    /// Transaction count for **display** (synchronization). Every endpoint that answers must be within211    /// `nonceReadWindow` of the others; the highest value is returned, and a note says so when they differ.212    /// A larger difference is not lag: it is reported as a disagreement.213    func observedTransactionCount(_ rpc: EthereumRPC, owner: String, tag: String, notes: inout [String]) async throws -> UInt64 {214        let answers = try await rpc.transactionCounts(of: owner, tag: tag)215        let low = answers.map(\.count).min() ?? 0, high = answers.map(\.count).max() ?? 0216        guard high - low <= Self.nonceReadWindow else {217            throw WalletError.untrustedResponse("the endpoints disagree on the account's transaction count (\(tag)) by more than \(Self.nonceReadWindow): \(Self.describe(answers))")218        }219        if high != low {220            notes.append("The endpoints were \(high - low) transaction(s) apart on the account's transaction count (\(tag)) when it was read (\(Self.describe(answers))); the highest value is shown.")221        }222        return high223    }224225    /// Transaction count for **preparing or broadcasting a transaction**: every endpoint that answers must report the226    /// same value. A difference is retried once after a short pause (the endpoints may be one block apart), then227    /// refused: a wrong nonce cannot lose funds, but it produces a transaction that fails or stays stuck.228    func agreedTransactionCount(_ rpc: EthereumRPC, owner: String, tag: String) async throws -> UInt64 {229        var answers = try await rpc.transactionCounts(of: owner, tag: tag)230        if Set(answers.map(\.count)).count > 1 {231            await gate.wait(Self.nonceAgreementRetryDelay)232            answers = try await rpc.transactionCounts(of: owner, tag: tag)233        }234        guard Set(answers.map(\.count)).count == 1, let value = answers.first?.count else {235            throw WalletError.untrustedResponse("the endpoints do not agree on the account's transaction count (\(tag)): \(Self.describe(answers)). Nothing was prepared; try again in a moment")236        }237        return value238    }239240    // MARK: Token metadata (on chain)241242    static func readDecimals(_ rpc: EthereumRPC, token: EthereumAddress) async throws -> Int {243        guard let value = ERC20.decodeUInt(try await rpc.ethCall(to: token.checksummed, data: ERC20.decimalsSelector))?.uint64,244              value <= UInt64(maximumTokenDecimals) else {245            throw WalletError.untrustedResponse("token decimals missing or above \(maximumTokenDecimals)")246        }247        return Int(value)248    }249250    /// Symbol, name and decimals read from the contract and bounded. Throws when the address is not an ERC-20 token.251    static func readToken(_ rpc: EthereumRPC, address: EthereumAddress, network: EthereumNetwork) async throws -> TokenInfo {252        guard !(try await rpc.code(at: address.checksummed)).isEmpty else { throw WalletError.ethereum(.tokenContractMissing) }253        let decimals = try await readDecimals(rpc, token: address)254        guard let rawSymbol = ERC20.decodeString(try await rpc.ethCall(to: address.checksummed, data: ERC20.symbolSelector)) else {255            throw WalletError.untrustedResponse("token symbol missing")256        }257        func clean(_ s: String, _ limit: Int) -> String {258            String(s.unicodeScalars.filter { $0.isASCII && $0.value >= 0x20 && $0.value < 0x7f }.map(Character.init)).trimmingCharacters(in: .whitespaces).prefix(limit).description259        }260        let symbol = clean(rawSymbol, 16)261        guard !symbol.isEmpty else { throw WalletError.untrustedResponse("token symbol unreadable") }262        let name = (try? await rpc.ethCall(to: address.checksummed, data: ERC20.nameSelector)).flatMap(ERC20.decodeString).map { clean($0, 48) } ?? ""263        return TokenInfo(network: network, address: address, symbol: symbol, name: name.isEmpty ? symbol : name, decimals: decimals, priceID: nil, custom: true)264    }265266    /// Tokens the indexer attributes to the account, each one read on chain. The indexer's symbol and decimals are ignored.267    private func detectTokens(_ holdings: [EthereumIndexer.TokenHolding], rpc: EthereumRPC, owner: EthereumAddress,268                              network: EthereumNetwork) async throws -> [TokenBalance] {269        let listed = Set((BuiltInTokens.tokens(for: network) + profile.customTokens.filter { $0.network == network }).map(\.address))270        let hidden = Set(profile.hiddenTokens)271        var candidates = [EthereumAddress]()272        for h in holdings.prefix(200) {273            guard let a = EthereumAddress(h.address.lowercased()), !a.isZero, !listed.contains(a), !candidates.contains(a),274                  !hidden.contains("\(network.rawValue):\(a.checksummed)") else { continue }275            candidates.append(a)276            if candidates.count == 20 { break }277        }278        let results = try await boundedMap(candidates) { a -> TokenBalance? in279            do {280                let token = try await Self.readToken(rpc, address: a, network: network)281                guard let value = ERC20.decodeUInt(try await rpc.ethCall(to: a.checksummed, data: ERC20.balanceOf(owner))), !value.isZero else { return nil }282                return TokenBalance(token: token, balance: .available(value))283            } catch let e as NetworkError {284                if case .offline = e { throw e }285                return nil286            } catch is WalletError {287                return nil288            }289        }290        return results.compactMap { $0 }291    }292293    // MARK: History and approvals294295    private func buildHistory(native: [EthereumIndexer.Transfer], transfers: [EthereumIndexer.Transfer], owner: EthereumAddress,296                              network: EthereumNetwork) -> [EthereumHistoryEntry] {297        let me = owner.checksummed.lowercased()298        var entries = [EthereumHistoryEntry]()299        func direction(_ from: String, _ to: String) -> EthereumHistoryEntry.Direction? {300            let f = from.lowercased() == me, t = to.lowercased() == me301            if f && t { return .selfTransfer }302            if f { return .sent }303            if t { return .received }304            return nil305        }306        func validHash(_ h: String) -> Bool { h.hasPrefix("0x") && h.utf8.count == 66 && Hex.decode(String(h.dropFirst(2))) != nil }307        for t in native.prefix(200) {308            guard validHash(t.hash), let d = direction(t.from, t.to) else { continue }309            let kind: EthereumHistoryEntry.Kind310            if d != .received, let m = t.method?.lowercased(), m == "approve" || m == "0x095ea7b3" {311                kind = .approval(token: t.to)312            } else if t.value.isZero, t.method != nil {313                kind = .contractCall(method: t.method.map { String($0.prefix(40)) })314            } else {315                kind = .ether316            }317            entries.append(EthereumHistoryEntry(hash: t.hash.lowercased(), kind: kind, direction: d, counterparty: d == .received ? t.from : t.to,318                                                amount: t.value, fee: d == .received ? nil : t.fee, succeeded: t.success, time: t.timestamp,319                                                blockNumber: t.blockNumber, id: "native:\(t.hash.lowercased())"))320        }321        for (n, t) in transfers.prefix(200).enumerated() {322            guard validHash(t.hash), let d = direction(t.from, t.to), let contract = t.tokenAddress else { continue }323            let known = EthereumAddress(contract.lowercased()).flatMap { knownToken($0, network: network) ?? verifiedTokens["\(network.rawValue):\($0.checksummed)"] }324            let kind: EthereumHistoryEntry.Kind = known.map { .token(address: contract, symbol: $0.symbol, decimals: $0.decimals, verified: true) }325                ?? .token(address: contract, symbol: t.tokenSymbol.map { String($0.prefix(16)) },326                          decimals: t.tokenDecimals.flatMap { $0 <= Self.maximumTokenDecimals ? $0 : nil }, verified: false)327            entries.append(EthereumHistoryEntry(hash: t.hash.lowercased(), kind: kind, direction: d, counterparty: d == .received ? t.from : t.to,328                                                amount: t.value, fee: nil, succeeded: t.success, time: t.timestamp, blockNumber: t.blockNumber,329                                                id: "token:\(t.hash.lowercased()):\(n)"))330        }331        return entries.sorted {332            switch ($0.time, $1.time) {333            case (nil, nil): return $0.id < $1.id334            case (nil, _): return true335            case (_, nil): return false336            case (let a?, let b?): return a != b ? a > b : $0.id < $1.id337            }338        }339    }340341    /// From the account's own `approve` transactions (found through the indexer, then read from the node), the spenders,342    /// then the current allowance of each on chain. Only non-zero allowances are returned.343    private func findApprovals(native: [EthereumIndexer.Transfer], rpc: EthereumRPC, owner: EthereumAddress, network: EthereumNetwork,344                               notes: inout [String]) async throws -> [TokenApproval] {345        let me = owner.checksummed.lowercased()346        let hashes = native.filter {347            guard $0.from.lowercased() == me, $0.success, let m = $0.method?.lowercased() else { return false }348            return m == "approve" || m == "0x095ea7b3"349        }.map { $0.hash.lowercased() }.filter { $0.hasPrefix("0x") && $0.utf8.count == 66 && Hex.decode(String($0.dropFirst(2))) != nil }350        var unique = [String]()351        for h in hashes where !unique.contains(h) { unique.append(h) }352        if unique.count > 40 { notes.append("Only the 40 most recent approval transactions were examined.") }353354        // the transaction itself, from the node: sender, contract and call data355        let pairs = try await boundedMap(Array(unique.prefix(40))) { hash -> (EthereumAddress, EthereumAddress)? in356            let tx = try await rpc.call("eth_getTransactionByHash", [.string(hash)])357            guard let from = tx["from"]?.string, from.lowercased() == me, let to = tx["to"]?.string, let contract = EthereumAddress(to.lowercased()),358                  let input = tx["input"]?.string, input.hasPrefix("0x"), input.utf8.count <= 2 + 68 * 2, let data = Hex.decode(String(input.dropFirst(2))),359                  case .approve(let spender, _)? = ERC20.decodeCall(data) else { return nil }360            return (contract, spender)361        }362        var seen = Set<String>()363        var targets = [(EthereumAddress, EthereumAddress)]()364        for p in pairs.compactMap({ $0 }) where seen.insert("\(p.0.checksummed):\(p.1.checksummed)").inserted { targets.append(p) }365366        var out = [TokenApproval]()367        for (contract, spender) in targets {368            guard let allowance = ERC20.decodeUInt(try await rpc.ethCall(to: contract.checksummed, data: ERC20.allowance(owner: owner, spender: spender))),369                  !allowance.isZero else { continue }370            var token = knownToken(contract, network: network) ?? verifiedTokens["\(network.rawValue):\(contract.checksummed)"]371            if token == nil {372                do {373                    token = try await Self.readToken(rpc, address: contract, network: network)374                } catch let e as WalletError {375                    notes.append("An allowance on \(contract.checksummed) is open but the contract does not describe itself as a token (\(Self.describe(e))).")376                    token = TokenInfo(network: network, address: contract, symbol: "?", name: "Unidentified contract", decimals: 0, priceID: nil, custom: true)377                }378            }379            if let token { out.append(TokenApproval(token: token, spender: spender, allowance: allowance, isUnlimited: ERC20.isUnlimited(allowance))) }380        }381        return out.sorted { $0.id < $1.id }382    }383384    // MARK: Token list385386    /// Adds a token by contract address. **Network**: symbol, name and decimals are read from the contract (decimals ≤ 36).387    public func addCustomToken(address text: String) async throws(WalletError) -> TokenInfo {388        try await run { try await addEVMToken(address: text, network: profile.ethereumNetwork) }389    }390391    func addEVMToken(address text: String, network: EthereumNetwork) async throws -> TokenInfo {392        do {393            _ = try requireWallet()394            guard usesEVM(network) else { throw WalletError.chainNotActive(network.displayName) }395            guard let address = EthereumAddress(text.trimmingCharacters(in: .whitespacesAndNewlines)), !address.isZero else {396                throw WalletError.ethereum(.invalidAddress)397            }398            if let existing = knownToken(address, network: network) {399                // adding a hidden token again shows it again400                profile.hiddenTokens.removeAll { $0 == existing.id }401                try saveProfile()402                alignEthereumSnapshotWithTokenList(network)403                return existing404            }405            let rpc = try await verifiedRPC(network)406            let token = try await Self.readToken(rpc, address: address, network: network)407            // the balance is read now, so that the token does not sit in the list without one until the next synchronization408            var balance: Availability<UInt256> = .notLoaded409            if let owner = profile.ethereumAddress {410                do {411                    balance = ERC20.decodeUInt(try await rpc.ethCall(to: token.address.checksummed, data: ERC20.balanceOf(owner))).map { .available($0) }412                        ?? .unavailable(reason: "The contract did not return a balance.")413                } catch {414                    balance = .unavailable(reason: Self.describe(WalletError.wrap(error, now: now())))415                }416            }417            guard profile.kind != nil, usesEVM(network) else { throw WalletError.stalePlan("the active network changed") }418            if knownToken(address, network: network) == nil { profile.customTokens.append(token) }419            profile.hiddenTokens.removeAll { $0 == token.id }420            verifiedTokens[token.id] = token421            try saveProfile()422            alignEthereumSnapshotWithTokenList(network, fresh: [token.id: balance])423            return token424        }425    }426427    /// Brings the token lists of the current Ethereum snapshot in line with the profile, without network: listed tokens428    /// keep the balance they had (as a listed or as a detected token), a token that has none yet is `.notLoaded` until429    /// the next synchronization, removed and hidden tokens leave the snapshot. `fresh` gives balances just read on chain.430    func alignEthereumSnapshotWithTokenList(_ network: EthereumNetwork? = nil, fresh: [String: Availability<UInt256>] = [:]) {431        let network = network ?? profile.ethereumNetwork432        guard let snapshot = evmSnapshots[network], snapshot.network == network else { return }433        var known = [String: TokenBalance]()434        for b in snapshot.detectedTokens + snapshot.tokens { known[b.token.id] = b }435        let listed = listedTokens(snapshot.network)436        let listedIDs = Set(listed.map(\.id)), hidden = Set(profile.hiddenTokens)437        let tokens = listed.map { TokenBalance(token: $0, balance: fresh[$0.id] ?? known[$0.id]?.balance ?? .notLoaded) }438        let detected = snapshot.detectedTokens.filter { !listedIDs.contains($0.token.id) && !hidden.contains($0.token.id) }439        guard tokens != snapshot.tokens || detected != snapshot.detectedTokens else { return }440        evmSnapshots[network] = snapshot.with(tokens: tokens, detectedTokens: detected)441        persistEVMSnapshot(network)442    }443444    static let detectedFromPreviousSessionText = "This token was detected in a previous session. Synchronize before adding it to the list."445446    /// Moves a token of the "detected" list into the wallet's list. No network: the metadata was read on chain at sync447    /// (of this session: a list restored from the previous session is refused until a synchronization).448    public func acceptDetectedToken(_ token: TokenInfo) async throws(WalletError) {449        try await run {450            guard let snapshot = evmSnapshots[token.network], let found = snapshot.detectedTokens.first(where: { $0.token == token }) else {451                throw WalletError.invalidInput("This token is not in the detected list.")452            }453            // only what this session read on chain enters the list: after a restart the detected list is a file, and454            // its symbol and decimals would become those of every later payment of the token (QYV-SVC-102)455            guard !snapshot.isFromPreviousSession else { throw WalletError.notSynchronized(Self.detectedFromPreviousSessionText) }456            guard knownToken(token.address, network: token.network) == nil else { return }457            profile.customTokens.append(found.token)458            verifiedTokens[found.token.id] = found.token459            try saveProfile()460            alignEthereumSnapshotWithTokenList(token.network)461        }462    }463464    /// Removes a custom token from the list (built-in tokens can only be hidden).465    public func removeCustomToken(_ token: TokenInfo) async throws(WalletError) {466        try await run {467            profile.customTokens.removeAll { $0.id == token.id }468            try saveProfile()469            alignEthereumSnapshotWithTokenList(token.network)470        }471    }472473    /// Hides (or shows again) a token, listed or detected. A hidden token is neither read nor reported.474    public func setTokenHidden(_ hidden: Bool, token: TokenInfo) async throws(WalletError) {475        try await run {476            var set = Set(profile.hiddenTokens)477            if hidden { set.insert(token.id) } else { set.remove(token.id) }478            profile.hiddenTokens = set.sorted()479            try saveProfile()480            alignEthereumSnapshotWithTokenList(token.network)481        }482    }483484    // MARK: Sending485486    /// Builds a reviewable transfer of ether or of a token. **Network**, no secret.487    ///488    /// Rules (each failure is a `WalletError.ethereum(…)` refusal):489    /// - the address must be valid (EIP-55 checked when mixed case), not zero, and for a token not the token contract itself;490    /// - pending nonce ≠ latest nonce is refused (`pendingTransaction`) unless `replacePending` is true, in which case the491    ///   transaction reuses the latest nonce and replaces the pending one;492    /// - fees: maxFeePerGas = 2 × base fee + priority fee of the chosen tier;493    /// - ether: gas 21 000; a destination holding code is refused unless `allowContractRecipient` (then gas is estimated);494    /// - token: gas = estimate × 1.3 + 5 000, refused above 200 000; the call is simulated and must return nothing or `true`;495    /// - balances are read again on chain; `sendMax` sends the whole token balance, or the ether balance minus the maximum fee.496    ///497    /// `network` is the primary EVM network unless given; it must be the primary one or the network of an enabled chain.498    public func prepareEthereumSend(asset: EthereumAsset, to: String, amount: UInt256, sendMax: Bool = false, feeTier: EthereumFeeTier = .normal,499                                    replacePending: Bool = false, allowContractRecipient: Bool = false,500                                    network: EthereumNetwork? = nil) async throws(WalletError) -> EthereumSendReview {501        try await run {502            let network = network ?? profile.ethereumNetwork503            guard usesEVM(network) else { throw WalletError.chainNotActive(network.displayName) }504            let text = to.trimmingCharacters(in: .whitespacesAndNewlines)505            guard let recipient = EthereumAddress(text) else { throw EthereumRefusal.invalidAddress }506            var warnings = [EthereumSendWarning]()507            let digits = text.dropFirst(2)508            let hasLower = digits.utf8.contains { $0 >= 0x61 && $0 <= 0x66 }, hasUpper = digits.utf8.contains { $0 >= 0x41 && $0 <= 0x46 }509            if !(hasLower && hasUpper) { warnings.append(.recipientWithoutChecksum) }510            switch asset {511            case .ether:512                return try await buildEthereumReview(network: network, asset: .ether, recipient: recipient, amount: amount, sendMax: sendMax, call: nil,513                                                     feeTier: feeTier, replacePending: replacePending, allowContractRecipient: allowContractRecipient,514                                                     warnings: warnings)515            case .token(let token):516                return try await buildEthereumReview(network: network, asset: asset, recipient: recipient, amount: amount, sendMax: sendMax,517                                                     call: .transfer(token), feeTier: feeTier, replacePending: replacePending,518                                                     allowContractRecipient: false, warnings: warnings)519            }520        }521    }522523    /// Builds the transaction that sets the allowance of `spender` on `token` to zero (`approve(spender, 0)`), through the524    /// same rules as a token transfer. **Network**, no secret. Sign it with `signAndBroadcastEthereum`.525    public func revokeApproval(token: TokenInfo, spender: EthereumAddress, feeTier: EthereumFeeTier = .normal,526                               replacePending: Bool = false) async throws(WalletError) -> EthereumSendReview {527        try await run {528            guard usesEVM(token.network) else { throw WalletError.chainNotActive(token.network.displayName) }529            return try await buildEthereumReview(network: token.network, asset: .token(token), recipient: spender, amount: .zero, sendMax: false,530                                                 call: .revoke(token), feeTier: feeTier, replacePending: replacePending, allowContractRecipient: false,531                                                 warnings: [.revokesApproval])532        }533    }534535    enum TokenCall {536        case transfer(TokenInfo)537        case revoke(TokenInfo)538    }539540    /// True when the history read for this account shows a payment (ether or token) sent to `recipient`, or when one541    /// was broadcast in this session. Without history (no indexer) nothing is known and the answer is false.542    func hasPaidEthereum(_ recipient: EthereumAddress, network: EthereumNetwork) -> Bool {543        let wanted = recipient.checksummed.lowercased()544        if paidRecipients.contains(Self.paidKey(.evm(network), wanted)) { return true }545        guard let history = evmSnapshots[network]?.history.value else { return false }546        return history.contains { $0.direction == .sent && $0.succeeded && $0.counterparty.lowercased() == wanted }547    }548549    private func buildEthereumReview(network: EthereumNetwork, asset: EthereumAsset, recipient: EthereumAddress, amount requested: UInt256,550                                     sendMax: Bool, call: TokenCall?, feeTier: EthereumFeeTier, replacePending: Bool, allowContractRecipient: Bool,551                                     warnings initial: [EthereumSendWarning]) async throws -> EthereumSendReview {552        let from = try ethereumAccount(network)553        var warnings = initial554        var isRevocation = false555        if case .revoke? = call { isRevocation = true }556        guard !recipient.isZero else { throw EthereumRefusal.zeroAddress }557        if case .token(let token) = asset {558            guard token.network == network else { throw EthereumRefusal.tokenNetworkMismatch }559            guard token.address != recipient else { throw EthereumRefusal.recipientIsTokenContract }560            guard !token.address.isZero, token.decimals >= 0, token.decimals <= Self.maximumTokenDecimals else { throw EthereumRefusal.tokenContractMissing }561        }562        if recipient == from {563            warnings.append(.recipientIsOwnAddress)564        } else if !isRevocation, !hasPaidEthereum(recipient, network: network) {565            // an address this account never paid, as far as the history read shows (QYV-APP-010)566            warnings.append(.firstPaymentToRecipient)567        }568        let rpc = try await verifiedRPC(network)569        let owner = from.checksummed570571        // Nonce: a pending transaction blocks a new one unless the caller replaces it572        let latest = try await agreedTransactionCount(rpc, owner: owner, tag: "latest")573        let pending = try await agreedTransactionCount(rpc, owner: owner, tag: "pending")574        guard pending >= latest else { throw WalletError.untrustedResponse("pending nonce below latest nonce") }575        if pending != latest {576            guard replacePending else { throw EthereumRefusal.pendingTransaction(latestNonce: latest, pendingNonce: pending) }577            warnings.append(.replacesPendingTransaction(nonce: latest))578        }579        let nonce = latest580581        // Fees by the rules of the network (`EVMFeeRules`: Polygon's minimum tip, BNB Smart Chain's zero base fee).582        // The client refuses endpoint figures above 10 000 gwei.583        let fees = try await rpc.feeData()584        let speed: EVMFeeSpeed585        switch feeTier {586        case .slow: speed = .slow587        case .normal: speed = .normal588        case .fast: speed = .fast589        }590        let gasFees: EVMGasFees591        do {592            gasFees = try EVMFeeRules.gasFees(network: network, baseFee: fees.baseFee, suggestedPriorityFee: fees.priorityFee,593                                              gasPrice: fees.gasPrice, speed: speed)594        } catch {595            throw EthereumRefusal.feeOutOfRange596        }597        let tip = gasFees.maxPriorityFeePerGas, maxFee = gasFees.maxFeePerGas598599        let balance = try await rpc.balance(of: owner)600        var gasLimit = Self.ethereumTransferGas601        var destination = recipient602        var value = UInt256.zero603        var data = Bytes()604        var amount = requested605        var description = EthereumCallDescription.etherTransfer606607        func marginGas(_ estimate: UInt64) throws -> UInt64 {608            guard estimate >= Self.ethereumTransferGas, estimate <= 30_000_000 else { throw EthereumRefusal.simulationFailed("gas estimate out of range") }609            let gas = estimate * 13 / 10 + 5_000610            guard gas <= Self.ethereumGasLimitCeiling else { throw EthereumRefusal.gasLimitTooHigh(estimated: gas, limit: Self.ethereumGasLimitCeiling) }611            return gas612        }613        func estimate(to: EthereumAddress, value: UInt256, data: Bytes) async throws -> UInt64 {614            do {615                return try marginGas(try await rpc.estimateGas(from: owner, to: to.checksummed, value: value, data: data))616            } catch NetworkError.rpc(_, let message) {617                throw EthereumRefusal.simulationFailed(message)618            }619        }620        func fee(_ gas: UInt64) throws -> UInt256 {621            let (f, o) = maxFee.multipliedReportingOverflow(by: gas)622            guard !o else { throw EthereumRefusal.feeOutOfRange }623            return f624        }625626        switch call {627        case nil:628            let code = try await rpc.code(at: recipient.checksummed)629            if !code.isEmpty {630                guard allowContractRecipient else { throw EthereumRefusal.recipientIsContract }631                warnings.append(.recipientIsContract)632            }633            // 21 000 gas only where that is a constant of the network: on Arbitrum the estimate carries the L1 component634            let mustEstimate = !code.isEmpty || !network.nativeTransferGasIsFixed635            if sendMax {636                if mustEstimate { gasLimit = try await estimate(to: recipient, value: UInt256(1), data: []) }637                let cost = try fee(gasLimit)638                guard balance > cost else { throw EthereumRefusal.insufficientFundsForFee(available: balance, required: cost) }639                amount = balance - cost640            } else {641                guard !amount.isZero else { throw EthereumRefusal.zeroAmount }642                guard amount <= balance else { throw EthereumRefusal.insufficientBalance(available: balance, required: amount) }643                if mustEstimate { gasLimit = try await estimate(to: recipient, value: amount, data: []) }644            }645            value = amount646        case .transfer(let token), .revoke(let token):647            guard !(try await rpc.code(at: token.address.checksummed)).isEmpty else { throw EthereumRefusal.tokenContractMissing }648            if case .transfer = call {649                guard let tokenBalance = ERC20.decodeUInt(try await rpc.ethCall(to: token.address.checksummed, data: ERC20.balanceOf(from))) else {650                    throw WalletError.untrustedResponse("token balance")651                }652                if sendMax { amount = tokenBalance }653                guard !amount.isZero else { throw EthereumRefusal.zeroAmount }654                guard amount <= tokenBalance else { throw EthereumRefusal.insufficientBalance(available: tokenBalance, required: amount) }655                data = ERC20.transfer(to: recipient, amount: amount)656                description = .tokenTransfer(token: token, contract: token.address, to: recipient, amount: amount)657            } else {658                amount = .zero659                data = ERC20.approve(spender: recipient, amount: .zero)660                description = .tokenApproval(token: token, contract: token.address, spender: recipient, amount: .zero)661            }662            destination = token.address663            gasLimit = try await estimate(to: token.address, value: .zero, data: data)664            // simulate: a compliant token returns nothing (old tokens) or true665            let returned: Bytes666            do {667                returned = try await rpc.ethCall(to: token.address.checksummed, data: data, from: owner)668            } catch NetworkError.rpc(_, let message) {669                throw EthereumRefusal.simulationFailed(message)670            }671            guard returned.isEmpty || ERC20.decodeUInt(returned) == UInt256(1) else { throw EthereumRefusal.unexpectedTokenReturn }672        }673674        // OP-Stack networks (Base, OP Mainnet) charge an L1 data fee on top of gas × price: it is quoted by the675        // GasPriceOracle for this very transaction, reserved with a margin, shown and capped with the rest of the fee.676        var l1DataFee = UInt256.zero677        if network.isOPStack {678            let draft = EIP1559Transaction(chainID: network.chainID, nonce: nonce, maxPriorityFeePerGas: tip, maxFeePerGas: maxFee,679                                           gasLimit: gasLimit, to: destination, value: value, data: data)680            do {681                l1DataFee = OPStackGasOracle.withMargin(try await rpc.l1DataFee(unsignedPayload: draft.unsignedPayload))682            } catch NetworkError.rpc(_, let message) {683                throw EthereumRefusal.simulationFailed(message)684            }685            if call == nil, sendMax {686                // sending everything: the L1 fee comes out of the amount as well687                guard value > l1DataFee else {688                    throw EthereumRefusal.insufficientFundsForFee(available: balance, required: (try fee(gasLimit)).addingReportingOverflow(l1DataFee).0)689                }690                value = value - l1DataFee691                amount = value692            }693        }694        let (maximumFee, feeOverflow) = (try fee(gasLimit)).addingReportingOverflow(l1DataFee)695        let (total, overflow) = maximumFee.addingReportingOverflow(value)696        guard !overflow, !feeOverflow else { throw EthereumRefusal.feeOutOfRange }697        guard total <= balance else {698            if call == nil { throw EthereumRefusal.insufficientBalance(available: balance, required: total) }699            throw EthereumRefusal.insufficientFundsForFee(available: balance, required: maximumFee)700        }701        if call == nil, !value.isZero, maximumFee.multipliedReportingOverflow(by: 20).0 > value {702            let share = (Double(maximumFee.description) ?? 0) / max(1, Double(value.description) ?? 1) * 10_000703            warnings.append(.highFeeShare(basisPoints: share.isFinite ? Int(min(share, 1e9)) : Int(1e9)))704        }705        let tx = EIP1559Transaction(chainID: network.chainID, nonce: nonce, maxPriorityFeePerGas: min(tip, maxFee), maxFeePerGas: maxFee,706                                    gasLimit: gasLimit, to: destination, value: value, data: data)707        guard EVMFeeRules.maximumCost(tx, l1DataFee: l1DataFee) == total else { throw EthereumRefusal.feeOutOfRange }708        try await enforceUnauditedEthereumLimits(tx, network: network, l1DataFee: l1DataFee)709        if !network.isTest, MainnetPolicy.unauditedMainnet { warnings.append(.unauditedMainnet) }710        return EthereumSendReview(id: UUID(), network: network, createdAt: now(), from: from, asset: asset, recipient: recipient, amount: amount,711                                  transaction: tx, call: description, feeTier: feeTier, baseFee: fees.baseFee, maximumFee: maximumFee,712                                  maximumTotalCost: total, isSendMax: sendMax, warnings: warnings, l1DataFee: l1DataFee)713    }714715    /// Structural limits every transaction must respect before the wallet signs it, whatever its origin.716    func checkSignable(_ tx: EIP1559Transaction, network: EthereumNetwork) throws {717        guard tx.chainID == network.chainID else { throw EthereumRefusal.chainMismatch(expected: network.chainID, found: tx.chainID) }718        guard let to = tx.to else { throw EthereumRefusal.unsupportedTransaction("Contract creation is not supported.") }719        guard !to.isZero else { throw EthereumRefusal.zeroAddress }720        guard tx.accessList.isEmpty else { throw EthereumRefusal.unsupportedTransaction("Access lists are not supported.") }721        guard tx.maxPriorityFeePerGas <= tx.maxFeePerGas, !tx.maxFeePerGas.isZero, tx.maxFeePerGas < UInt256(100_000_000_000_000) else {722            throw EthereumRefusal.feeOutOfRange723        }724        guard tx.gasLimit >= Self.ethereumTransferGas else { throw EthereumRefusal.unsupportedTransaction("The gas limit is below 21 000.") }725        guard tx.gasLimit <= Self.ethereumGasLimitCeiling else {726            throw EthereumRefusal.gasLimitTooHigh(estimated: tx.gasLimit, limit: Self.ethereumGasLimitCeiling)727        }728        guard tx.data.count <= 4_096, tx.maximumCost != nil else { throw EthereumRefusal.unsupportedTransaction("Call data too large or cost out of range.") }729        if case .transfer(let recipient, _)? = ERC20.decodeCall(tx.data) {730            guard !recipient.isZero else { throw EthereumRefusal.zeroAddress }731            guard recipient != to else { throw EthereumRefusal.recipientIsTokenContract }732        }733    }734735    /// Ceilings of an unaudited build on mainnet, applied when a transaction is prepared and again before it is signed:736    /// ether value ≤ 0.05 ETH; an ERC-20 transfer ≤ 150 USD at a fresh price (a token without known price cannot be sent);737    /// approvals only to revoke (amount zero); no undecodable call data; maximum fee (gas limit × maxFeePerGas) ≤ 0.01 ETH738    /// (QYV-SVC-009: fee figures come from one endpoint, the ceiling bounds what a hostile one can make a transaction cost).739    ///740    /// Every EVM network that is not a test network is a mainnet here. Where the native coin is ether (Ethereum, Base,741    /// Arbitrum, OP Mainnet) the two ether ceilings apply as they are. Elsewhere (POL, BNB, AVAX) the value is capped at742    /// 150 USD and the maximum fee at 5 USD, both at a fresh price of the coin: without one the transaction is refused.743    /// `l1DataFee` (OP-Stack, known when the transaction is prepared) counts in the maximum fee.744    func enforceUnauditedEthereumLimits(_ tx: EIP1559Transaction, network: EthereumNetwork, l1DataFee: UInt256 = .zero) async throws {745        guard !network.isTest, MainnetPolicy.unauditedMainnet else { return }746        let limits = MainnetPolicy.limits747        let valueCeiling = MainnetPolicy.nativeValueCeiling(for: network), feeCeiling = MainnetPolicy.feeCeiling(for: network)748        guard let maximumFee = EVMFeeRules.maximumFee(gasLimit: tx.gasLimit, maxFeePerGas: tx.maxFeePerGas, l1DataFee: l1DataFee) else {749            throw WalletError.exceedsUnauditedLimit(limit: "a maximum fee of " + MainnetPolicy.describe(feeCeiling, network: network) + " per transaction")750        }751        // the native coin's price is fetched once, and only when a ceiling is expressed in dollars752        var nativePrice: Double?753        if valueCeiling.needsPrice || feeCeiling.needsPrice { nativePrice = try await limitUSDPrice(network.priceID) }754        switch valueCeiling.allows(wei: tx.value, usdPrice: nativePrice) {755        case true?: break756        case false?: throw WalletError.exceedsUnauditedLimit(limit: MainnetPolicy.describe(valueCeiling, network: network) + " per transaction")757        case nil: throw WalletError.unauditedLimitUnverifiable("The \(network.nativeSymbol) amount cannot be valued, so it cannot be checked against the limit.")758        }759        switch feeCeiling.allows(wei: maximumFee, usdPrice: nativePrice) {760        case true?: break761        case false?:762            throw WalletError.exceedsUnauditedLimit(limit: "a maximum fee of " + MainnetPolicy.describe(feeCeiling, network: network) + " per transaction")763        case nil: throw WalletError.unauditedLimitUnverifiable("The fee cannot be valued, so it cannot be checked against the limit.")764        }765        guard !tx.data.isEmpty else { return }766        switch ERC20.decodeCall(tx.data) {767        case .approve(_, let amount)?:768            guard amount.isZero else {769                throw WalletError.unauditedLimitUnverifiable("On mainnet this build only signs approvals that revoke an allowance (amount zero).")770            }771        case .transfer(_, let amount)?:772            // the built-in tables only: a token of the stored profile never brings its own price identifier (QYV-SVC-087)773            guard let to = tx.to, let token = BuiltInTokens.token(to, network: network), let priceID = token.priceID else {774                throw WalletError.unauditedLimitUnverifiable("This token has no known price, so its value cannot be checked against the limit of \(Int(limits.tokenUSDPerTransaction)) USD.")775            }776            let price = try await limitUSDPrice(priceID, pricing: BuiltInTokens.isDollarPegged(to, network: network) ? .dollarPegged : .twoSources)777            guard let units = Double(BaseUnits.format(amount, decimals: token.decimals)), units.isFinite else {778                throw WalletError.unauditedLimitUnverifiable("The token amount cannot be valued.")779            }780            guard units * price <= limits.tokenUSDPerTransaction else {781                throw WalletError.exceedsUnauditedLimit(limit: "\(Int(limits.tokenUSDPerTransaction)) USD per token transfer")782            }783        case nil:784            throw WalletError.unauditedLimitUnverifiable("On mainnet this build does not sign call data it cannot decode.")785        }786    }787788    /// Signs with the account key (m/44'/60'/0'/0/0) read from the vault for the duration of the signature, then checks789    /// the result: decodable, valid signature, sender is this account, content identical to what was reviewed.790    func signEthereum(_ tx: EIP1559Transaction, network: EthereumNetwork) async throws -> SignedEIP1559Transaction {791        let from = try ethereumAccount(network)792        // the account the vault vouches for, not only the one the profile file names (QYV-SVC-011)793        if let trusted = await trustedPublicData(), trusted.ethereum != from {794            throw WalletError.signingFailed("The account of the profile is not the one the vault holds. Lock and unlock the wallet, then try again.")795        }796        try checkSignable(tx, network: network)797        try await enforceUnauditedEthereumLimits(tx, network: network)798        let signed: SignedEIP1559Transaction = try await withMasterKey { master in799            var key = try master.derive(StandardPaths.ethereum())800            // declared first, so it runs last: once `secret` has let go of the buffer, `key` erases it in place801            defer { key.wipe() }802            guard var secret = key.privateKey else { throw WalletError.signingFailed("no private key") }803            defer { SecureMemory.zero(&secret) }804            guard try EthereumAddress(publicKey: key.publicKey) == from else {805                throw WalletError.signingFailed("The recovery phrase in the vault does not match this wallet's account.")806            }807            return try tx.sign(privateKey: secret)808        }809        guard let decoded = try? SignedEIP1559Transaction.decode(signed.raw), decoded.transaction == tx, (try? decoded.sender()) == from else {810            throw WalletError.signingFailed("The signed transaction does not verify.")811        }812        return signed813    }814815    func broadcastEthereum(_ signed: SignedEIP1559Transaction, rpc: EthereumRPC) async throws -> EthereumBroadcastResult {816        let local = signed.hashHex817        let remote = try await rpc.sendRawTransaction(signed.raw)818        guard remote.isEmpty || remote.lowercased() == local else { throw WalletError.broadcastMismatch(local: local, remote: remote) }819        noteBroadcast(.evm(rpc.network), id: local)820        return EthereumBroadcastResult(hash: local, rawHex: "0x" + Hex.encode(signed.raw), nonce: signed.transaction.nonce)821    }822823    /// Signs the reviewed transaction locally and broadcasts it. **Needs an unlocked vault (full wallet). Network.**824    /// The hash is recomputed from the signed bytes and compared with the endpoint's answer (`broadcastMismatch`).825    public func signAndBroadcastEthereum(_ review: EthereumSendReview) async throws(WalletError) -> EthereumBroadcastResult {826        try await run {827            let from = try ethereumAccount(review.network)828            guard usesEVM(review.network), review.from == from else { throw WalletError.stalePlan("The review was made for another account or network.") }829            let rpc = try await verifiedRPC(review.network)830            let signed = try await signEthereum(review.transaction, network: review.network)831            let result = try await broadcastEthereum(signed, rpc: rpc)832            paidRecipients.insert(Self.paidKey(.evm(review.network), review.recipient.checksummed.lowercased()))833            return result834        }835    }836837    /// Status of a broadcast transaction from its receipt. **Network.** `hash` is "0x" + 64 hexadecimal digits.838    public func trackEthereumTransaction(hash: String, network: EthereumNetwork? = nil) async throws(WalletError) -> EthereumTransactionStatus {839        try await run {840            let h = hash.lowercased()841            guard h.hasPrefix("0x"), h.utf8.count == 66, Hex.decode(String(h.dropFirst(2))) != nil else { throw WalletError.invalidInput("Not a transaction hash.") }842            let network = network ?? profile.ethereumNetwork843            guard usesEVM(network) else { throw WalletError.chainNotActive(network.displayName) }844            _ = try ethereumAccount(network)845            let rpc = try await verifiedRPC(network)846            guard let receipt = try await rpc.receipt(h) else { return .pending }847            let (paid, overflow) = receipt.effectiveGasPrice.multipliedReportingOverflow(by: receipt.gasUsed)848            let fee: UInt256? = overflow || receipt.effectiveGasPrice.isZero ? nil : paid849            return receipt.success ? .confirmed(blockNumber: receipt.blockNumber, gasUsed: receipt.gasUsed, feePaid: fee)850                : .failed(blockNumber: receipt.blockNumber, gasUsed: receipt.gasUsed, feePaid: fee)851        }852    }853854    // MARK: Cold signing855856    /// The unsigned transaction of a review (0x02 ‖ rlp, as "0x…" text and QR frames) for a cold device. No secret, no network.857    public func exportUnsignedEthereum(_ review: EthereumSendReview) async throws(WalletError) -> QRExport {858        try await run {859            try checkSignable(review.transaction, network: review.network)860            return try QRExport.make(text: "0x" + Hex.encode(review.transaction.unsignedPayload))861        }862    }863864    private func decodeHexPayload(_ input: [String]) throws -> Bytes {865        let text = try QRExport.text(from: input)866        guard text.hasPrefix("0x"), text.utf8.count <= 20_000, let bytes = Hex.decode(String(text.dropFirst(2))), !bytes.isEmpty else {867            throw WalletError.invalidPayload("Not a hexadecimal transaction payload.")868        }869        return bytes870    }871872    func describeCall(_ tx: EIP1559Transaction, network: EthereumNetwork) -> (EthereumCallDescription, [EthereumSendWarning]) {873        guard !tx.data.isEmpty, let to = tx.to else { return (.etherTransfer, []) }874        let token = knownToken(to, network: network)875        var warnings = [EthereumSendWarning]()876        switch ERC20.decodeCall(tx.data) {877        case .transfer(let recipient, let amount)?:878            if token == nil { warnings.append(.unknownTokenContract) }879            return (.tokenTransfer(token: token, contract: to, to: recipient, amount: amount), warnings)880        case .approve(let spender, let amount)?:881            if token == nil { warnings.append(.unknownTokenContract) }882            if ERC20.isUnlimited(amount) { warnings.append(.unlimitedApproval) }883            if amount.isZero { warnings.append(.revokesApproval) }884            return (.tokenApproval(token: token, contract: to, spender: spender, amount: amount), warnings)885        case nil:886            return (.unknown(dataHex: "0x" + Hex.encode(tx.data)), [.blindSigning])887        }888    }889890    /// Decodes and reviews an unsigned transaction on the cold device ("0x02…" text or QR frames). No secret, no network.891    ///892    /// The chain id must be the active network's. ERC-20 `transfer` and `approve` calls are decoded; any other call data893    /// is shown as raw hexadecimal with the `.blindSigning` warning. Fee and gas limits are bounded like for a local send.894    public func reviewColdEthereumPayload(_ input: [String]) async throws(WalletError) -> ColdEthereumReview {895        try await run { try coldReview(try decodeHexPayload(input)) }896    }897898    /// The network a transaction received from outside is for: the primary EVM network, or the network of an enabled899    /// chain, whose chain identifier the transaction names. Any other identifier is a `chainMismatch`.900    func coldNetwork(chainID: UInt64) throws -> EthereumNetwork {901        if chainID == profile.ethereumNetwork.chainID { return profile.ethereumNetwork }902        if let network = EthereumNetwork(chainID: chainID), usesEVM(network) { return network }903        throw EthereumRefusal.chainMismatch(expected: profile.ethereumNetwork.chainID, found: chainID)904    }905906    private func coldReview(_ payload: Bytes) throws -> ColdEthereumReview {907        let tx: EIP1559Transaction908        do {909            tx = try EIP1559Transaction.decodeUnsigned(payload)910        } catch {911            throw WalletError.invalidPayload("Not an unsigned EIP-1559 transaction.")912        }913        let network = try coldNetwork(chainID: tx.chainID)914        _ = try ethereumAccount(network)915        // canonical encoding only: what is reviewed is exactly what is signed916        guard tx.unsignedPayload == payload else { throw WalletError.invalidPayload("The transaction encoding is not canonical.") }917        try checkSignable(tx, network: network)918        let (call, callWarnings) = describeCall(tx, network: network)919        var warnings = callWarnings920        let (fee, _) = tx.maxFeePerGas.multipliedReportingOverflow(by: tx.gasLimit)921        guard let total = tx.maximumCost, let to = tx.to else { throw EthereumRefusal.feeOutOfRange }922        if to == profile.ethereumAddress { warnings.append(.recipientIsOwnAddress) }923        if !network.isTest, MainnetPolicy.unauditedMainnet { warnings.append(.unauditedMainnet) }924925        func eth(_ wei: UInt256) -> String { BaseUnits.format(wei, decimals: network.nativeDecimals) + " " + network.nativeSymbol }926        var summary = ["Network: \(network.displayName) (chain \(tx.chainID))", "Nonce: \(tx.nonce)"]927        switch call {928        case .etherTransfer:929            summary.append("Send \(eth(tx.value)) to \(to.checksummed)")930        case .tokenTransfer(let token, let contract, let recipient, let amount):931            summary.append(token.map { "Send \(BaseUnits.format(amount, decimals: $0.decimals)) \($0.symbol) to \(recipient.checksummed)" }932                ?? "Token transfer of \(amount) base units to \(recipient.checksummed)")933            summary.append("Token contract: \(contract.checksummed)")934            if !tx.value.isZero { summary.append("Ether attached: \(eth(tx.value))") }935        case .tokenApproval(let token, let contract, let spender, let amount):936            let what = ERC20.isUnlimited(amount) ? "an UNLIMITED amount" : (token.map { "\(BaseUnits.format(amount, decimals: $0.decimals)) \($0.symbol)" } ?? "\(amount) base units")937            summary.append(amount.isZero ? "Revoke the allowance of \(spender.checksummed)" : "Allow \(spender.checksummed) to spend \(what)")938            summary.append("Token contract: \(contract.checksummed)")939            if !tx.value.isZero { summary.append("Ether attached: \(eth(tx.value))") }940        case .unknown(let hex):941            summary.append("Contract call to \(to.checksummed) with \(eth(tx.value))")942            summary.append("Call data (\(tx.data.count) bytes): \(hex)")943        }944        summary.append("Maximum fee: \(eth(fee)) (gas limit \(tx.gasLimit))")945        if network.isOPStack {946            // the L1 data fee is charged by the network on top of gas × price and depends on chain state947            summary.append("Not included: the L1 data fee of \(network.displayName). An offline device cannot compute it; the online device showed it when the transaction was prepared.")948        }949        summary.append("Maximum total cost: \(eth(total))" + (network.isOPStack ? " plus the L1 data fee" : ""))950        summary += warnings.map { "Warning: \($0.message)" }951        return ColdEthereumReview(network: network, transaction: tx, call: call, maximumFee: fee, maximumTotalCost: total, warnings: warnings, summary: summary)952    }953954    /// Signs an unsigned transaction on the cold device. **Needs an unlocked vault (full wallet). No network.**955    /// Undecodable call data is refused unless `allowBlindSigning` is true. Returns the raw signed transaction ("0x…" text956    /// and QR frames) to carry back to the online device.957    public func signColdEthereumPayload(_ input: [String], allowBlindSigning: Bool = false) async throws(WalletError) -> ColdSignedEthereum {958        try await run {959            let review = try coldReview(try decodeHexPayload(input))960            if review.warnings.contains(.blindSigning), !allowBlindSigning {961                throw EthereumRefusal.unsupportedTransaction("The call data cannot be decoded. Blind signing must be allowed explicitly.")962            }963            let signed = try await signEthereum(review.transaction, network: review.network)964            return ColdSignedEthereum(review: review, hash: signed.hashHex, export: try QRExport.make(text: "0x" + Hex.encode(signed.raw)))965        }966    }967968    /// Broadcasts a transaction signed by the cold device ("0x02…" text or QR frames) from the online device. **Network.**969    /// The signature must verify and recover this wallet's account, the chain id must be the active network's, the970    /// ceilings of an unaudited build are applied again, and the nonce must not be already used.971    public func broadcastSignedEthereum(_ input: [String]) async throws(WalletError) -> EthereumBroadcastResult {972        try await run {973            let raw = try decodeHexPayload(input)974            let signed: SignedEIP1559Transaction975            do {976                signed = try SignedEIP1559Transaction.decode(raw)977            } catch {978                throw WalletError.invalidPayload("Not a signed EIP-1559 transaction, or its signature does not verify.")979            }980            let network = try coldNetwork(chainID: signed.transaction.chainID)981            let from = try ethereumAccount(network)982            guard signed.raw == raw else { throw WalletError.invalidPayload("The transaction encoding is not canonical.") }983            try checkSignable(signed.transaction, network: network)984            guard (try? signed.sender()) == from else { throw EthereumRefusal.foreignSender }985            // as for Bitcoin, Solana and TRON: the ceilings of an unaudited build are applied again before the broadcast (QYV-SVC-081)986            try await enforceUnauditedEthereumLimits(signed.transaction, network: network)987            let rpc = try await verifiedRPC(network)988            let latest = try await agreedTransactionCount(rpc, owner: from.checksummed, tag: "latest")989            guard signed.transaction.nonce >= latest else {990                throw EthereumRefusal.unsupportedTransaction("Nonce \(signed.transaction.nonce) was already used (the account is at \(latest)).")991            }992            return try await broadcastEthereum(signed, rpc: rpc)993        }994    }995}996
Files main
Menu

Theme