SPB Git

Repository Public

Networks.swift 51.7 KB 1,025 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraCore/Networks.swift8// Module           : Qyvora Core9// 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 Foundation4243/// The UTXO networks QYVORA knows: Bitcoin and the coins that share its transaction format.44///45/// The type keeps its historical name and the raw values of its first three cases (stored profiles and caches46/// decode unchanged). Everything that differs between coins is a property of the network; see `// MARK: - UTXO coins`.47public enum BitcoinNetwork: String, Codable, Sendable, CaseIterable {48    case mainnet, testnet, signet49    case litecoin, litecoinTestnet50    case dogecoin, dogecoinTestnet51    case bitcoinCash, bitcoinCashTestnet5253    /// Bech32 human-readable part; empty on a network without SegWit (see `bech32HRP`).54    public var hrp: String { bech32HRP ?? "" }55    /// SLIP-44 coin type (1 on every test network).56    public var coinType: UInt32 {57        switch self {58        case .mainnet: return 059        case .litecoin: return 260        case .dogecoin: return 361        case .bitcoinCash: return 14562        case .testnet, .signet, .litecoinTestnet, .dogecoinTestnet, .bitcoinCashTestnet: return 163        }64    }65    /// Base58Check version of a P2PKH address. On Bitcoin Cash this is the legacy form, accepted on input only.66    public var p2pkhVersion: UInt8 {67        switch self {68        case .mainnet, .bitcoinCash: return 0x0069        case .testnet, .signet, .litecoinTestnet, .bitcoinCashTestnet: return 0x6f70        case .litecoin: return 0x3071        case .dogecoin: return 0x1e72        case .dogecoinTestnet: return 0x7173        }74    }75    /// Base58Check version of a P2SH address (Litecoin: the current "M…" / "Q…" form).76    public var p2shVersion: UInt8 {77        switch self {78        case .mainnet, .bitcoinCash: return 0x0579        case .testnet, .signet, .dogecoinTestnet, .bitcoinCashTestnet: return 0xc480        case .litecoin: return 0x3281        case .litecoinTestnet: return 0x3a82        case .dogecoin: return 0x1683        }84    }85    public var wifVersion: UInt8 {86        switch self {87        case .mainnet, .bitcoinCash: return 0x8088        case .testnet, .signet, .litecoinTestnet, .bitcoinCashTestnet: return 0xef89        case .litecoin: return 0xb090        case .dogecoin: return 0x9e91        case .dogecoinTestnet: return 0xf192        }93    }94    public var isTest: Bool {95        switch self {96        case .mainnet, .litecoin, .dogecoin, .bitcoinCash: return false97        case .testnet, .signet, .litecoinTestnet, .dogecoinTestnet, .bitcoinCashTestnet: return true98        }99    }100    public var displayName: String {101        switch self {102        case .mainnet: return "Bitcoin"103        case .testnet: return "Bitcoin Testnet"104        case .signet: return "Bitcoin Signet"105        case .litecoin: return "Litecoin"106        case .litecoinTestnet: return "Litecoin Testnet"107        case .dogecoin: return "Dogecoin"108        case .dogecoinTestnet: return "Dogecoin Testnet"109        case .bitcoinCash: return "Bitcoin Cash"110        case .bitcoinCashTestnet: return "Bitcoin Cash Testnet4"111        }112    }113    /// The coin on a main network ("Litecoin"), the network alone on a test network ("Signet", "Testnet", "Testnet4"):114    /// the display name without the name of the coin. For badges and pickers shown next to the coin.115    public var shortName: String {116        guard isTest else { return displayName }117        let coin = mainCounterpart.displayName118        return displayName.hasPrefix(coin + " ") ? String(displayName.dropFirst(coin.count + 1)) : displayName119    }120    /// Hash of block 0 (display byte order). Bitcoin Cash shares Bitcoin's genesis block, and its testnet4 shares its121    /// genesis with chipnet: an indexer is identified with `identityBlock`, not with this value alone.122    public var genesisHash: String {123        switch self {124        case .mainnet, .bitcoinCash: return "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"125        case .testnet: return "000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"126        case .signet: return "00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6"127        case .litecoin: return "12a765e31ffd4059bada1e25190f6e98c99d9714d334efa41a195a7e7e04bfe2"128        case .litecoinTestnet: return "4966625a4b2851d9fdee139e56211a0d88575f59ed816ff5e6a63deb4e3e29a0"129        case .dogecoin: return "1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691"130        case .dogecoinTestnet: return "bb0a78264637406b6360aad926284d544d7049f45189db5664f3c4d07350559e"131        case .bitcoinCashTestnet: return "000000001dd410c49a788668ce26751718cc797474d3152a5fc073dd44fd9f7b"132        }133    }134}135136// MARK: - UTXO coins137138/// The coins behind `BitcoinNetwork`.139public enum UTXOCoin: String, Codable, Sendable, CaseIterable {140    case bitcoin, litecoin, dogecoin, bitcoinCash141}142143/// Derivation purpose of a single-key account and the script it pays to.144public enum UTXOAccountPurpose: UInt32, Codable, Sendable, CaseIterable {145    /// BIP-44: m/44'/coin'/account', legacy P2PKH addresses.146    case bip44 = 44147    /// BIP-84: m/84'/coin'/account', native SegWit P2WPKH addresses.148    case bip84 = 84149}150151/// How the digest signed by an input is computed on a network.152public enum UTXOSighashScheme: String, Codable, Sendable, CaseIterable {153    /// Bitcoin and Litecoin: BIP-143 for witness version 0 inputs, the original algorithm for legacy inputs.154    case bip143155    /// Dogecoin: the original algorithm only (no SegWit). The digest does not commit to the spent amounts.156    case legacy157    /// Bitcoin Cash: the BIP-143 algorithm for every input, with SIGHASH_FORKID (0x40) set in the hash type and158    /// fork id 0 ("replay protected sighash", UAHF 2017). The signature byte of SIGHASH_ALL is 0x41.159    case bip143ForkID160}161162/// How a network decides that an output is too small to be relayed.163public enum UTXODustRule: Sendable, Equatable {164    /// Bitcoin Core's rule: the output size plus the size of the input spending it, priced at this rate165    /// (base units per 1000 virtual bytes).166    case relayFee(perKiloVByte: UInt64)167    /// One threshold for every script type, in base units.168    case fixed(UInt64)169}170171/// Fee and dust rules of a network, as exact integers. Rates are base units per 1000 (virtual) bytes, the unit of172/// the node software (`sat/kvB`, `koinu/kB`).173public struct UTXOFeePolicy: Sendable, Equatable {174    /// The lowest rate the wallet builds a transaction with.175    public let minimumFeeRatePerKiloVByte: UInt64176    /// A rate above this is refused as an error of the estimator or of the caller, on any network.177    public let maximumFeeRatePerKiloVByte: UInt64178    public let dust: UTXODustRule179}180181/// A block that identifies a chain among those sharing the same genesis block.182public struct UTXOChainIdentity: Sendable, Equatable {183    public let height: Int184    /// Block hash, display byte order.185    public let hash: String186}187188/// Protocols spoken by the public indexers of UTXO coins (clients in QyvoraNetworking).189public enum UTXOIndexerProtocol: String, Codable, Sendable, CaseIterable {190    /// Esplora / mempool.space REST API.191    case esplora192    /// Blockbook REST API v2 (Trezor's indexer and its forks).193    case blockbook194    /// Bitcore REST API (BitPay's indexer). It serves no raw transactions.195    case bitcore196}197198extension BitcoinNetwork {199    public var coin: UTXOCoin {200        switch self {201        case .mainnet, .testnet, .signet: return .bitcoin202        case .litecoin, .litecoinTestnet: return .litecoin203        case .dogecoin, .dogecoinTestnet: return .dogecoin204        case .bitcoinCash, .bitcoinCashTestnet: return .bitcoinCash205        }206    }207208    /// Every network of a coin, production network first.209    public static func networks(of coin: UTXOCoin) -> [BitcoinNetwork] { allCases.filter { $0.coin == coin } }210211    public var ticker: String {212        switch coin {213        case .bitcoin: return "BTC"214        case .litecoin: return "LTC"215        case .dogecoin: return "DOGE"216        case .bitcoinCash: return "BCH"217        }218    }219    /// Ticker as shown for the network: test coins carry a "t" prefix so that they are never mistaken for real ones.220    public var displayTicker: String { isTest ? "t" + ticker : ticker }221    /// Decimal places of the main unit (1 coin = 10^8 base units on every UTXO coin QYVORA supports).222    public var decimals: Int { 8 }223    /// Name of the base unit.224    public var baseUnitName: String {225        switch coin {226        case .bitcoin, .bitcoinCash: return "satoshi"227        case .litecoin: return "litoshi"228        case .dogecoin: return "koinu"229        }230    }231232    /// The production network of the coin (itself when it is one).233    public var mainCounterpart: BitcoinNetwork {234        switch coin {235        case .bitcoin: return .mainnet236        case .litecoin: return .litecoin237        case .dogecoin: return .dogecoin238        case .bitcoinCash: return .bitcoinCash239        }240    }241    /// The default test network of the coin (itself when it is a test network): Signet for Bitcoin, as in QYVORA 1.0.242    public var testCounterpart: BitcoinNetwork {243        if isTest { return self }244        switch coin {245        case .bitcoin: return .signet246        case .litecoin: return .litecoinTestnet247        case .dogecoin: return .dogecoinTestnet248        case .bitcoinCash: return .bitcoinCashTestnet249        }250    }251252    // MARK: Address formats253254    /// Bech32 human-readable part of SegWit addresses, nil on a network without SegWit.255    public var bech32HRP: String? {256        switch self {257        case .mainnet: return "bc"258        case .testnet, .signet: return "tb"259        case .litecoin: return "ltc"260        case .litecoinTestnet: return "tltc"261        case .dogecoin, .dogecoinTestnet, .bitcoinCash, .bitcoinCashTestnet: return nil262        }263    }264    public var supportsSegWit: Bool { bech32HRP != nil }265    /// Taproot (witness version 1) is active on Bitcoin and on Litecoin (MWEB upgrade, 2022).266    public var supportsTaproot: Bool { supportsSegWit }267    /// CashAddr prefix (without the colon) on Bitcoin Cash, nil elsewhere. Addresses are always displayed in this form268    /// there; the legacy Base58 form is accepted on input and reported as such.269    public var cashAddrPrefix: String? {270        switch self {271        case .bitcoinCash: return "bitcoincash"272        case .bitcoinCashTestnet: return "bchtest"273        default: return nil274        }275    }276    /// Litecoin's former P2SH version byte, identical to Bitcoin's ("3…" on mainnet, "2…" on testnet). Litecoin Core277    /// still decodes it, but such an address cannot be told from a Bitcoin one: QYVORA refuses it, as SP Wallet does,278    /// and asks for the current form ("M…" / "Q…"). nil on the other networks.279    public var deprecatedP2SHVersion: UInt8? {280        switch self {281        case .litecoin: return 0x05282        case .litecoinTestnet: return 0xc4283        default: return nil284        }285    }286287    // MARK: Accounts and signatures288289    /// Purpose of the account QYVORA derives by default: BIP-84 (P2WPKH) where SegWit exists, BIP-44 (P2PKH) otherwise.290    public var defaultPurpose: UTXOAccountPurpose { supportsSegWit ? .bip84 : .bip44 }291    /// Whether an account of this purpose can exist on the network.292    public func supports(_ purpose: UTXOAccountPurpose) -> Bool { purpose == .bip44 || supportsSegWit }293294    public var sighashScheme: UTXOSighashScheme {295        switch coin {296        case .bitcoin, .litecoin: return .bip143297        case .dogecoin: return .legacy298        case .bitcoinCash: return .bip143ForkID299        }300    }301    /// BIP-125 opt-in replacement. Bitcoin Cash has no replace-by-fee: QYVORA never signals it there.302    public var supportsRBF: Bool { coin != .bitcoinCash }303    /// BIP-174 is implemented for every network. On Dogecoin and Bitcoin Cash an input can only be signed when the PSBT304    /// carries the whole previous transaction (`non_witness_utxo`): see `psbtRequiresPreviousTransactions`.305    public var supportsPSBT: Bool { true }306    /// True when every input of a PSBT needs its previous transaction: networks whose wallet inputs are not SegWit.307    public var psbtRequiresPreviousTransactions: Bool { !supportsSegWit }308    /// True when the signed digest does not commit to the amounts spent (Dogecoin): the wallet must then check each309    /// coin against its previous transaction before signing, or an indexer could make it overpay the fee.310    public var signatureCommitsToAmounts: Bool { sighashScheme != .legacy }311312    // MARK: Money, fees, dust313314    /// Largest valid amount in base units (consensus `MAX_MONEY`): 21 million coins on Bitcoin and Bitcoin Cash,315    /// 84 million on Litecoin, 10 billion per transaction on Dogecoin (whose supply has no cap).316    public var maximumMoney: UInt64 {317        switch coin {318        case .bitcoin, .bitcoinCash: return 2_100_000_000_000_000319        case .litecoin: return 8_400_000_000_000_000320        case .dogecoin: return 1_000_000_000_000_000_000321        }322    }323324    /// Sources: Bitcoin Core `policy.h` (1 sat/vB relay, 3 sat/vB dust relay); Litecoin Core `policy.h`325    /// (`DUST_RELAY_TX_FEE = 30'000`, read 2026-12-05); Dogecoin Core 1.14.6+ `doc/fee-recommendation.md` and326    /// `policy.h` (recommended fee 0.01 DOGE/kB over the exact size, relay floor 0.001 DOGE/kB, soft dust limit327    /// 0.01 DOGE below which an output costs an extra 0.01 DOGE, hard limit 0.001 DOGE; read 2026-12-05): QYVORA uses328    /// the recommended fee as its floor and the soft limit as its dust threshold; Bitcoin Cash Node (1 sat/byte,329    /// dust 546 sat).330    public var feePolicy: UTXOFeePolicy {331        switch coin {332        case .bitcoin:333            return UTXOFeePolicy(minimumFeeRatePerKiloVByte: 1_000, maximumFeeRatePerKiloVByte: 5_000_000, dust: .relayFee(perKiloVByte: 3_000))334        case .litecoin:335            return UTXOFeePolicy(minimumFeeRatePerKiloVByte: 1_000, maximumFeeRatePerKiloVByte: 5_000_000, dust: .relayFee(perKiloVByte: 30_000))336        case .dogecoin:337            return UTXOFeePolicy(minimumFeeRatePerKiloVByte: 1_000_000, maximumFeeRatePerKiloVByte: 100_000_000, dust: .fixed(1_000_000))338        case .bitcoinCash:339            return UTXOFeePolicy(minimumFeeRatePerKiloVByte: 1_000, maximumFeeRatePerKiloVByte: 1_000_000, dust: .fixed(546))340        }341    }342343    // MARK: Chain facts344345    /// Target time between two blocks, in seconds.346    public var blockTimeSeconds: Int {347        switch coin {348        case .bitcoin, .bitcoinCash: return 600349        case .litecoin: return 150350        case .dogecoin: return 60351        }352    }353    /// Confirmations after which the interface may call a payment settled (a hint, the values SP Wallet uses).354    public var minimumConfirmationsHint: Int { coin == .dogecoin ? 20 : 6 }355356    /// The block an indexer must serve at a given height to be on this chain. The genesis block, except for:357    /// Bitcoin Cash, whose genesis is also Bitcoin's (and Bitcoin SV's and eCash's) — block 661648 is the first after358    /// its last chain split (2020-11-15); and its testnet4, whose genesis is also chipnet's — block 200000 is past the359    /// point where chipnet left (121957), same hash on api.bitcore.io and api.haskoin.com on 2026-12-05.360    public var identityBlock: UTXOChainIdentity {361        switch self {362        case .bitcoinCash:363            return UTXOChainIdentity(height: 661_648, hash: "0000000000000000029e471c41818d24b8b74c911071c4ef0b4a0509f9b5a8ce")364        case .bitcoinCashTestnet:365            return UTXOChainIdentity(height: 200_000, hash: "00000000071ca109d9e44e26c1510922d2913ead12e8d2bd86d7bc7577806d7b")366        default:367            return UTXOChainIdentity(height: 0, hash: genesisHash)368        }369    }370371    /// False when no keyless public indexer could be verified for the network: it stays defined (addresses, signing)372    /// but cannot be synchronised with the built-in endpoints, and the interface presents it as unavailable.373    /// Dogecoin Testnet, checked on 2026-12-05: the only keyless instance found (api.bitcore.io, DOGE/testnet) had374    /// stopped at a block of 2026-11-15 and numbers its blocks one below their height; no public Blockbook or Esplora.375    public var indexerAvailable: Bool { self != .dogecoinTestnet }376377    /// CoinGecko identifier of the coin; nil on test networks, whose coins have no price.378    public var priceID: String? {379        guard !isTest else { return nil }380        switch coin {381        case .bitcoin: return "bitcoin"382        case .litecoin: return "litecoin"383        case .dogecoin: return "dogecoin"384        case .bitcoinCash: return "bitcoin-cash"385        }386    }387388    /// Base of a public block explorer (pages built by `explorerTransactionURL`); nil when none is known (Dogecoin389    /// Testnet). Checked on 2026-12-05: the mempool.space, litecoinspace.org and loping.net pages answer a plain390    /// request; blockchair.com refuses automated clients (HTTP 401) but its API serves the same transaction, so the391    /// Dogecoin page pattern is the one of the site's own links.392    public var explorerBaseURL: String? {393        switch self {394        case .mainnet: return "https://mempool.space"395        case .testnet: return "https://mempool.space/testnet"396        case .signet: return "https://mempool.space/signet"397        case .litecoin: return "https://litecoinspace.org"398        case .litecoinTestnet: return "https://litecoinspace.org/testnet"399        case .dogecoin: return "https://blockchair.com/dogecoin"400        case .dogecoinTestnet: return nil401        case .bitcoinCash: return "https://bch.loping.net"402        case .bitcoinCashTestnet: return "https://tbch4.loping.net"403        }404    }405    /// Explorer page of a transaction; nil without an explorer or when `txid` is not 64 hexadecimal characters.406    public func explorerTransactionURL(txid: String) -> String? {407        guard let base = explorerBaseURL, txid.utf8.count == 64,408              txid.utf8.allSatisfy({ ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x61 && $0 <= 0x66) }) else { return nil }409        // blockchair.com names the page "transaction"; the other explorers use "tx"410        return base + (self == .dogecoin ? "/transaction/" : "/tx/") + txid411    }412}413414extension StandardPaths {415    /// Account path of a purpose: m/purpose'/coin'/account'.416    public static func account(_ purpose: UTXOAccountPurpose, _ network: BitcoinNetwork, account: UInt32 = 0) -> DerivationPath {417        DerivationPath([.hardened(purpose.rawValue), .hardened(network.coinType), .hardened(account)])418    }419420    /// BIP-44 account: m/44'/coin'/account'421    public static func bip44Account(_ network: BitcoinNetwork, account: UInt32 = 0) -> DerivationPath {422        self.account(.bip44, network, account: account)423    }424}425426extension MainnetPolicy {427    /// Ceilings of one transaction of a UTXO coin on its production network while the engine is unaudited.428    public struct UTXOLimits: Sendable, Equatable {429        public enum ValueCeiling: Sendable, Equatable {430            /// Largest total of recipient outputs, in base units.431            case baseUnits(UInt64)432            /// Largest total of recipient outputs as a fiat value (USD): the service converts it with a fresh price433            /// (`nativeCeiling`), and a coin without a known price cannot be sent.434            case usd(Double)435        }436        public let value: ValueCeiling437        /// Largest absolute fee, in base units.438        public let feePerTransaction: UInt64439        /// Largest fee rate, in base units per virtual byte.440        public let feeRatePerVByte: UInt64441    }442443    /// The ceilings of a network; nil on a test network. Bitcoin keeps the values of `limits`. The others are bounded444    /// by `limits.nativeUSDPerTransaction` and by: Litecoin 0.001 LTC of fee and 200 litoshi/vB; Dogecoin 5 DOGE of445    /// fee and 1 DOGE/kB (100 times the recommended rate); Bitcoin Cash 0.0005 BCH of fee and 20 sat/byte.446    public static func utxoLimits(_ network: BitcoinNetwork) -> UTXOLimits? {447        guard !network.isTest else { return nil }448        switch network.coin {449        case .bitcoin:450            return UTXOLimits(value: .baseUnits(limits.bitcoinSatoshisPerTransaction), feePerTransaction: limits.bitcoinFeeSatoshisPerTransaction,451                              feeRatePerVByte: limits.bitcoinFeeRateSatPerVByte)452        case .litecoin:453            return UTXOLimits(value: .usd(limits.nativeUSDPerTransaction), feePerTransaction: 100_000, feeRatePerVByte: 200)454        case .dogecoin:455            return UTXOLimits(value: .usd(limits.nativeUSDPerTransaction), feePerTransaction: 500_000_000, feeRatePerVByte: 100_000)456        case .bitcoinCash:457            return UTXOLimits(value: .usd(limits.nativeUSDPerTransaction), feePerTransaction: 50_000, feeRatePerVByte: 20)458        }459    }460461    /// Converts a fiat ceiling into base units with the price of one coin, rounding down. nil when the price is not462    /// usable (not finite, zero or negative): the transaction is then refused rather than left unbounded.463    public static func nativeCeiling(usd: Double, priceUSD: Double, decimals: Int) -> UInt64? {464        guard usd.isFinite, usd >= 0, priceUSD.isFinite, priceUSD > 0, (0...18).contains(decimals) else { return nil }465        let units = (usd / priceUSD) * pow(10, Double(decimals))466        guard units.isFinite, units >= 0 else { return nil }467        // above 2^63 the conversion is not exact and no ceiling of this size is meaningful: saturate468        return units >= 9_223_372_036_854_775_808.0 ? UInt64(Int64.max) : UInt64(units.rounded(.down))469    }470}471472/// EVM networks supported by QYVORA. The type keeps its historical name and the raw values `mainnet` and `sepolia`473/// (Ethereum), so that profiles stored by earlier versions still decode. One account address (m/44'/60'/0'/0/0) is474/// shared by all of them. Everything else about a network is in the "EVM networks" section at the end of this file.475public enum EthereumNetwork: String, Codable, Sendable, CaseIterable {476    case mainnet, sepolia477    case base, baseSepolia478    case arbitrum, arbitrumSepolia479    case optimism, optimismSepolia480    case polygon, polygonAmoy481    case bsc, bscTestnet482    case avalanche, avalancheFuji483484    /// EIP-155 chain identifier: part of every signed transaction, so a signature is valid on that chain only.485    public var chainID: UInt64 {486        switch self {487        case .mainnet: return 1488        case .sepolia: return 11_155_111489        case .base: return 8_453490        case .baseSepolia: return 84_532491        case .arbitrum: return 42_161492        case .arbitrumSepolia: return 421_614493        case .optimism: return 10494        case .optimismSepolia: return 11_155_420495        case .polygon: return 137496        case .polygonAmoy: return 80_002497        case .bsc: return 56498        case .bscTestnet: return 97499        case .avalanche: return 43_114500        case .avalancheFuji: return 43_113501        }502    }503504    public var isTest: Bool {505        switch self {506        case .mainnet, .base, .arbitrum, .optimism, .polygon, .bsc, .avalanche: return false507        case .sepolia, .baseSepolia, .arbitrumSepolia, .optimismSepolia, .polygonAmoy, .bscTestnet, .avalancheFuji: return true508        }509    }510511    public var displayName: String {512        switch self {513        case .mainnet: return "Ethereum"514        case .sepolia: return "Ethereum Sepolia"515        case .base: return "Base"516        case .baseSepolia: return "Base Sepolia"517        case .arbitrum: return "Arbitrum One"518        case .arbitrumSepolia: return "Arbitrum Sepolia"519        case .optimism: return "OP Mainnet"520        case .optimismSepolia: return "OP Sepolia"521        case .polygon: return "Polygon PoS"522        case .polygonAmoy: return "Polygon Amoy"523        case .bsc: return "BNB Smart Chain"524        case .bscTestnet: return "BNB Smart Chain Testnet"525        case .avalanche: return "Avalanche C-Chain"526        case .avalancheFuji: return "Avalanche Fuji"527        }528    }529}530531/// Mainnet gate.532///533/// QYVORA's cryptographic engine is written from scratch and has not been audited. A public release therefore534/// operates on test networks only (`auditCompleted` is false). The owner decided on 2026-12-04 to test with small535/// amounts of real funds on the internal TestFlight build: such a build declares `QYInternalMainnet` in its536/// Info.plist, and the user must still switch mainnet on in the settings after reading the warning. Both conditions537/// are needed, and per-transaction limits apply for as long as the engine is unaudited.538public enum MainnetPolicy {539    /// Set to true only by a release that documents a completed independent audit (see docs/SECURITY.md).540    public static let auditCompleted = false541542    private static let lock = NSLock()543    nonisolated(unsafe) private static var internalBuild = false544    nonisolated(unsafe) private static var userOptIn = false545546    /// Called once at launch by the application with the build's declaration and the stored user choice.547    public static func configure(internalBuildAllowsMainnet: Bool, userOptedIn: Bool) {548        lock.lock()549        defer { lock.unlock() }550        internalBuild = internalBuildAllowsMainnet551        userOptIn = userOptedIn552    }553554    /// True when this build may offer the mainnet switch at all.555    public static var mainnetAvailable: Bool {556        lock.lock()557        defer { lock.unlock() }558        return auditCompleted || internalBuild559    }560561    /// True when mainnet operations are allowed right now.562    public static var mainnetEnabled: Bool {563        lock.lock()564        defer { lock.unlock() }565        return auditCompleted || (internalBuild && userOptIn)566    }567568    /// True when real funds are handled by unaudited code: the application shows a permanent notice and applies `limits`.569    public static var unauditedMainnet: Bool { mainnetEnabled && !auditCompleted }570571    /// Per-transaction ceilings while the engine is unaudited. They bound a mistake, not the wallet balance:572    /// keep only small amounts in an unaudited build.573    public struct Limits: Sendable, Equatable {574        /// Largest total of recipient outputs in one Bitcoin transaction, in satoshis (0.002 BTC).575        public let bitcoinSatoshisPerTransaction: UInt64576        /// Largest ether value in one transaction, in wei (0.05 ETH).577        public let etherWeiPerTransaction: UInt256578        /// Largest fiat value (USD) of one ERC-20 transfer; a token without a known price cannot be sent on mainnet.579        public let tokenUSDPerTransaction: Double580        /// Largest absolute fee of one Bitcoin transaction, in satoshis (QYV-SVC-009).581        public let bitcoinFeeSatoshisPerTransaction: UInt64582        /// Largest fee rate of one Bitcoin transaction, in satoshis per virtual byte.583        public let bitcoinFeeRateSatPerVByte: UInt64584        /// Largest maximum fee (gas limit × maxFeePerGas) of one Ethereum transaction, in wei (0.01 ETH).585        public let etherFeeWeiPerTransaction: UInt256586        /// Largest fiat value (USD) of the native coin sent by one transaction on a network without its own ceiling587        /// (Litecoin, Dogecoin, Bitcoin Cash); converted with a fresh price, and no price means no transaction.588        public let nativeUSDPerTransaction: Double589    }590591    public static let limits = Limits(bitcoinSatoshisPerTransaction: 200_000,592                                      etherWeiPerTransaction: UInt256(50_000_000_000_000_000),593                                      tokenUSDPerTransaction: 150,594                                      bitcoinFeeSatoshisPerTransaction: 20_000,595                                      bitcoinFeeRateSatPerVByte: 200,596                                      etherFeeWeiPerTransaction: UInt256(10_000_000_000_000_000),597                                      nativeUSDPerTransaction: 150)598}599600/// Standard derivation paths (documented in docs/RECOVERY.md).601public enum StandardPaths {602    /// BIP-84 account: m/84'/coin'/account'603    public static func bip84Account(_ network: BitcoinNetwork, account: UInt32 = 0) -> DerivationPath {604        DerivationPath([.hardened(84), .hardened(network.coinType), .hardened(account)])605    }606607    /// BIP-44 Ethereum address: m/44'/60'/0'/0/index (the same path on test networks, as other wallets do).608    public static func ethereum(index: UInt32 = 0) -> DerivationPath {609        DerivationPath([.hardened(44), .hardened(60), .hardened(0), .normal(0), .normal(index)])610    }611}612613// MARK: - EVM networks614615/// The seven EVM chains, each with one main network and one test network.616public enum EVMFamily: String, Codable, Sendable, CaseIterable {617    case ethereum, base, arbitrum, optimism, polygon, bsc, avalanche618}619620extension EthereumNetwork {621    /// The chain this network belongs to (a main network and its test network share a family).622    public var family: EVMFamily {623        switch self {624        case .mainnet, .sepolia: return .ethereum625        case .base, .baseSepolia: return .base626        case .arbitrum, .arbitrumSepolia: return .arbitrum627        case .optimism, .optimismSepolia: return .optimism628        case .polygon, .polygonAmoy: return .polygon629        case .bsc, .bscTestnet: return .bsc630        case .avalanche, .avalancheFuji: return .avalanche631        }632    }633634    /// Main networks, in display order.635    public static let mainNetworks: [EthereumNetwork] = [.mainnet, .base, .arbitrum, .optimism, .polygon, .bsc, .avalanche]636    /// Test networks, in the same order as `mainNetworks`.637    public static let testNetworks: [EthereumNetwork] = [.sepolia, .baseSepolia, .arbitrumSepolia, .optimismSepolia, .polygonAmoy, .bscTestnet, .avalancheFuji]638639    /// The network of a chain identifier, nil when QYVORA does not support that chain.640    public init?(chainID: UInt64) {641        guard let n = Self.allCases.first(where: { $0.chainID == chainID }) else { return nil }642        self = n643    }644645    /// The main and test network of a family.646    public static func networks(of family: EVMFamily) -> (main: EthereumNetwork, test: EthereumNetwork) {647        switch family {648        case .ethereum: return (.mainnet, .sepolia)649        case .base: return (.base, .baseSepolia)650        case .arbitrum: return (.arbitrum, .arbitrumSepolia)651        case .optimism: return (.optimism, .optimismSepolia)652        case .polygon: return (.polygon, .polygonAmoy)653        case .bsc: return (.bsc, .bscTestnet)654        case .avalanche: return (.avalanche, .avalancheFuji)655        }656    }657658    /// The test network of the same chain (itself for a test network).659    public var testCounterpart: EthereumNetwork { Self.networks(of: family).test }660    /// The main network of the same chain (itself for a main network).661    public var mainCounterpart: EthereumNetwork { Self.networks(of: family).main }662663    /// Short label for lists and badges.664    public var shortName: String {665        switch self {666        case .mainnet: return "Ethereum"667        case .sepolia: return "Sepolia"668        case .base: return "Base"669        case .baseSepolia: return "Base Sepolia"670        case .arbitrum: return "Arbitrum"671        case .arbitrumSepolia: return "Arb Sepolia"672        case .optimism: return "Optimism"673        case .optimismSepolia: return "OP Sepolia"674        case .polygon: return "Polygon"675        case .polygonAmoy: return "Amoy"676        case .bsc: return "BNB Chain"677        case .bscTestnet: return "BNB Testnet"678        case .avalanche: return "Avalanche"679        case .avalancheFuji: return "Fuji"680        }681    }682683    /// Ticker of the coin that pays the fees. Ether on Ethereum, Base, Arbitrum and OP Mainnet.684    public var nativeSymbol: String {685        switch family {686        case .ethereum, .base, .arbitrum, .optimism: return "ETH"687        case .polygon: return "POL"688        case .bsc: return "BNB"689        case .avalanche: return "AVAX"690        }691    }692693    public var nativeName: String {694        switch family {695        case .ethereum, .base, .arbitrum, .optimism: return "Ether"696        case .polygon: return "POL"697        case .bsc: return "BNB"698        case .avalanche: return "Avalanche"699        }700    }701702    /// Every supported EVM network counts its native coin in 10^-18 units.703    public var nativeDecimals: Int { 18 }704705    /// True when the native coin is ether (the 0.05 ETH and 0.01 ETH ceilings of `MainnetPolicy.limits` then apply as they are).706    public var nativeIsEther: Bool {707        switch family {708        case .ethereum, .base, .arbitrum, .optimism: return true709        case .polygon, .bsc, .avalanche: return false710        }711    }712713    /// CoinGecko identifier of the native coin. A test network names the coin of its main network; test coins have714    /// no value and the application must not value a test balance.715    public var priceID: String {716        switch family {717        case .ethereum, .base, .arbitrum, .optimism: return "ethereum"718        case .polygon: return "polygon-ecosystem-token"719        case .bsc: return "binancecoin"720        case .avalanche: return "avalanche-2"721        }722    }723724    /// Approximate time between two blocks, in seconds: a display hint (expected waiting time), never a protocol rule.725    /// Measured over 2 000 blocks on 2026-12-05: Ethereum 12.0, Sepolia 13.4, Base 0.2, Arbitrum 0.25, OP 2.0,726    /// Polygon 1.5 (Amoy 1.0), BNB Smart Chain 0.45, Avalanche 0.9 (Fuji 1.6).727    public var blockTimeSeconds: Double {728        switch self {729        case .mainnet, .sepolia: return 12730        case .base, .baseSepolia: return 0.2731        case .arbitrum, .arbitrumSepolia: return 0.25732        case .optimism, .optimismSepolia: return 2733        case .polygon: return 1.5734        case .polygonAmoy: return 1735        case .bsc, .bscTestnet: return 0.45736        case .avalanche: return 1737        case .avalancheFuji: return 1.6738        }739    }740741    /// Number of blocks after which a transaction is treated as final when the endpoint cannot name its finalized742    /// block. A hint on the cautious side, not a guarantee:743    /// Ethereum two epochs (64 blocks); the rollups about fifteen minutes of their own blocks, the time their batches744    /// need to be final on Ethereum (Base 4 500, Arbitrum 3 600, OP 450); Polygon 64 and BNB Smart Chain 15 (the values745    /// SP Wallet uses; both chains now finalize in a few blocks); Avalanche 2 (accepted blocks are final).746    public var finalityConfirmations: UInt64 {747        switch family {748        case .ethereum: return 64749        case .base: return 4_500750        case .arbitrum: return 3_600751        case .optimism: return 450752        case .polygon: return 64753        case .bsc: return 15754        case .avalanche: return 2755        }756    }757758    /// OP-Stack rollups (Base, OP Mainnet): a transaction also pays an L1 data fee that is not part of759    /// gasLimit × maxFeePerGas. It is read from the GasPriceOracle predeploy (`EVMPredeploys.opStackGasPriceOracle`).760    public var isOPStack: Bool { family == .base || family == .optimism }761762    /// Arbitrum (Nitro): the L1 data cost is folded into the gas estimate, so a plain transfer costs more than763    /// 21 000 gas and the gas limit always comes from `eth_estimateGas`.764    public var isArbitrum: Bool { family == .arbitrum }765766    /// Every supported network accepts type-2 (EIP-1559) transactions, the only type QYVORA signs.767    public var supportsEIP1559: Bool { true }768769    /// BNB Smart Chain accepts type-2 transactions but its base fee is zero: the whole price is the priority fee,770    /// and validators refuse a transaction below their minimum gas price. The floor is then `eth_gasPrice`.771    public var hasZeroBaseFee: Bool { family == .bsc }772773    /// True when a transfer of the native coin to an account without code costs exactly 21 000 gas.774    /// False on Arbitrum, where the estimate carries the L1 component.775    public var nativeTransferGasIsFixed: Bool { !isArbitrum }776777    /// Smallest priority fee the network's validators accept, in wei; zero when the network sets none.778    /// Polygon PoS: 30 gwei. Bor refuses a lower tip; the rule was 30 gwei for years (the value SP Wallet enforces)779    /// and public nodes answered 25 gwei to `eth_maxPriorityFeePerGas` on 2026-12-05. The wallet keeps 30 gwei,780    /// which satisfies both; the difference is 0.0001 POL on a transfer.781    public var minimumPriorityFee: UInt256 {782        family == .polygon ? UInt256(30_000_000_000) : .zero783    }784785    /// Public block explorer of the network (for links opened by the user; QYVORA never queries it).786    public var explorerBaseURL: String {787        switch self {788        case .mainnet: return "https://etherscan.io"789        case .sepolia: return "https://sepolia.etherscan.io"790        case .base: return "https://basescan.org"791        case .baseSepolia: return "https://sepolia.basescan.org"792        case .arbitrum: return "https://arbiscan.io"793        case .arbitrumSepolia: return "https://sepolia.arbiscan.io"794        case .optimism: return "https://optimistic.etherscan.io"795        case .optimismSepolia: return "https://sepolia-optimism.etherscan.io"796        case .polygon: return "https://polygonscan.com"797        case .polygonAmoy: return "https://amoy.polygonscan.com"798        case .bsc: return "https://bscscan.com"799        case .bscTestnet: return "https://testnet.bscscan.com"800        case .avalanche: return "https://snowtrace.io"801        case .avalancheFuji: return "https://testnet.snowtrace.io"802        }803    }804805    /// Explorer page of a transaction; nil unless `hash` is "0x" followed by 64 hexadecimal digits.806    public func explorerTransactionURL(hash: String) -> URL? {807        guard hash.hasPrefix("0x"), hash.utf8.count == 66, Self.isHexDigits(hash.dropFirst(2)) else { return nil }808        return URL(string: explorerBaseURL + "/tx/" + hash)809    }810811    /// Explorer page of an account; nil unless `address` is "0x" followed by 40 hexadecimal digits.812    public func explorerAddressURL(address: String) -> URL? {813        guard address.hasPrefix("0x"), address.utf8.count == 42, Self.isHexDigits(address.dropFirst(2)) else { return nil }814        return URL(string: explorerBaseURL + "/address/" + address)815    }816817    private static func isHexDigits(_ s: Substring) -> Bool {818        s.utf8.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x41 && $0 <= 0x46) || ($0 >= 0x61 && $0 <= 0x66) }819    }820}821822/// Contracts that exist at the same address on every network of a kind.823public enum EVMPredeploys {824    /// GasPriceOracle of OP-Stack chains: `getL1Fee(bytes)` returns the L1 data fee of a serialized transaction.825    public static let opStackGasPriceOracle = "0x420000000000000000000000000000000000000F"826}827828extension MainnetPolicy {829    /// Every EVM network that is not a test network handles real funds: the mainnet gate and the limits apply to it.830    public static func isMainnet(_ network: EthereumNetwork) -> Bool { !network.isTest }831832    /// A per-transaction ceiling of an unaudited build, in the unit that can be checked.833    public enum Ceiling: Sendable, Equatable {834        /// An amount of the native coin, in wei.835        case native(UInt256)836        /// A value in US dollars, checked with a fresh price of the coin; without a price the transaction is refused.837        case usd(Double)838839        /// Whether `wei` (18 decimals) respects the ceiling. `usdPrice` is the price of one coin; it is needed for a840        /// dollar ceiling only. nil means "cannot be verified" (no price, or a price that is not a positive finite841        /// number): the caller must refuse, never assume.842        public func allows(wei: UInt256, usdPrice: Double?) -> Bool? {843            switch self {844            case .native(let limit): return wei <= limit845            case .usd(let limit):846                guard let usdPrice, usdPrice.isFinite, usdPrice > 0,847                      let units = Double(BaseUnits.format(wei, decimals: 18)), units.isFinite else { return nil }848                return units * usdPrice <= limit849            }850        }851852        /// True when checking the ceiling needs a price.853        public var needsPrice: Bool {854            if case .usd = self { return true }855            return false856        }857    }858859    /// Ceilings for the native coins of the EVM networks other than ether, while the engine is unaudited.860    /// Ether keeps `limits.etherWeiPerTransaction` (0.05 ETH) and `limits.etherFeeWeiPerTransaction` (0.01 ETH) on every861    /// network where it is the native coin (Ethereum, Base, Arbitrum, OP Mainnet).862    public struct EVMLimits: Sendable, Equatable {863        /// Largest value (USD) of POL, BNB or AVAX sent in one transaction: the same figure as for a token transfer.864        public let nativeUSDPerTransaction: Double865        /// Largest maximum fee (USD) of one transaction on a network whose native coin is not ether.866        public let nativeFeeUSDPerTransaction: Double867    }868869    public static let evmLimits = EVMLimits(nativeUSDPerTransaction: limits.nativeUSDPerTransaction, nativeFeeUSDPerTransaction: 5)870871    /// Largest native-coin value of one transaction on `network` for an unaudited build.872    public static func nativeValueCeiling(for network: EthereumNetwork) -> Ceiling {873        network.nativeIsEther ? .native(limits.etherWeiPerTransaction) : .usd(evmLimits.nativeUSDPerTransaction)874    }875876    /// Largest maximum fee (gas limit × maxFeePerGas, plus the L1 data fee on OP-Stack networks) of one transaction on877    /// `network` for an unaudited build.878    public static func feeCeiling(for network: EthereumNetwork) -> Ceiling {879        network.nativeIsEther ? .native(limits.etherFeeWeiPerTransaction) : .usd(evmLimits.nativeFeeUSDPerTransaction)880    }881882    /// The ceiling as text for a refusal message ("0.05 ETH", "150 USD of POL").883    public static func describe(_ ceiling: Ceiling, network: EthereumNetwork) -> String {884        switch ceiling {885        case .native(let wei): return BaseUnits.format(wei, decimals: network.nativeDecimals) + " " + network.nativeSymbol886        case .usd(let usd): return "\(Int(usd)) USD of \(network.nativeSymbol)"887        }888    }889}890891// MARK: - Price plausibility (QYV-SVC-082, QYV-SVC-087)892893extension MainnetPolicy {894    /// Lowest USD price of a native coin that the wallet accepts when it converts a dollar ceiling into coins.895    ///896    /// A dollar ceiling is checked as `units × price ≤ ceiling`, so the units it allows are `ceiling / price`: a price897    /// that is too LOW allows MORE units. A source that answers a price close to zero would turn "150 USD of BNB" into898    /// any amount of BNB. Two barriers stand against that. The first is the agreement of two independent price sources899    /// (`agreedCeilingPrice`, QYV-SVC-087). The second is this table: a price under the floor is treated as no price at900    /// all and the transaction is refused (`unauditedLimitUnverifiable`), so that even two sources lying together never901    /// let one transaction of an unaudited build move more than `nativeUSDPerTransaction / floor` coins902    /// (`absoluteNativeCeiling`).903    ///904    /// Provenance of the figures (revised on 2026-12-05). For each coin the lowest weekly low since 2022-01-01 was read905    /// on 2026-12-05 from Kraken's public candles (`GET https://api.kraken.com/0/public/OHLC?pair=<pair>&interval=10080`,906    /// field "low"); the floor is one half of that low, rounded down to two significant digits, and never under the907    /// floor the audit of 2026-12-05 had set before (a floor is only ever raised here: a higher floor allows fewer908    /// coins). Where Kraken's history is shorter than the period, the line says so: the earlier years were NOT checked909    /// and the figure rests on the listed period only.910    ///911    /// | Identifier | Pair | Lowest weekly low since 2022-01-01 (week of) | Floor |912    /// |---|---|---|---|913    /// | polygon-ecosystem-token | POLUSD | 0.0575 (2026-12-03); listed since 2023-12-21 only | 0.028 |914    /// | binancecoin | BNBUSD | 397.45 (2026-12-03); listed since 2025-04-17 only | 190 |915    /// | avalanche-2 | AVAXUSD | 5.00 (2026-12-03) | 2.5 |916    /// | solana | SOLUSD | 7.95 (2022-12-29) | 5 (previous floor, above one half of the low: kept) |917    /// | tron | TRXUSD | 0.044553 (2022-11-10) | 0.022 |918    /// | litecoin | XLTCZUSD | 31.21 (2026-12-03) | 15 |919    /// | dogecoin | XDGUSD | 0.0431 (2026-12-03) | 0.021 |920    /// | bitcoin-cash | BCHUSD | 88.00 (2022-11-03) | 44 |921    ///922    /// These are policy figures derived from one exchange's candles, not a statement about any market. A coin whose923    /// real price falls under its floor (half of its lowest price in five years) cannot be sent on mainnet by an924    /// unaudited build until the owner revises the floor: the failure is on the safe side.925    /// Keys are the CoinGecko identifiers used as `priceID`. Bitcoin and ether have ceilings in their own unit and926    /// need no price. Tokens have no floor in this table: a dollar-pegged token is bounded by `stablecoinCeilingPrice`,927    /// every other token by the agreement of two sources.928    public static let minimumPlausibleUSDPrice: [String: Double] = [929        "polygon-ecosystem-token": 0.028,930        "binancecoin": 190,931        "avalanche-2": 2.5,932        "solana": 5,933        "tron": 0.022,934        "litecoin": 15,935        "dogecoin": 0.021,936        "bitcoin-cash": 44,937    ]938939    /// True when `price` can be used to check a dollar ceiling of the asset `priceID`: finite, positive, below940    /// 10^12, and not under the floor of a native coin that has one.941    public static func isPlausibleUSDPrice(_ price: Double, priceID: String) -> Bool {942        guard price.isFinite, price > 0, price < 1e12 else { return false }943        if let floor = minimumPlausibleUSDPrice[priceID] { return price >= floor }944        return true945    }946947    /// The most coins of a native asset one transaction of an unaudited build can move, whatever the price sources948    /// answer: the dollar ceiling at the floor price. nil for an asset without a floor.949    public static func absoluteNativeCeiling(usd: Double, priceID: String) -> Double? {950        minimumPlausibleUSDPrice[priceID].map { usd / $0 }951    }952953    // MARK: Dollar-pegged tokens (QYV-SVC-087, rule a)954955    /// Lowest price used to convert the dollar ceiling of a built-in dollar-pegged token (`pegUSD`) into units:956    /// whatever the source answers, one transfer never exceeds `tokenUSDPerTransaction / 0.90` units (166.66 for 150 USD).957    public static let stablecoinCeilingPriceFloor = 0.90958    /// Quotes of a dollar-pegged token outside this range are not prices of a dollar-pegged token: the transfer is959    /// refused ("price out of the plausible range") rather than valued with them.960    public static let stablecoinPlausibleRange: ClosedRange<Double> = 0.50...2.00961962    /// The price to value a transfer of a built-in dollar-pegged token with, from the quote of one source:963    /// `max(quote, 0.90)`; nil when the quote is not finite or lies outside `stablecoinPlausibleRange`.964    ///965    /// Why the maximum: the units a dollar ceiling allows are `ceiling / price`, so the HIGHER price is the conservative966    /// one. A source lying low about USDC (0.000001) is ignored below 0.90 and refused below 0.50; a source lying high967    /// only makes the wallet allow fewer units. A real loss of the peg under 0.90 leaves the ceiling at 166.66 units,968    /// which are then worth less than 150 USD.969    public static func stablecoinCeilingPrice(quote: Double) -> Double? {970        guard quote.isFinite, stablecoinPlausibleRange.contains(quote) else { return nil }971        return max(quote, stablecoinCeilingPriceFloor)972    }973974    /// The largest number of whole units of a dollar-pegged token one transfer of an unaudited build can carry.975    public static var stablecoinAbsoluteUnitCeiling: Double { limits.tokenUSDPerTransaction / stablecoinCeilingPriceFloor }976977    // MARK: Two independent sources (QYV-SVC-087, rules b and c)978979    /// Largest relative difference between the two price sources for their prices to count as the same price.980    public static let priceAgreementTolerance = 0.05981982    /// The price to convert a dollar ceiling with, from the quotes of two independent sources: nil unless both are983    /// usable and differ by at most `priceAgreementTolerance` of the larger; otherwise the HIGHER of the two.984    ///985    /// Why the higher and not the lower: the ceiling is `units × price ≤ dollars`, i.e. `units ≤ dollars / price`.986    /// The lower price would allow more units — it would let the source that is wrong on the low side decide. The987    /// higher price allows fewer units, and within the tolerance the two differ by at most 5 %: taking the higher988    /// costs an honest user at most 5 % of the ceiling and gives a lying source nothing.989    public static func agreedCeilingPrice(_ first: Double, _ second: Double, tolerance: Double = priceAgreementTolerance) -> Double? {990        guard first.isFinite, second.isFinite, first > 0, second > 0, first < 1e12, second < 1e12 else { return nil }991        let high = max(first, second), low = min(first, second)992        guard high - low <= tolerance * high else { return nil }993        return high994    }995}996997// MARK: - Solana and TRON limits998999extension MainnetPolicy {1000    /// Per-transaction ceilings of an unaudited build on a chain whose native coin has no ceiling of its own in `limits`1001    /// (Solana, TRON). Nothing here raises an existing limit: the fiat figure is `limits.nativeUSDPerTransaction`, the one1002    /// used for the UTXO coins and for the EVM coins other than ether, converted with `nativeCeiling(usd:priceUSD:decimals:)`.1003    public struct AccountChainLimits: Sendable, Equatable {1004        /// Largest value (USD) of the native coin sent by one transaction, checked with a fresh price of the coin.1005        /// Without a fresh price the transaction is refused. Tokens (SPL, TRC-20) stay under `limits.tokenUSDPerTransaction`.1006        public let nativeUSDPerTransaction: Double1007        /// Largest fee the transaction may commit to, in base units of the native coin (lamports, sun).1008        /// Solana: the priority fee (compute-unit limit × price). TRON: `fee_limit`, and the worst-case burn of a transfer.1009        public let feePerTransaction: UInt641010    }10111012    /// Solana mainnet-beta: `limits.nativeUSDPerTransaction` (150 USD) of SOL per transaction; priority fee at most 0.01 SOL (10 000 000 lamports), the value1013    /// `SolanaSendPlanner.maximumPriorityFee` already refuses above on every cluster.1014    public static let solanaLimits = AccountChainLimits(nativeUSDPerTransaction: limits.nativeUSDPerTransaction, feePerTransaction: 10_000_000)10151016    /// TRON mainnet: `limits.nativeUSDPerTransaction` (150 USD) of TRX per transaction; `fee_limit` and the worst-case fee at most 100 TRX (100 000 000 sun),1017    /// the default ceiling of `TronSendPlanner.Policy`.1018    public static let tronLimits = AccountChainLimits(nativeUSDPerTransaction: limits.nativeUSDPerTransaction, feePerTransaction: 100_000_000)10191020    /// Largest rent (lamports) the wallet accepts to lock in a new token account for the recipient of an SPL transfer:1021    /// 0.01 SOL. The cluster's value was 0.00203928 SOL (legacy program) and 0.00207408 SOL (Token-2022) on 2026-12-05;1022    /// a larger figure from an endpoint is treated as an untrusted answer, on every cluster.1023    public static let solanaAccountCreationLamportsCeiling: UInt64 = 10_000_0001024}1025
Files main
Menu

Theme