SPB Git

Repository Public

WalletService+Tron.swift 45.7 KB 700 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraWallet/WalletService+Tron.swift8// Module           : Qyvora Wallet9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraMath43import QyvoraCore44import QyvoraEthereum45import QyvoraNetworking46import QyvoraTron4748/// The TRON part of a send review: the plan the transaction was built from.49public struct TronSendDetails: Equatable, Sendable {50    public let network: TronNetwork51    /// The unsigned transaction with its resources and fees (`plan.review` is what a cold device would decode).52    public let plan: TronSendPlan53    /// When the transaction stops being valid.54    public var expiresAt: Date { Date(timeIntervalSince1970: TimeInterval(plan.transaction.expiration / 1000)) }55}5657extension WalletService {58    // MARK: Clients and accounts5960    static let tronPriceID = "tron"6162    /// CoinGecko identifiers of the built-in TRC-20 tokens, by contract.63    static let tronTokenPriceIDs: [String: String] = [64        "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t": "tether",65        "TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8": "usd-coin",66    ]6768    /// Longest validity left that a TRON transaction may have when it is signed, in milliseconds: the longest lifetime69    /// the planner writes (one hour) plus five minutes for a device clock that runs late. The protocol itself allows70    /// a day; a transaction that stays valid that long can be held back and broadcast much later, or elsewhere.71    static let tronMaximumSigningWindowMilliseconds: UInt64 = 3_900_0007273    /// Validity of a transaction prepared for a cold device, in seconds: long enough to carry it over by QR codes.74    static let tronColdLifetime: UInt64 = 1_8007576    func tronAccount(_ network: TronNetwork) throws -> TronAddress {77        _ = try requireWallet()78        try requireAllowed(.tron(network))79        guard let text = profile.tronAddress, let address = TronAddress(text) else {80            throw WalletError.featureUnavailable("This wallet has no TRON account.")81        }82        return address83    }8485    /// Verifies once per session (and per endpoint list) that the nodes serve the expected network (genesis block id).86    func verifiedTron(_ network: TronNetwork) async throws -> TronClient {87        try requireAllowed(.tron(network))88        if gate.isOffline { throw WalletError.offline }89        let client = TronClient(network: network, endpoints: profile.tronEndpoints, transport: gate, apiKey: tronAPIKey, pacing: tronPacing)90        guard client.isConfigured else { throw WalletError.network("No TRON node is configured for \(network.displayName).") }91        let key = "trx|\(network.rawValue)|" + (profile.tronEndpoints.fullNodes[network.rawValue] ?? []).joined(separator: ",")92        if !verifiedChains.contains(key) {93            do {94                try await client.verifyChain()95            } catch NetworkError.disagreement(let text) {96                throw WalletError.wrongChain(text)97            }98            verifiedChains.insert(key)99        }100        return client101    }102103    /// QYV-SVC-040. A TRON transaction names no network, and this wallet's account is the same key on every one: a104    /// transaction prepared for a test network whose reference block is in fact a block of the main network — which105    /// a node of the test network can arrange, since the reference block comes from it — would be executed on the106    /// main network with real funds, whatever the mainnet switch and the limits say. Before a test-network107    /// transaction is shown for review, and again before it is signed, the wallet asks the main-network nodes whether108    /// they would accept its reference block, and refuses when they would. When no main-network node answers, nothing109    /// is signed (the check cannot be made). Only `ref_block_bytes` and `ref_block_hash` matter: the request carries110    /// a block number, no address and no amount.111    func requireNotValidOnTronMainnet(_ transaction: TronTransaction, network: TronNetwork) async throws {112        guard network.isTest else { return }113        if gate.isOffline { throw WalletError.offline }114        let mainnet = TronClient(network: .mainnet, endpoints: profile.tronEndpoints, transport: gate, apiKey: tronAPIKey, pacing: tronPacing)115        guard mainnet.isConfigured else {116            throw WalletError.network("No TRON mainnet node is configured: QYVORA cannot check that this test transaction is not also valid on the main network, and does not sign it.")117        }118        let accepted: Bool119        do {120            let key = "trx|\(TronNetwork.mainnet.rawValue)|" + (profile.tronEndpoints.fullNodes[TronNetwork.mainnet.rawValue] ?? []).joined(separator: ",")121            if !verifiedChains.contains(key) {122                try await mainnet.verifyChain()123                verifiedChains.insert(key)124            }125            accepted = try await mainnet.acceptsReference(refBlockBytes: transaction.refBlockBytes, refBlockHash: transaction.refBlockHash)126        } catch let e as NetworkError {127            if case .offline = e { throw WalletError.offline }128            throw WalletError.network("The TRON mainnet nodes did not answer as expected: QYVORA cannot check that this test transaction is not also valid on the main network, and does not sign it. (\(e.summary))")129        }130        guard !accepted else {131            throw WalletError.wrongChain("The reference block this \(network.displayName) node gave is a block of TRON mainnet: the transaction would be valid on the main network, with real funds. Nothing was signed. Change the \(network.displayName) node in the settings.")132        }133    }134135    /// The transaction of a plan must be the payment its review shows: same sender, recipient, asset and amount.136    /// A review cannot be built or changed through the public interface; this is the check behind that.137    static func requireMatches(_ review: SendReview, plan: TronSendPlan) throws {138        let refuse = WalletError.stalePlan("The transaction does not match its review.")139        let decoded = TronTransactionReview(plan.transaction)140        guard decoded.permissionID == 0, !decoded.requiresBlindSigning else { throw refuse }141        switch (review.asset, decoded.action) {142        case (.native, .trxTransfer(let from, let to, let amountSun)):143            guard from.base58 == review.from, to.base58 == review.recipient, UInt256(amountSun) == review.amount, review.amountDecimals == TronUnits.decimals,144                  plan.transaction.feeLimit == 0 else { throw refuse }145        case (.token(let token), .trc20Transfer(let from, let contract, let to, let amount)):146            guard from.base58 == review.from, to.base58 == review.recipient, amount == review.amount, contract.base58 == token.address,147                  token.decimals == review.amountDecimals, plan.transaction.memo.isEmpty else { throw refuse }148        default:149            throw refuse150        }151        guard plan.from.base58 == review.from, plan.to.base58 == review.recipient, plan.amount == review.amount else { throw refuse }152    }153154    // MARK: Token list155156    static func builtInTronTokens(_ network: TronNetwork) -> [ChainToken] {157        let chain = ChainRegistry.id(network)158        return TronBuiltInTokens.tokens(for: network).map {159            ChainToken(chain: chain, address: $0.contract.base58, symbol: $0.symbol, name: $0.name, decimals: $0.decimals, standard: .trc20,160                       priceID: tronTokenPriceIDs[$0.contract.base58], note: $0.note)161        }162    }163164    func knownTronTokens(_ network: TronNetwork) -> [ChainToken] {165        let chain = ChainRegistry.id(network)166        var seen = Set<String>()167        return (Self.builtInTronTokens(network) + profile.customTronTokens.filter { $0.chain == chain }).filter { seen.insert($0.address).inserted }168    }169170    func listedTronTokens(_ network: TronNetwork) -> [ChainToken] {171        let hidden = Set(profile.hiddenTokens)172        return knownTronTokens(network).filter { !hidden.contains($0.id) }173    }174175    /// Symbol, name and decimals read from the contract and bounded. Throws when the address is not a TRC-20 token.176    static func readTronToken(_ client: TronClient, contract: TronAddress, chain: ChainID) async throws -> ChainToken {177        guard try await client.account(contract).isContract else { throw WalletError.tron(.tokenIsNotAContract) }178        let decimals = try await client.tokenDecimals(contract)179        guard decimals <= maximumTokenDecimals else { throw WalletError.untrustedResponse("token decimals above \(maximumTokenDecimals)") }180        func clean(_ s: String, _ limit: Int) -> String {181            String(s.unicodeScalars.filter { $0.isASCII && $0.value >= 0x20 && $0.value < 0x7f }.map(Character.init)).trimmingCharacters(in: .whitespaces).prefix(limit).description182        }183        let symbol = clean(try await client.tokenSymbol(contract), 16)184        guard !symbol.isEmpty else { throw WalletError.untrustedResponse("token symbol unreadable") }185        let name = ((try? await client.tokenName(contract)) ?? "").isEmpty ? symbol : clean((try? await client.tokenName(contract)) ?? symbol, 48)186        return ChainToken(chain: chain, address: contract.base58, symbol: symbol, name: name.isEmpty ? symbol : name, decimals: decimals, standard: .trc20, isCustom: true)187    }188189    // MARK: Synchronization190191    static let tronHistoryLimit = 50192    static let tronDetectedLimit = 10193194    func syncTron(_ network: TronNetwork) async throws {195        try await runChainSync(.tron(network)) { try await self.performTronSync(network) }196    }197198    private func performTronSync(_ network: TronNetwork) async throws {199        let kind = ChainKind.tron(network)200        let chain = ChainRegistry.id(network)201        let owner = try tronAccount(network)202        let client = try await verifiedTron(network)203        var notes = [String]()204205        noteProgress(kind, stage: "Reading the account", completed: 0, total: 4)206        let head = try await client.latestBlock()207        let account = try await client.account(owner)208        let resources = try await client.resources(owner)209210        noteProgress(kind, stage: "Reading chain parameters", completed: 1, total: 4)211        let parameters = try await client.chainParameters()212213        noteProgress(kind, stage: "Reading token balances", completed: 2, total: 4)214        let listed = listedTronTokens(network)215        let alreadyVerified = verifiedTronTokens216        let results = try await boundedMap(listed, limit: 2) { token -> (ChainHolding, Bool) in217            guard let contract = TronAddress(token.address) else {218                return (ChainHolding(token: token, amount: nil, reason: "The contract address of this token is invalid.", warning: nil, listed: true), false)219            }220            do {221                var checked = alreadyVerified.contains(token.id)222                if !checked {223                    let decimals = try await client.tokenDecimals(contract)224                    guard decimals == token.decimals else {225                        return (ChainHolding(token: token, amount: nil, reason: "The contract reports \(decimals) decimals, the token list says \(token.decimals).",226                                             warning: nil, listed: true), false)227                    }228                    checked = true229                }230                return (ChainHolding(token: token, amount: try await client.tokenBalance(token: contract, owner: owner), reason: nil, warning: nil, listed: true), checked)231            } catch let e as NetworkError {232                if case .offline = e { throw e }233                return (ChainHolding(token: token, amount: nil, reason: Self.describe(WalletError.from(e)), warning: nil, listed: true), false)234            }235        }236        for (holding, checked) in results where checked { verifiedTronTokens.insert(holding.token.id) }237        var holdings = results.map(\.0)238239        noteProgress(kind, stage: "Reading history", completed: 3, total: 4)240        var history: [ActivityEntry]?241        var historyReason: String?242        // an address the chain never saw cannot have sent anything243        var hasOutgoing: Bool? = account.isActivated ? nil : false244        if client.hasHistory {245            do {246                let native = try await client.transactions(of: owner, limit: Self.tronHistoryLimit)247                let transfers = try await client.tokenTransfers(of: owner, limit: Self.tronHistoryLimit)248                let tokens = Dictionary(uniqueKeysWithValues: knownTronTokens(network).map { ($0.address, $0) })249                history = Self.activity(native: native.items, transfers: transfers.items, owner: owner, chain: chain, tokens: tokens)250                let sent = native.items.contains { $0.from == owner } || transfers.items.contains { $0.from == owner }251                let complete = native.nextFingerprint == nil && transfers.nextFingerprint == nil252                if account.isActivated { hasOutgoing = sent ? true : (complete ? false : nil) }253                if !complete { notes.append("Only the \(Self.tronHistoryLimit) most recent entries of the history are shown.") }254                if account.isActivated, hasOutgoing == nil {255                    // a busy account whose recent entries are all incoming: ask the index for what the account itself256                    // sent (one bounded request). An entry it initiated settles the question; an empty answer too; an257                    // index that ignores the filter leaves it open.258                    if let own = try? await client.transactions(of: owner, limit: Self.tronOutgoingProbeLimit, onlyFrom: true) {259                        if own.items.contains(where: { $0.from == owner }) {260                            hasOutgoing = true261                        } else if own.items.isEmpty, own.nextFingerprint == nil {262                            hasOutgoing = false263                        }264                    }265                }266267                // tokens seen in the history and not in the list: read on chain, kept apart as "detected"268                let known = Set(knownTronTokens(network).map(\.address)), hidden = Set(profile.hiddenTokens)269                var candidates = [TronAddress]()270                for t in transfers.items {271                    guard let token = t.token, !token.isZero, !known.contains(token.base58), !candidates.contains(token),272                          !hidden.contains("\(chain.rawValue):\(token.base58)") else { continue }273                    candidates.append(token)274                    if candidates.count == Self.tronDetectedLimit { break }275                }276                let detected = try await boundedMap(candidates, limit: 2) { contract -> ChainHolding? in277                    do {278                        let token = try await Self.readTronToken(client, contract: contract, chain: chain)279                        let balance = try await client.tokenBalance(token: contract, owner: owner)280                        return balance.isZero ? nil : ChainHolding(token: token, amount: balance, reason: nil, warning: nil, listed: false)281                    } catch let e as NetworkError {282                        if case .offline = e { throw e }283                        return nil284                    } catch is WalletError {285                        return nil286                    }287                }288                holdings += detected.compactMap { $0 }289            } catch let e as NetworkError {290                if case .offline = e { throw e }291                historyReason = Self.describe(WalletError.from(e))292            }293        } else {294            historyReason = "No history index is configured for \(network.displayName). Balances and payments work; the history is not shown."295        }296        // bandwidth or energy already consumed is the trace of a transaction this account sent in the last day: it297        // counts whatever the index says (an index can lag, or be wrong)298        if account.isActivated, resources.freeNetUsed > 0 || resources.netUsed > 0 || resources.energyUsed > 0 { hasOutgoing = true }299300        guard profile.kind != nil, Self.activeKinds(profile).contains(kind), profile.tronAddress == owner.base58,301              let identity = Self.tronIdentity(profile, network: network) else {302            throw WalletError.stalePlan("the active network changed during synchronization")303        }304        tronRecords[network] = TronChainRecord(identity: identity, network: network, address: owner.base58, synchronizedAt: now(), blockNumber: head.number,305                                               balanceSun: account.balanceSun, isActivated: account.isActivated, resources: .init(resources),306                                               parameters: .init(parameters), holdings: holdings, history: history, historyReason: historyReason,307                                               hasOutgoing: hasOutgoing, notes: notes, isFromPreviousSession: nil)308        persistTron(network)309    }310311    /// The history of the index as activity lines. A TRC-20 transfer appears twice in the index (as a contract call of312    /// the account and as a token transfer): the token transfer is kept, the call is dropped.313    static func activity(native: [TronTransfer], transfers: [TronTransfer], owner: TronAddress, chain: ChainID, tokens: [String: ChainToken]) -> [ActivityEntry] {314        func direction(_ from: TronAddress, _ to: TronAddress?) -> ActivityEntry.Direction {315            let f = from == owner, t = to == owner316            if f && t { return .selfTransfer }317            if f { return .sent }318            if t { return .received }319            return .none320        }321        func status(_ t: TronTransfer) -> ActivityEntry.Status {322            if !t.succeeded { return .failed }323            return t.confirmed ? .finalized : .confirmed(confirmations: nil)324        }325        let tokenTransactionIDs = Set(transfers.map(\.txID))326        var entries = [ActivityEntry]()327        for (n, t) in native.prefix(200).enumerated() {328            let d = direction(t.from, t.to)329            let fee: UInt256? = t.from == owner ? t.feeSun.map { UInt256($0) } : nil330            switch t.kind {331            case .trx:332                entries.append(ActivityEntry(chain: chain, id: "trx:\(t.txID):\(n)", hash: t.txID, direction: d, counterparty: d == .received ? t.from.base58 : t.to?.base58,333                                             amount: t.amount, decimals: TronUnits.decimals, symbol: "TRX", fee: fee, status: status(t), time: t.date,334                                             blockHeight: t.blockNumber, kind: .native))335            case .other, .trc20:336                if t.contractType == "TriggerSmartContract", tokenTransactionIDs.contains(t.txID) { continue }337                let kind: ActivityEntry.Kind = t.contractType == "TriggerSmartContract" ? .contract(method: nil) : .unknown(description: t.contractType)338                entries.append(ActivityEntry(chain: chain, id: "call:\(t.txID):\(n)", hash: t.txID, direction: t.amount.isZero ? .none : d, counterparty: t.to?.base58,339                                             amount: t.amount, decimals: TronUnits.decimals, symbol: "TRX", fee: fee, status: status(t), time: t.date,340                                             blockHeight: t.blockNumber, kind: kind))341            }342        }343        for (n, t) in transfers.prefix(200).enumerated() {344            guard let contract = t.token else { continue }345            let d = direction(t.from, t.to)346            guard d != .none else { continue }347            let known = tokens[contract.base58]348            let decimals = known?.decimals ?? t.tokenDecimals.flatMap { $0 <= maximumTokenDecimals ? $0 : nil }349            entries.append(ActivityEntry(chain: chain, id: "trc20:\(t.txID):\(n)", hash: t.txID, direction: d, counterparty: d == .received ? t.from.base58 : t.to?.base58,350                                         amount: t.amount, decimals: decimals, symbol: known?.symbol ?? t.tokenSymbol, fee: nil, status: status(t), time: t.date,351                                         blockHeight: nil,352                                         kind: .token(address: contract.base58, symbol: known?.symbol ?? t.tokenSymbol, decimals: decimals, verified: known != nil)))353        }354        return entries.sorted {355            switch ($0.time, $1.time) {356            case (nil, nil): return $0.id < $1.id357            case (nil, _): return true358            case (_, nil): return false359            case (let a?, let b?): return a != b ? a > b : $0.id < $1.id360            }361        }362    }363364    // MARK: Custom tokens365366    func addTronToken(contract text: String, network: TronNetwork) async throws -> ChainToken {367        _ = try requireWallet()368        let chain = ChainRegistry.id(network)369        guard let contract = TronAddress(text.trimmingCharacters(in: .whitespacesAndNewlines)), !contract.isZero else {370            throw WalletError.address(Self.classifyForeign(text, expected: .tron, chainName: "TRON", expectedForm: "A TRON contract address has 34 characters and starts with T."))371        }372        if let existing = knownTronTokens(network).first(where: { $0.address == contract.base58 }) {373            profile.hiddenTokens.removeAll { $0 == existing.id }374            try saveProfile()375            alignTronHoldings(network)376            return existing377        }378        let client = try await verifiedTron(network)379        let token = try await Self.readTronToken(client, contract: contract, chain: chain)380        var fresh: UInt256?381        if let owner = profile.tronAddress.flatMap({ TronAddress($0) }) { fresh = try? await client.tokenBalance(token: contract, owner: owner) }382        guard profile.kind != nil, Self.activeKinds(profile).contains(.tron(network)) else { throw WalletError.stalePlan("the active network changed") }383        profile.customTronTokens.removeAll { $0.id == token.id }384        profile.customTronTokens.append(token)385        profile.hiddenTokens.removeAll { $0 == token.id }386        verifiedTronTokens.insert(token.id)387        try saveProfile()388        alignTronHoldings(network, fresh: fresh.map { [token.id: $0] } ?? [:])389        return token390    }391392    func alignTronHoldings(_ network: TronNetwork, fresh: [String: UInt256] = [:]) {393        guard var record = tronRecords[network] else { return }394        let hidden = Set(profile.hiddenTokens)395        let listed = listedTronTokens(network)396        let listedIDs = Set(listed.map(\.id))397        var known = [String: ChainHolding]()398        for h in record.holdings { known[h.token.id] = h }399        var holdings = listed.map { token -> ChainHolding in400            if let amount = fresh[token.id] { return ChainHolding(token: token, amount: amount, reason: nil, warning: nil, listed: true) }401            if let h = known[token.id] { return ChainHolding(token: token, amount: h.amount, reason: h.reason, warning: h.warning, listed: true) }402            return ChainHolding(token: token, amount: nil, reason: "Not read yet: synchronize.", warning: nil, listed: true)403        }404        holdings += record.holdings.filter { !$0.listed && !listedIDs.contains($0.token.id) && !hidden.contains($0.token.id) }405        guard holdings != record.holdings else { return }406        record.holdings = holdings407        tronRecords[network] = record408        persistTron(network)409    }410411    // MARK: Sending412413    /// The planner policy for a network now: on an unaudited mainnet the TRX amount is capped at the fiat ceiling,414    /// converted with a fresh price (no fresh price, no transaction), and the fee limit at the policy's ceiling.415    func tronPolicy(_ network: TronNetwork, cold: Bool) async throws -> TronSendPlanner.Policy {416        var policy = TronSendPlanner.Policy()417        if cold { policy.lifetimeSeconds = Self.tronColdLifetime }418        guard !network.isTest, MainnetPolicy.unauditedMainnet else { return policy }419        let limits = MainnetPolicy.tronLimits420        policy.maximumFeeLimitSun = min(policy.maximumFeeLimitSun, limits.feePerTransaction)421        let price = try await limitUSDPrice(Self.tronPriceID)422        guard let ceiling = MainnetPolicy.nativeCeiling(usd: limits.nativeUSDPerTransaction, priceUSD: price, decimals: TronUnits.decimals) else {423            throw WalletError.unauditedLimitUnverifiable("The TRX amount cannot be valued, so it cannot be checked against the limit.")424        }425        policy.maximumAmountSun = ceiling426        return policy427    }428429    /// Entries asked of the index when it is only asked whether the account ever sent a transaction.430    static let tronOutgoingProbeLimit = 5431432    func prepareTronSend(network: TronNetwork, asset requested: ChainAsset, to: String, amount: UInt256, options: SendOptions) async throws -> SendReview {433        let kind = ChainKind.tron(network)434        let descriptor = ChainRegistry.descriptor(kind)435        // symbol and decimals of a token are the wallet's own, never the caller's description (QYV-SVC-103)436        let asset: ChainAsset437        if case .token(let asked) = requested { asset = .token(try tronToken(asked, network: network)) } else { asset = requested }438        let sender = try tronAccount(network)439        let check = try checkAddress(to, kind: kind)440        guard let recipient = TronAddress(check.canonical) else { throw WalletError.address(.malformed(chain: "TRON", expected: "")) }441        let client = try await verifiedTron(network)442        let policy = try await tronPolicy(network, cold: options.forColdSigning)443        let planner = TronSendPlanner(policy: policy)444445        let parameters = try await client.chainParameters()446        // nothing in a TRON transaction names its chain: the reference block must be one every answering node agrees on447        let reference: TronBlockReference448        let referenceConfirmations: Int449        do {450            (reference, referenceConfirmations) = try await client.referenceBlock()451        } catch NetworkError.disagreement(let text) {452            throw WalletError.wrongChain(text)453        }454        let senderAccount = try await client.account(sender)455        let resources = try await client.resources(sender)456        let recipientAccount = try await client.account(recipient)457        let state = TronSendPlanner.ChainState(network: network, parameters: parameters, reference: reference,458                                               nowMilliseconds: UInt64(max(0, now().timeIntervalSince1970 * 1000)))459        let plan: TronSendPlan460        var symbol = network.symbol461        var decimals = TronUnits.decimals462        switch asset {463        case .native:464            var memo = Bytes()465            if let text = options.memo, !text.isEmpty {466                memo = Bytes(text.utf8)467                guard memo.count <= TronTransaction.maximumMemoBytes, text.unicodeScalars.allSatisfy({ $0.value >= 0x20 && $0.value != 0x7f }) else {468                    throw WalletError.invalidInput("The note is longer than \(TronTransaction.maximumMemoBytes) bytes or contains control characters.")469                }470            }471            guard options.sendMax || amount.uint64 != nil else { throw WalletError.invalidInput("The amount is too large.") }472            plan = try planner.planTransfer(state: state, sender: senderAccount, resources: resources, recipient: recipientAccount,473                                            amount: options.sendMax ? .max : .exact(amount.uint64 ?? 0), memo: memo)474        case .token(let token):475            guard token.chain == descriptor.id, let contract = TronAddress(token.address) else { throw WalletError.invalidInput("This token belongs to another network.") }476            guard options.memo?.isEmpty ?? true else { throw WalletError.invalidInput("A note can only be attached to a TRX payment.") }477            let tokenAccount = try await client.account(contract)478            let balance = try await client.tokenBalance(token: contract, owner: sender)479            let value = options.sendMax ? balance : amount480            guard !value.isZero else { throw WalletError.tron(.zeroAmount) }481            guard value <= balance else { throw WalletError.tron(.insufficientTokenBalance(required: value, available: balance)) }482            let simulation: TronConstantResult483            do {484                simulation = try await client.simulateTokenTransfer(token: contract, from: sender, to: recipient, amount: value)485            } catch NetworkError.rpc(_, let message) {486                throw WalletError.tron(.simulationFailed(message))487            }488            plan = try planner.planTokenTransfer(state: state, sender: senderAccount, resources: resources, recipient: recipientAccount, token: tokenAccount,489                                                 tokenBalance: balance, amount: value, simulation: simulation)490            symbol = token.symbol491            decimals = token.decimals492        }493        try await enforceTronLimits(plan.transaction, network: network, maximumFeeSun: plan.maximumFeeSun)494        try await requireNotValidOnTronMainnet(plan.transaction, network: network)495496        var warnings = [SendWarning]()497        var notes = [String]()498        for note in plan.notes {499            switch note {500            case .activatesRecipient(let fee):501                warnings.append(SendWarning(id: "tron.activates-recipient", message: "This address has never been used on TRON: the payment creates it and burns \(WalletMessages.trx(fee)) on top of the amount.", isCritical: false))502            case .tokenRecipientNotActivated:503                warnings.append(SendWarning(id: "tron.recipient-not-activated", message: "The recipient's address has never been activated. The tokens will arrive, but the recipient needs TRX or energy to move them.", isCritical: false))504            case .recipientIsContract:505                warnings.append(SendWarning(id: "tron.recipient-is-contract", message: "The recipient is a smart contract. Funds sent to a contract that cannot handle them are lost.", isCritical: true))506            case .burnsTRXForBandwidth(let sun): notes.append("\(WalletMessages.trx(sun)) are burned for bandwidth: the free daily allowance of this account does not cover this transaction.")507            case .burnsTRXForEnergy(let sun): notes.append("About \(WalletMessages.trx(sun)) are burned for energy (at most \(WalletMessages.trx(plan.feeLimitSun)), the fee limit). Staked energy would avoid it.")508            case .memoFee(let sun): notes.append("The note costs \(WalletMessages.trx(sun)).")509            case .confirmWithReceipt:510                notes.append("Some tokens (USDT among them) report nothing or \"false\" for a transfer that succeeded: the outcome is read from the transaction's receipt after it is confirmed, never from that value.")511            }512        }513        if !paidRecipients.contains(Self.paidKey(kind, recipient.base58)), !hasPaidTron(recipient, network: network) {514            warnings.append(SendWarning(id: "first-payment", message: "First payment to this address: the history of this account shows no earlier payment to it. Compare every character with the address you were given, on its original source.", isCritical: false))515        }516        if !network.isTest, MainnetPolicy.unauditedMainnet { warnings.append(SendWarning(id: "unaudited-mainnet", message: WalletError.unauditedText, isCritical: true)) }517        if referenceConfirmations == 0 {518            notes.append("Only one TRON node vouched for the reference block of this transaction. A TRON transaction does not name its network: if that node lied, the signature could also be valid on another TRON network for the same account.")519        } else {520            notes.append("The reference block of this transaction is the same on \(referenceConfirmations + 1) TRON nodes.")521        }522        // said on every TRON review, as asked: the wallet's TRON encoding has not been broadcast to a real node yet523        warnings.append(SendWarning(id: "tron.node-checked", message: "TRON support is new: QYVORA builds and signs this transaction itself, and the network checks it when it is broadcast. If a node refuses it, nothing is sent and nothing is lost; the reason is shown.", isCritical: false))524        notes.append("Valid until \(Date(timeIntervalSince1970: TimeInterval(plan.transaction.expiration / 1000)).formatted(date: .omitted, time: .standard)). After that it must be prepared again.")525526        var lines = [SendFeeLine]()527        if plan.bandwidthFeeSun > 0 { lines.append(SendFeeLine(label: "Bandwidth (\(plan.bandwidthBytes) bytes)", amount: UInt256(plan.bandwidthFeeSun))) }528        if plan.energyFeeSun > 0 { lines.append(SendFeeLine(label: "Energy (\(plan.energyEstimate) units estimated)", amount: UInt256(plan.energyFeeSun))) }529        if plan.activationFeeSun > 0 { lines.append(SendFeeLine(label: "Activation of the recipient's address", amount: UInt256(plan.activationFeeSun))) }530        if plan.memoFeeSun > 0 { lines.append(SendFeeLine(label: "Note", amount: UInt256(plan.memoFeeSun))) }531        return makeReview(kind: kind, from: sender.base58, recipient: recipient.base58, asset: asset, amount: plan.amount, decimals: decimals, symbol: symbol,532                          expectedFee: UInt256(plan.estimatedFeeSun), maximumFee: UInt256(plan.maximumFeeSun), feeLines: lines,533                          totalNative: UInt256(plan.maximumDebitSun), isSendMax: options.sendMax, warnings: warnings, notes: notes,534                          expiresAt: Date(timeIntervalSince1970: TimeInterval(plan.transaction.expiration / 1000)),535                          body: .tron(TronSendDetails(network: network, plan: plan)))536    }537538    func hasPaidTron(_ recipient: TronAddress, network: TronNetwork) -> Bool {539        guard let history = tronRecords[network]?.history else { return false }540        return history.contains { $0.direction == .sent && $0.status != .failed && $0.counterparty == recipient.base58 }541    }542543    /// Ceilings applied to a TRON transaction when it is prepared and again before it is signed, on the online device544    /// and on a cold one.545    ///546    /// On every network: `fee_limit` at most 100 TRX, and (when known) a worst-case fee of at most 100 TRX — chain547    /// parameters come from a node, and a hostile one must not be able to make a transfer burn more.548    /// On an unaudited mainnet in addition: TRX sent ≤ 150 USD at a fresh price; a TRC-20 transfer ≤ 150 USD at a fresh549    /// price (a token without known price cannot be sent); approvals, other contract calls and contracts the wallet550    /// cannot decode are refused.551    func enforceTronLimits(_ transaction: TronTransaction, network: TronNetwork, maximumFeeSun: UInt64?) async throws {552        let feeCeiling = MainnetPolicy.tronLimits.feePerTransaction553        guard transaction.feeLimit <= feeCeiling else {554            throw WalletError.tron(.feeLimitTooHigh(requiredSun: transaction.feeLimit, capSun: feeCeiling))555        }556        if let maximumFeeSun, maximumFeeSun > feeCeiling {557            throw WalletError.untrustedResponse("the fee parameters of the chain would make this transfer cost up to \(WalletMessages.trx(maximumFeeSun))")558        }559        guard !network.isTest, MainnetPolicy.unauditedMainnet else { return }560        let limits = MainnetPolicy.tronLimits561        let review = TronTransactionReview(transaction)562        switch review.action {563        case .trxTransfer(_, _, let amountSun):564            let price = try await limitUSDPrice(Self.tronPriceID)565            guard let ceiling = MainnetPolicy.nativeCeiling(usd: limits.nativeUSDPerTransaction, priceUSD: price, decimals: TronUnits.decimals) else {566                throw WalletError.unauditedLimitUnverifiable("The TRX amount cannot be valued, so it cannot be checked against the limit.")567            }568            guard amountSun <= ceiling else {569                throw WalletError.exceedsUnauditedLimit(limit: "\(Int(limits.nativeUSDPerTransaction)) USD of TRX per transaction (\(WalletMessages.trx(ceiling)) at the current price)")570            }571        case .trc20Transfer(_, let contract, _, let amount):572            let tokenLimit = MainnetPolicy.limits.tokenUSDPerTransaction573            // the built-in list only: a token of the stored profile never brings its own price identifier (QYV-SVC-087)574            guard let token = Self.builtInTronTokens(network).first(where: { $0.address == contract.base58 }), let priceID = token.priceID else {575                throw WalletError.unauditedLimitUnverifiable("This token has no known price, so its value cannot be checked against the limit of \(Int(tokenLimit)) USD.")576            }577            let price = try await limitUSDPrice(priceID, pricing: TronBuiltInTokens.isDollarPegged(contract, on: network) ? .dollarPegged : .twoSources)578            guard let units = Double(BaseUnits.format(amount, decimals: token.decimals)), units.isFinite else {579                throw WalletError.unauditedLimitUnverifiable("The token amount cannot be valued.")580            }581            guard units * price <= tokenLimit else { throw WalletError.exceedsUnauditedLimit(limit: "\(Int(tokenLimit)) USD per token transfer") }582        case .trc20Approve, .contractCall, .unknownContract:583            throw WalletError.unauditedLimitUnverifiable("On mainnet this build only signs TRX and TRC-20 payments on TRON.")584        }585    }586587    /// Signs with the TRON key (m/44'/195'/0'/0/0) read from the vault for the duration of the signature, then checks588    /// the result: signed by the owner of the transaction, content identical, bytes that decode back to themselves.589    func signTron(_ transaction: TronTransaction, network: TronNetwork, allowBlindSigning: Bool = false) async throws -> SignedTronTransaction {590        let owner = try tronAccount(network)591        if let declared = transaction.owner {592            guard declared == owner else { throw WalletError.signingFailed("This wallet's account is not the owner of the transaction.") }593        } else if !allowBlindSigning {594            throw WalletError.signingFailed("The transaction holds a contract QYVORA cannot decode.")595        }596        if let trusted = await trustedPublicData(), trusted.tron != owner.base58 {597            throw WalletError.signingFailed("The account of the profile is not the one the vault holds. Lock and unlock the wallet, then try again.")598        }599        try await enforceTronLimits(transaction, network: network, maximumFeeSun: nil)600        // the wallet's own bound on the validity: on the online device and on a cold one, whatever built the transaction601        let nowMilliseconds = UInt64(max(0, now().timeIntervalSince1970 * 1000))602        guard transaction.expiration > nowMilliseconds else {603            throw WalletError.transactionExpired("its validity ended at \(Date(timeIntervalSince1970: TimeInterval(transaction.expiration / 1000)).formatted(date: .abbreviated, time: .standard)).")604        }605        guard transaction.expiration - nowMilliseconds <= Self.tronMaximumSigningWindowMilliseconds else {606            throw WalletError.signingFailed("This transaction would stay valid for more than an hour. QYVORA does not sign it: check the clock of this device, or prepare the payment again.")607        }608        let signed: SignedTronTransaction = try await withMasterKey { master in609            var key = try master.derive(TronPaths.account())610            defer { key.wipe() }611            guard var secret = key.privateKey else { throw WalletError.signingFailed("no private key") }612            defer { SecureMemory.zero(&secret) }613            guard try TronAddress(publicKey: key.publicKey) == owner else {614                throw WalletError.signingFailed("The recovery phrase in the vault does not match this wallet's account.")615            }616            return try transaction.sign(privateKey: secret, allowBlindSigning: allowBlindSigning)617        }618        guard signed.transaction == transaction, (try? signed.signers()) == [owner], (try? SignedTronTransaction.decode(signed.serialized)) == signed else {619            throw WalletError.signingFailed("The signed transaction does not verify.")620        }621        return signed622    }623624    func broadcastTron(_ signed: SignedTronTransaction, network: TronNetwork, paymentKey: String, client: TronClient) async throws -> SendResult {625        let kind = ChainKind.tron(network)626        let id = signed.txIDHex627        let expiration = signed.transaction.expiration628        guard UInt64(max(0, now().timeIntervalSince1970 * 1000)) < expiration else {629            sentTransactions[id]?.settled = true630            throw WalletError.transactionExpired("its validity ended at \(Date(timeIntervalSince1970: TimeInterval(expiration / 1000)).formatted(date: .omitted, time: .standard)).")631        }632        if sentTransactions[id] == nil {633            sentTransactions[id] = SentTransaction(kind: kind, id: id, paymentKey: paymentKey, signed: signed.serialized, lastValidBlockHeight: nil,634                                                   expirationMilliseconds: expiration)635        }636        switch try await client.broadcast(signed) {637        case .accepted, .alreadyKnown:638            sentTransactions[id]?.outcome = .unknown639        case .rejected(let code, let message):640            sentTransactions[id]?.outcome = .rejected641            throw WalletError.broadcastRejected(message.isEmpty ? code : "\(code): \(message)")642        }643        noteBroadcast(kind, id: id)644        return SendResult(chain: ChainRegistry.id(kind), id: id, raw: signed.hex, explorerURL: ChainRegistry.descriptor(kind).explorerTransactionURL(id),645                          lastValidBlockHeight: nil, expiresAt: Date(timeIntervalSince1970: TimeInterval(expiration / 1000)))646    }647648    func signAndBroadcastTron(_ review: SendReview, details: TronSendDetails) async throws -> SendResult {649        let network = details.network650        let kind = ChainKind.tron(network)651        let owner = try tronAccount(network)652        guard Self.activeKinds(profile).contains(kind), review.from == owner.base58, details.plan.from == owner else {653            throw WalletError.stalePlan("The review was made for another account or network.")654        }655        let client = try await verifiedTron(network)656        let paymentKey = Self.paymentKey(kind, recipient: review.recipient, asset: review.asset, amount: review.amount)657        if let id = signedReviews[review.id], let sent = sentTransactions[id], let again = try? SignedTronTransaction.decode(sent.signed) {658            return try await broadcastTron(again, network: network, paymentKey: paymentKey, client: client)659        }660        guard UInt64(max(0, now().timeIntervalSince1970 * 1000)) < details.plan.transaction.expiration else {661            throw WalletError.transactionExpired("its validity ended at \(details.expiresAt.formatted(date: .omitted, time: .standard)).")662        }663        try Self.requireMatches(review, plan: details.plan)664        try await enforceTronLimits(details.plan.transaction, network: network, maximumFeeSun: details.plan.maximumFeeSun)665        try await requireNotValidOnTronMainnet(details.plan.transaction, network: network)666        let signed = try await signTron(details.plan.transaction, network: network)667        signedReviews[review.id] = signed.txIDHex668        let result = try await broadcastTron(signed, network: network, paymentKey: paymentKey, client: client)669        paidRecipients.insert(Self.paidKey(kind, review.recipient))670        return result671    }672673    /// Status of a TRON transaction, from its receipt: `.failed` when the receipt says so, whatever the contract674    /// returned (the value a token returns is not the outcome). Final only once the irreversible state has it.675    func trackTron(_ id: String, network: TronNetwork) async throws -> TransactionStatus {676        let lower = id.lowercased()677        guard lower.utf8.count == 64, Hex.decode(lower) != nil else { throw WalletError.invalidInput("Not a TRON transaction identifier.") }678        let client = try await verifiedTron(network)679        let status = try await client.transactionStatus(id: lower)680        let fee: UInt256? = status.feeSun > 0 ? UInt256(status.feeSun) : nil681        switch status.state {682        case .notFound, .pending:683            if let sent = sentTransactions[lower], let expiration = sent.expirationMilliseconds, UInt64(max(0, now().timeIntervalSince1970 * 1000)) > expiration + 60_000 {684                // past its expiration (and a minute of margin) without a receipt: it can no longer be included685                sentTransactions[lower]?.settled = true686                return .expired687            }688            return status.state == .pending ? .pending : .notFound689        case .failed:690            sentTransactions[lower]?.settled = true691            return .failed(blockHeight: status.blockNumber, reason: status.message ?? status.receiptResult ?? status.contractResult, fee: fee)692        case .succeeded:693            sentTransactions[lower]?.settled = true694            let solid = try? await client.transactionStatus(id: lower, irreversibleOnly: true)695            if solid?.state == .succeeded { return .finalized(blockHeight: status.blockNumber, fee: fee) }696            return .confirmed(blockHeight: status.blockNumber, confirmations: nil, fee: fee)697        }698    }699}700
Files main
Menu

Theme