Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraWallet/WalletService+FeeQuote.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 QyvoraSolana47import QyvoraTron4849// What a payment is likely to cost, before a recipient and an amount exist: the fee of a plain transfer at each tier50// (EVM, Solana), or what a transfer consumes of the account's resources (TRON). These are estimates for the form;51// `prepareSend` stays the source of truth and its review states the fee of the payment actually built.5253/// An estimate of the fee of a plain transfer on a chain. Never a commitment: the review of `prepareSend` is.54public struct SendFeeQuote: Equatable, Sendable {55 public struct Tier: Equatable, Sendable, Identifiable {56 public let tier: SendFeeTier57 /// What a plain transfer is expected to cost at this tier, in base units of the native coin.58 public let expected: UInt25659 /// The most it could cost at this tier.60 public let maximum: UInt25661 public var id: String { tier.rawValue }62 }6364 public let chain: ChainID65 /// The asset the estimate is for (a token transfer costs more than a transfer of the native coin).66 public let asset: ChainAsset67 /// Symbol and decimals of the coin that pays the fee.68 public let symbol: String69 public let decimals: Int70 /// Slow, normal, fast, in that order. Empty on TRON, which has no fee tiers (see `tron`).71 public let tiers: [Tier]72 /// What the figures assume, as a sentence to show with them ("Estimate for a plain transfer of ETH (21,000 gas)…").73 public let basis: String74 /// TRON only: what a transfer consumes and what the account has.75 public let tron: TronResourceEstimate?76 public let readAt: Date77 /// Always true: a quote is an estimate, to be labelled as such wherever it is shown.78 public var isEstimate: Bool { true }7980 public func tier(_ tier: SendFeeTier) -> Tier? { tiers.first { $0.tier == tier } }81}8283/// What a TRON transfer consumes, against what the account has now. Read on chain; an estimate of a payment that84/// does not exist yet.85public struct TronResourceEstimate: Equatable, Sendable {86 /// Bandwidth (bytes) of a plain TRX transfer as this wallet builds it, without a note.87 public let transferBandwidthBytes: UInt6488 /// Free daily bandwidth and staked bandwidth left on the account, in bytes.89 public let freeBandwidth: UInt6490 public let stakedBandwidth: UInt6491 /// Sun burned for the bandwidth of that transfer with the resources above; zero when they cover it.92 public let transferBandwidthFeeSun: UInt6493 /// Energy left on the account (staked or delegated). A TRC-20 transfer consumes energy; without it TRX is burned.94 public let energy: UInt6495 /// Sun burned per unit of energy the account does not have.96 public let energyPriceSun: UInt6497 /// Sun burned on top when the recipient's address has never been used (at most: the two activation fees).98 public let maximumActivationFeeSun: UInt6499 /// The same facts as sentences, ready to display.100 public let lines: [String]101}102103extension WalletService {104 /// An estimate of the fee of a plain transfer of `asset` on an active chain, before a recipient or an amount is105 /// known. **Network.** No secret.106 ///107 /// - EVM: the fee of each tier from the fees read now (`EVMFeeRules`, as `prepareSend`), for the gas of a plain108 /// transfer: 21 000 where that is a constant of the network, otherwise the node's estimate of a transfer of the109 /// account to itself, with the margin `prepareSend` applies; for a token, the estimate of a zero transfer to110 /// itself. The L1 data fee is included on OP-Stack networks.111 /// - Solana: the signature fee plus the priority fee of each tier (same rule as `prepareSend`) for the compute112 /// budget of a plain transfer of the asset. A new token account for the recipient is not a fee and is not included.113 /// - TRON: no tiers; `tron` says what a TRX transfer consumes and what the account has. The energy of a token114 /// transfer is known only by simulating it with its recipient and amount, which `prepareSend` does.115 /// - UTXO chains: refused; their fee depends on the coins spent (`bitcoinFeeOptions`, then `prepareSend`).116 ///117 /// Errors: `unknownChain`, `chainNotActive`, `mainnetDisabled`, `offline`, `simulationFailed` when the node118 /// cannot estimate the transfer, and the network errors of the endpoints.119 public func feeQuote(chain id: ChainID, asset: ChainAsset = .native) async throws(WalletError) -> SendFeeQuote {120 try await run {121 let kind = try activeKind(id)122 let descriptor = ChainRegistry.descriptor(kind)123 switch kind {124 case .utxo(let network):125 throw WalletError.invalidInput("The fee of a \(network.mainCounterpart.displayName) payment depends on the coins it spends: it is known when the payment is prepared.")126 case .evm(let network):127 return try await evmFeeQuote(network, asset: asset, descriptor: descriptor)128 case .solana(let network):129 return try await solanaFeeQuote(network, asset: asset, descriptor: descriptor)130 case .tron(let network):131 return try await tronFeeQuote(network, asset: asset, descriptor: descriptor)132 }133 }134 }135136 private func evmFeeQuote(_ network: EthereumNetwork, asset: ChainAsset, descriptor: ChainDescriptor) async throws -> SendFeeQuote {137 let owner = try ethereumAccount(network)138 let rpc = try await verifiedRPC(network)139 let fees = try await rpc.feeData()140141 // the gas of a plain transfer, with the margin a prepared payment gets142 func margin(_ estimate: UInt64) throws -> UInt64 {143 guard estimate >= Self.ethereumTransferGas, estimate <= 30_000_000 else { throw EthereumRefusal.simulationFailed("gas estimate out of range") }144 let gas = estimate * 13 / 10 + 5_000145 guard gas <= Self.ethereumGasLimitCeiling else { throw EthereumRefusal.gasLimitTooHigh(estimated: gas, limit: Self.ethereumGasLimitCeiling) }146 return gas147 }148 var gas = Self.ethereumTransferGas149 var destination = owner150 var data = Bytes()151 var what = "a plain transfer of \(network.nativeSymbol)"152 do {153 switch asset {154 case .native:155 if !network.nativeTransferGasIsFixed {156 gas = try margin(try await rpc.estimateGas(from: owner.checksummed, to: owner.checksummed, value: .zero, data: []))157 }158 case .token(let token):159 let info = try evmToken(token, network: network)160 data = ERC20.transfer(to: owner, amount: .zero)161 destination = info.address162 gas = try margin(try await rpc.estimateGas(from: owner.checksummed, to: info.address.checksummed, value: .zero, data: data))163 what = "a plain transfer of \(info.symbol)"164 }165 } catch NetworkError.rpc(_, let message) {166 throw WalletError.simulationFailed(message)167 }168169 var l1 = UInt256.zero170 var tiers = [SendFeeQuote.Tier]()171 for (tier, speed) in [(SendFeeTier.slow, EVMFeeSpeed.slow), (.normal, .normal), (.fast, .fast)] {172 let gasFees: EVMGasFees173 do {174 gasFees = try EVMFeeRules.gasFees(network: network, baseFee: fees.baseFee, suggestedPriorityFee: fees.priorityFee, gasPrice: fees.gasPrice, speed: speed)175 } catch {176 throw EthereumRefusal.feeOutOfRange177 }178 if network.isOPStack, tier == .slow {179 // quoted once by the GasPriceOracle for a draft of the transfer: it depends on the size of the180 // transaction, not on the tier181 let draft = EIP1559Transaction(chainID: network.chainID, nonce: 0, maxPriorityFeePerGas: gasFees.maxPriorityFeePerGas, maxFeePerGas: gasFees.maxFeePerGas,182 gasLimit: gas, to: destination, value: .zero, data: data)183 do {184 l1 = OPStackGasOracle.withMargin(try await rpc.l1DataFee(unsignedPayload: draft.unsignedPayload))185 } catch NetworkError.rpc(_, let message) {186 throw WalletError.simulationFailed(message)187 }188 }189 let perGas = min(gasFees.maxFeePerGas, fees.baseFee.addingReportingOverflow(gasFees.maxPriorityFeePerGas).0)190 let (expected, o1) = perGas.multipliedReportingOverflow(by: gas)191 let (maximum, o2) = gasFees.maxFeePerGas.multipliedReportingOverflow(by: gas)192 let (expectedTotal, o3) = expected.addingReportingOverflow(l1)193 let (maximumTotal, o4) = maximum.addingReportingOverflow(l1)194 guard !o1, !o2, !o3, !o4 else { throw EthereumRefusal.feeOutOfRange }195 tiers.append(SendFeeQuote.Tier(tier: tier, expected: expectedTotal, maximum: maximumTotal))196 }197 let basis = "Estimate for \(what) (\(gas.formatted(.number.grouping(.automatic).locale(Locale(identifier: "en_US")))) gas) at the fees read now"198 + (network.isOPStack ? ", L1 data fee included" : "") + ". The fee of your payment is stated when it is prepared."199 return SendFeeQuote(chain: descriptor.id, asset: asset, symbol: descriptor.nativeSymbol, decimals: descriptor.nativeDecimals, tiers: tiers, basis: basis,200 tron: nil, readAt: now())201 }202203 private func solanaFeeQuote(_ network: SolanaNetwork, asset: ChainAsset, descriptor: ChainDescriptor) async throws -> SendFeeQuote {204 let sender = try solanaAccount(network)205 var requestAsset = SolanaSendRequest.Asset.sol206 var program: SolanaTokenProgram.Kind?207 var what = "a plain transfer of SOL"208 if case .token(let token) = asset {209 guard token.chain == descriptor.id, let mint = SolanaPublicKey(base58: token.address) else { throw WalletError.invalidInput("This token belongs to another network.") }210 requestAsset = .token(mint: mint)211 program = token.standard == .splToken2022 ? .token2022 : .token212 what = "a plain transfer of \(token.symbol)"213 }214 let rpc = try await verifiedSolana(network)215 // the same rule as a prepared payment: the 75th percentile of what recent transactions paid, halved or doubled216 let suggested = SolanaFees.suggestedUnitPrice(recentFees: (try? await rpc.recentPrioritizationFees(accounts: [sender])) ?? [])217 let units = SolanaSendPlanner.defaultUnitLimit(asset: requestAsset, program: program, hasMemo: false)218 var tiers = [SendFeeQuote.Tier]()219 for tier in SendFeeTier.allCases {220 let price: UInt64221 switch tier {222 case .slow: price = max(SolanaFees.minimumUnitPrice, suggested / 2)223 case .normal: price = suggested224 case .fast: price = min(SolanaFees.maximumUnitPrice, suggested.multipliedReportingOverflow(by: 2).overflow ? SolanaFees.maximumUnitPrice : suggested * 2)225 }226 guard let priority = SolanaComputeBudget.priorityFee(unitLimit: units, microLamportsPerUnit: price) else { throw WalletError.solana(.priorityFeeTooHigh(lamports: nil)) }227 let (fee, overflow) = SolanaComputeBudget.lamportsPerSignature.addingReportingOverflow(priority)228 guard !overflow else { throw WalletError.solana(.priorityFeeTooHigh(lamports: nil)) }229 // the priority fee is charged on the compute budget asked for, used or not: expected and maximum are the same230 tiers.append(SendFeeQuote.Tier(tier: tier, expected: UInt256(fee), maximum: UInt256(fee)))231 }232 let basis = "Estimate for \(what): the signature fee and the priority fee at the prices paid recently."233 + (program == nil ? "" : " A new token account for the recipient, when one is needed, is not a fee and is not included.")234 + " The fee of your payment is stated when it is prepared."235 return SendFeeQuote(chain: descriptor.id, asset: asset, symbol: descriptor.nativeSymbol, decimals: descriptor.nativeDecimals, tiers: tiers, basis: basis,236 tron: nil, readAt: now())237 }238239 private func tronFeeQuote(_ network: TronNetwork, asset: ChainAsset, descriptor: ChainDescriptor) async throws -> SendFeeQuote {240 let sender = try tronAccount(network)241 if case .token(let token) = asset {242 guard token.chain == descriptor.id, TronAddress(token.address) != nil else { throw WalletError.invalidInput("This token belongs to another network.") }243 }244 let client = try await verifiedTron(network)245 let parameters = try await client.chainParameters()246 let reference = try await client.latestSolidBlock()247 let resources = try await client.resources(sender)248 // the size of a TRX transfer as the wallet builds it (the amount changes it by a few bytes at most)249 let stamp = UInt64(max(0, now().timeIntervalSince1970 * 1000))250 guard let placeholder = TronAddress(hash: Bytes(repeating: 0x01, count: 20)) else { throw WalletError.invalidInput("TRON address") }251 let draft: TronTransaction252 do {253 draft = try TronTransaction.transfer(from: sender, to: placeholder, amountSun: 1_000_000, reference: reference, timestamp: stamp,254 expiration: stamp + 120_000, memo: [])255 } catch {256 throw WalletError.tron(.invalidTransaction(error))257 }258 let bytes = UInt64(draft.bandwidthSize())259 let covered = resources.stakedBandwidth >= bytes || resources.freeBandwidth >= bytes260 let (burn, overflow) = bytes.multipliedReportingOverflow(by: parameters.bandwidthPriceSun)261 guard !overflow else { throw WalletError.untrustedResponse("bandwidth price out of range") }262 let (activation, activationOverflow) = parameters.accountActivationFeeSun.addingReportingOverflow(parameters.createAccountFeeSun)263 guard !activationOverflow else { throw WalletError.untrustedResponse("activation fee out of range") }264 let bandwidthFee = covered ? 0 : burn265266 var lines = [String]()267 if resources.stakedBandwidth >= bytes {268 lines.append("A TRX transfer uses about \(bytes) bytes of bandwidth: covered by this account's staked bandwidth (\(resources.stakedBandwidth) bytes left).")269 } else if resources.freeBandwidth >= bytes {270 lines.append("A TRX transfer uses about \(bytes) bytes of bandwidth: covered by today's free allowance (\(resources.freeBandwidth) bytes left).")271 } else {272 lines.append("A TRX transfer uses about \(bytes) bytes of bandwidth. This account has \(resources.freeBandwidth) free bytes left today: about \(WalletMessages.trx(burn)) would be burned instead.")273 }274 lines.append("Paying an address that was never used on TRON burns up to \(WalletMessages.trx(activation)) more, to create it.")275 if case .token = asset {276 lines.append("A token transfer also consumes energy. This account has \(resources.energy) units; each missing unit burns \(WalletMessages.trx(parameters.energyPriceSun)). The amount of energy is known when the payment is prepared: the contract is simulated with its recipient and amount.")277 }278 let estimate = TronResourceEstimate(transferBandwidthBytes: bytes, freeBandwidth: resources.freeBandwidth, stakedBandwidth: resources.stakedBandwidth,279 transferBandwidthFeeSun: bandwidthFee, energy: resources.energy, energyPriceSun: parameters.energyPriceSun,280 maximumActivationFeeSun: activation, lines: lines)281 return SendFeeQuote(chain: descriptor.id, asset: asset, symbol: descriptor.nativeSymbol, decimals: descriptor.nativeDecimals, tiers: [],282 basis: "Estimate from this account's resources and the chain's prices read now. TRON has no fee tiers; the fee of your payment is stated when it is prepared.",283 tron: estimate, readAt: now())284 }285}286