Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraEthereum/EVMFees.swift8// Module : Qyvora Ethereum9// 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 QyvoraMath42import QyvoraKeccak43import QyvoraCore4445/// How fast the user wants the transaction mined: scales the priority fee, never the base fee.46public enum EVMFeeSpeed: String, Sendable, CaseIterable {47 case slow, normal, fast48}4950/// The two EIP-1559 prices of a transaction, with the base fee they were computed from.51public struct EVMGasFees: Equatable, Sendable {52 /// Base fee of the latest block, in wei per gas (zero on BNB Smart Chain).53 public let baseFee: UInt25654 public let maxPriorityFeePerGas: UInt25655 public let maxFeePerGas: UInt2565657 public init(baseFee: UInt256, maxPriorityFeePerGas: UInt256, maxFeePerGas: UInt256) {58 self.baseFee = baseFee59 self.maxPriorityFeePerGas = maxPriorityFeePerGas60 self.maxFeePerGas = maxFeePerGas61 }62}6364public enum EVMFeeError: Error, Equatable, Sendable {65 /// A figure supplied by the endpoint (or derived from it) is outside what the wallet accepts.66 case outOfRange67 /// The network has a zero base fee and the endpoint gave no usable `eth_gasPrice`: no floor is known.68 case missingGasPrice69}7071/// Fee rules per EVM network. Pure: every figure an endpoint supplied is an argument, and is bounded here.72///73/// - Ethereum, Base, OP Mainnet, Arbitrum, Avalanche: maxFeePerGas = 2 × base fee + priority fee (covers five full74/// blocks in a row, +12.5 % each); the priority fee is the endpoint's `eth_maxPriorityFeePerGas`, scaled by the speed.75/// Arbitrum ignores the priority fee (its sequencer orders first come, first served); a 1 wei tip costs nothing.76/// - Polygon PoS: the same, with the priority fee never below `EthereumNetwork.minimumPriorityFee` (30 gwei).77/// - BNB Smart Chain: the base fee is zero, so the formula above would give a price below what validators accept.78/// `eth_gasPrice` is the floor of the priority fee, and therefore of maxFeePerGas; "slow" cannot go under it.79public enum EVMFeeRules {80 /// An endpoint figure at or above 10 000 gwei per gas is refused (faulty or hostile endpoint).81 public static let endpointFeePerGasCeiling = UInt256(10_000_000_000_000)82 /// A computed maxFeePerGas at or above 100 000 gwei is refused.83 public static let maxFeePerGasCeiling = UInt256(100_000_000_000_000)84 /// Priority fee used when the endpoint does not implement `eth_maxPriorityFeePerGas`: 0.001 gwei.85 public static let fallbackPriorityFee = UInt256(1_000_000)86 /// Gas of a transfer of the native coin to an account without code, where `nativeTransferGasIsFixed`.87 public static let nativeTransferGas: UInt64 = 21_0008889 public static func gasFees(network: EthereumNetwork, baseFee: UInt256, suggestedPriorityFee: UInt256?, gasPrice: UInt256?,90 speed: EVMFeeSpeed = .normal) throws(EVMFeeError) -> EVMGasFees {91 guard baseFee < endpointFeePerGasCeiling else { throw .outOfRange }92 var tip = suggestedPriorityFee ?? fallbackPriorityFee93 guard tip < endpointFeePerGasCeiling else { throw .outOfRange }94 switch speed {95 case .slow: tip = tip.quotientAndRemainder(dividingBy: 2).096 case .normal: break97 case .fast: tip = tip.multipliedReportingOverflow(by: 2).098 }99 var floor = network.minimumPriorityFee100 if network.hasZeroBaseFee {101 guard let gasPrice, !gasPrice.isZero else { throw .missingGasPrice }102 guard gasPrice < endpointFeePerGasCeiling else { throw .outOfRange }103 if gasPrice > floor { floor = gasPrice }104 }105 if tip < floor { tip = floor }106 if tip.isZero { tip = UInt256(1) }107 let (twiceBase, o1) = baseFee.multipliedReportingOverflow(by: 2)108 let (maxFee, o2) = twiceBase.addingReportingOverflow(tip)109 guard !o1, !o2, !maxFee.isZero, maxFee < maxFeePerGasCeiling, tip <= maxFee else { throw .outOfRange }110 return EVMGasFees(baseFee: baseFee, maxPriorityFeePerGas: tip, maxFeePerGas: maxFee)111 }112113 /// Gas limit of a native transfer to an account without code when it is a constant of the network; nil where it114 /// has to be estimated (Arbitrum: the estimate includes the L1 component and is above 21 000).115 public static func fixedNativeTransferGas(_ network: EthereumNetwork) -> UInt64? {116 network.nativeTransferGasIsFixed ? nativeTransferGas : nil117 }118119 /// The most a transaction can cost: gasLimit × maxFeePerGas + value + the L1 data fee charged on top120 /// (`l1DataFee` is zero except on OP-Stack networks). nil on overflow.121 public static func maximumCost(_ tx: EIP1559Transaction, l1DataFee: UInt256 = .zero) -> UInt256? {122 guard let inner = tx.maximumCost else { return nil }123 let (total, overflow) = inner.addingReportingOverflow(l1DataFee)124 return overflow ? nil : total125 }126127 /// The most the fees of a transaction can cost: gasLimit × maxFeePerGas + L1 data fee. nil on overflow.128 public static func maximumFee(gasLimit: UInt64, maxFeePerGas: UInt256, l1DataFee: UInt256 = .zero) -> UInt256? {129 let (gasFee, o1) = maxFeePerGas.multipliedReportingOverflow(by: gasLimit)130 let (total, o2) = gasFee.addingReportingOverflow(l1DataFee)131 return o1 || o2 ? nil : total132 }133134 /// The value of a "send everything" transfer: balance − gasLimit × maxFeePerGas − L1 data fee (pass the fee with135 /// its margin, see `OPStackGasOracle.withMargin`). nil when the balance does not cover the fees or leaves nothing.136 public static func sendMaxValue(balance: UInt256, gasLimit: UInt64, maxFeePerGas: UInt256, l1DataFee: UInt256 = .zero) -> UInt256? {137 guard let fee = maximumFee(gasLimit: gasLimit, maxFeePerGas: maxFeePerGas, l1DataFee: l1DataFee), balance > fee else { return nil }138 return balance - fee139 }140}141142/// The GasPriceOracle predeploy of OP-Stack networks (Base, OP Mainnet and their test networks).143///144/// On these networks the sequencer charges, on top of gasUsed × gas price, the cost of publishing the transaction on145/// Ethereum. That L1 data fee is taken from the sender's balance and appears nowhere in the transaction: the wallet146/// reads it from the oracle to show it, to cap it and to leave room for it when sending the whole balance.147public enum OPStackGasOracle {148 /// 0x420000000000000000000000000000000000000F on every OP-Stack network.149 public static let address = EthereumAddress(unchecked: [0x42] + Bytes(repeating: 0, count: 18) + [0x0f])150151 /// `getL1Fee(bytes)`: the fee of a serialized transaction. The oracle itself accounts for the signature the152 /// unsigned serialization lacks, so the unsigned payload (0x02 ‖ rlp of nine fields) is what is passed.153 public static let getL1FeeSelector = ERC20.selector("getL1Fee(bytes)")154155 /// An L1 data fee at or above 0.1 ETH is refused as implausible (a transfer is a few hundred bytes).156 public static let feeCeiling = UInt256(100_000_000_000_000_000)157158 /// Call data of `getL1Fee(serialized)`.159 public static func getL1FeeCall(_ serialized: Bytes) -> Bytes {160 let padding = (32 - serialized.count % 32) % 32161 return getL1FeeSelector + UInt256(32).bytes32 + UInt256(UInt64(serialized.count)).bytes32 + serialized + Bytes(repeating: 0, count: padding)162 }163164 /// The fee returned by the oracle: exactly one 32-byte word below `feeCeiling`, otherwise nil.165 public static func decodeFee(_ returned: Bytes) -> UInt256? {166 guard let fee = ERC20.decodeUInt(returned), fee < feeCeiling else { return nil }167 return fee168 }169170 /// The fee with a safety margin of one quarter. The L1 fee follows Ethereum's base fee and blob fee, which move171 /// between the quote and the inclusion of the transaction; the margin is what the wallet reserves and caps, the172 /// network charges the real figure.173 public static func withMargin(_ fee: UInt256) -> UInt256 {174 let (sum, overflow) = fee.addingReportingOverflow(fee.quotientAndRemainder(dividingBy: 4).0)175 return overflow ? .max : sum176 }177}178