SPB Git

Repository Public

UTXONetworkTests.swift 23.5 KB 396 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraCoreTests/UTXONetworkTests.swift8// Module           : Tests9// 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 Testing43import QyvoraMath44import QyvoraSymmetric45@testable import QyvoraCore4647/// CashAddr against the vectors of its specification (CashAddrVectors.swift), and against mutations of them.48@Suite struct CashAddrTests {49    @Test func translationExamplesOfTheSpecification() throws {50        #expect(CashAddrVectors.translation.count == 6)51        for (legacy, cash) in CashAddrVectors.translation {52            let payload = try #require(Base58Check.decode(legacy))53            let decoded = try #require(CashAddr.decode(cash))54            #expect(decoded.prefix == "bitcoincash")55            #expect(decoded.hash == [UInt8](payload.dropFirst()))56            // Base58 version 0x00 is P2PKH (type 0), 0x05 is P2SH (type 1)57            #expect(decoded.type == (payload[0] == 0x00 ? CashAddr.typeP2PKH : CashAddr.typeP2SH))58            #expect(CashAddr.encode(prefix: "bitcoincash", type: decoded.type, hash: decoded.hash) == cash)59        }60    }6162    @Test func largerVectorsOfTheSpecification() throws {63        #expect(CashAddrVectors.larger.count == 32)64        for v in CashAddrVectors.larger {65            let payload = try #require(Hex.decode(v.payload.lowercased()))66            #expect(payload.count == v.size)67            let colon = try #require(v.address.firstIndex(of: ":"))68            let prefix = String(v.address[..<colon]), body = String(v.address[v.address.index(after: colon)...])69            #expect(CashAddr.encode(prefix: prefix, type: v.type, hash: payload) == v.address)70            let decoded = try #require(CashAddr.decode(v.address))71            #expect(decoded == CashAddr.Decoded(prefix: prefix, type: v.type, hash: payload))72            // the prefix may come from the context, and QR codes are upper case73            #expect(CashAddr.decode(body, defaultPrefix: prefix) == decoded)74            #expect(CashAddr.decode(v.address.uppercased()) == decoded)75            // without a prefix nothing can be verified; with another one the checksum fails76            #expect(CashAddr.decode(body) == nil)77            #expect(CashAddr.decode(body, defaultPrefix: prefix == "pref" ? "prefix" : "pref") == nil)78        }79    }8081    @Test func checksumExamplesOfTheSpecification() {82        #expect(CashAddrVectors.validChecksums.count == 5)83        for text in CashAddrVectors.validChecksums {84            #expect(CashAddr.hasValidChecksum(text), "\(text)")85            #expect(CashAddr.hasValidChecksum(text.uppercased()))86            // changing any one character breaks it87            var bytes = [UInt8](text.utf8)88            let last = bytes.count - 189            bytes[last] = bytes[last] == 0x71 ? 0x70 : 0x7190            #expect(!CashAddr.hasValidChecksum(String(decoding: bytes, as: UTF8.self)))91        }92        // valid checksums, but not addresses: the payload is not a version byte and a hash of an allowed size93        #expect(CashAddr.decode("prefix:x64nx6hz") == nil)94        #expect(CashAddr.decode("bchtest:testnetaddress4d6njnut") == nil)95    }9697    @Test func everySingleCharacterErrorIsDetected() throws {98        let good = "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a"99        let prefixLength = "bitcoincash:".utf8.count100        let alphabet = [UInt8]("qpzry9x8gf2tvdw0s3jn54khce6mua7l".utf8)101        var tried = 0102        var bytes = [UInt8](good.utf8)103        for position in prefixLength..<bytes.count {104            let original = bytes[position]105            for replacement in alphabet where replacement != original {106                bytes[position] = replacement107                #expect(CashAddr.decode(String(decoding: bytes, as: UTF8.self)) == nil)108                tried += 1109            }110            bytes[position] = original111        }112        #expect(tried == 42 * 31)113        // two adjacent characters swapped114        for position in prefixLength..<(bytes.count - 1) where bytes[position] != bytes[position + 1] {115            var swapped = bytes116            swapped.swapAt(position, position + 1)117            #expect(CashAddr.decode(String(decoding: swapped, as: UTF8.self)) == nil)118        }119    }120121    @Test func malformedInputIsRefused() {122        let good = "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a"123        let body = String(good.dropFirst("bitcoincash:".count))124        let bad = [125            "", ":", "bitcoincash:", ":" + body, "a:b:c", "bitcoincash:" + body + ":", "bitcoincash::" + body,126            "bitcoincash:Qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a",   // mixed case in the payload127            "Bitcoincash:" + body,                                       // mixed case through the prefix128            "bitcoincash:" + body.dropLast(),                            // truncated129            "bitcoincash:" + body + "q",                                 // one character too many130            "bitcoincash: " + body, " " + good, good + " ", good + "\n",131            "bitcoincash:" + body.replacingOccurrences(of: "q", with: "b"),   // "b" is not in the character set132            "bitcoincash:" + body.replacingOccurrences(of: "q", with: "1"),133            "bitcoin-cash:" + body, "bitcoincash1:" + body, "bitcöincash:" + body,134            "bchtest:" + body,                                           // right payload under another prefix135            String(repeating: "q", count: 200),136            "bitcoincash:" + String(repeating: "q", count: 113),137        ]138        for text in bad { #expect(CashAddr.decode(text) == nil, "accepted: \(text)") }139        #expect(CashAddr.decode(body) == nil)140        #expect(CashAddr.decode(body, defaultPrefix: "bchtest") == nil)141        #expect(CashAddr.decode(body, defaultPrefix: "bitcoincash") != nil)142        #expect(CashAddr.decode(body, defaultPrefix: "BITCOINCASH") == nil)143    }144145    @Test func encoderRefusesWhatTheFormatCannotExpress() {146        let h = [UInt8](repeating: 7, count: 20)147        #expect(CashAddr.encode(prefix: "bitcoincash", type: 0, hash: h) != nil)148        #expect(CashAddr.encode(prefix: "bitcoincash", type: 16, hash: h) == nil)149        #expect(CashAddr.encode(prefix: "", type: 0, hash: h) == nil)150        #expect(CashAddr.encode(prefix: "BitcoinCash", type: 0, hash: h) == nil)151        #expect(CashAddr.encode(prefix: "bch1", type: 0, hash: h) == nil)152        for size in [0, 1, 19, 21, 33, 63, 65] {153            #expect(CashAddr.encode(prefix: "bitcoincash", type: 0, hash: [UInt8](repeating: 1, count: size)) == nil)154        }155    }156157    @Test func versionByteRulesAreEnforcedOnDecode() throws {158        // Build payloads by hand with a correct checksum but a wrong version byte, through the encoder of a longer hash:159        // a 24-byte hash announced as 20 bytes cannot be produced by `encode`, so check the reserved bit and size rule160        // on re-encoded words instead.161        let hash = [UInt8](repeating: 0xab, count: 20)162        let good = try #require(CashAddr.encode(prefix: "bitcoincash", type: 1, hash: hash))163        #expect(CashAddr.decode(good)?.type == 1)164        // token-aware types 2 and 3 decode (the wallet layer decides what to do with them)165        for type: UInt8 in [2, 3, 15] {166            let text = try #require(CashAddr.encode(prefix: "bitcoincash", type: type, hash: hash))167            #expect(CashAddr.decode(text)?.type == type)168        }169        // random round trips over every size170        var state: UInt64 = 0x1234_5678_9abc_def0171        func next() -> UInt8 {172            state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407173            return UInt8(truncatingIfNeeded: state >> 33)174        }175        for size in [20, 24, 28, 32, 40, 48, 56, 64] {176            for type: UInt8 in [0, 1] {177                let h = (0..<size).map { _ in next() }178                let text = try #require(CashAddr.encode(prefix: "bchtest", type: type, hash: h))179                #expect(CashAddr.decode(text) == CashAddr.Decoded(prefix: "bchtest", type: type, hash: h))180            }181        }182    }183}184185/// Parameters of every UTXO network, compared with the values published by each project (see the comments of186/// `BitcoinNetwork`): a table written a second time here, so that an accidental edit of one side is caught.187@Suite struct UTXONetworkParameterTests {188    struct Expected {189        let network: BitcoinNetwork190        let raw: String191        let coin: UTXOCoin192        let ticker: String193        let test: Bool194        let coinType: UInt32195        let p2pkh: UInt8196        let p2sh: UInt8197        let wif: UInt8198        let hrp: String?199        let cashPrefix: String?200        let purpose: UTXOAccountPurpose201        let scheme: UTXOSighashScheme202        let rbf: Bool203        let genesis: String204    }205206    static let table: [Expected] = [207        Expected(network: .mainnet, raw: "mainnet", coin: .bitcoin, ticker: "BTC", test: false, coinType: 0, p2pkh: 0x00, p2sh: 0x05, wif: 0x80,208                 hrp: "bc", cashPrefix: nil, purpose: .bip84, scheme: .bip143, rbf: true,209                 genesis: "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"),210        Expected(network: .testnet, raw: "testnet", coin: .bitcoin, ticker: "BTC", test: true, coinType: 1, p2pkh: 0x6f, p2sh: 0xc4, wif: 0xef,211                 hrp: "tb", cashPrefix: nil, purpose: .bip84, scheme: .bip143, rbf: true,212                 genesis: "000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"),213        Expected(network: .signet, raw: "signet", coin: .bitcoin, ticker: "BTC", test: true, coinType: 1, p2pkh: 0x6f, p2sh: 0xc4, wif: 0xef,214                 hrp: "tb", cashPrefix: nil, purpose: .bip84, scheme: .bip143, rbf: true,215                 genesis: "00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6"),216        Expected(network: .litecoin, raw: "litecoin", coin: .litecoin, ticker: "LTC", test: false, coinType: 2, p2pkh: 48, p2sh: 50, wif: 176,217                 hrp: "ltc", cashPrefix: nil, purpose: .bip84, scheme: .bip143, rbf: true,218                 genesis: "12a765e31ffd4059bada1e25190f6e98c99d9714d334efa41a195a7e7e04bfe2"),219        Expected(network: .litecoinTestnet, raw: "litecoinTestnet", coin: .litecoin, ticker: "LTC", test: true, coinType: 1, p2pkh: 111, p2sh: 58, wif: 239,220                 hrp: "tltc", cashPrefix: nil, purpose: .bip84, scheme: .bip143, rbf: true,221                 genesis: "4966625a4b2851d9fdee139e56211a0d88575f59ed816ff5e6a63deb4e3e29a0"),222        Expected(network: .dogecoin, raw: "dogecoin", coin: .dogecoin, ticker: "DOGE", test: false, coinType: 3, p2pkh: 30, p2sh: 22, wif: 158,223                 hrp: nil, cashPrefix: nil, purpose: .bip44, scheme: .legacy, rbf: true,224                 genesis: "1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691"),225        Expected(network: .dogecoinTestnet, raw: "dogecoinTestnet", coin: .dogecoin, ticker: "DOGE", test: true, coinType: 1, p2pkh: 113, p2sh: 196, wif: 241,226                 hrp: nil, cashPrefix: nil, purpose: .bip44, scheme: .legacy, rbf: true,227                 genesis: "bb0a78264637406b6360aad926284d544d7049f45189db5664f3c4d07350559e"),228        Expected(network: .bitcoinCash, raw: "bitcoinCash", coin: .bitcoinCash, ticker: "BCH", test: false, coinType: 145, p2pkh: 0, p2sh: 5, wif: 128,229                 hrp: nil, cashPrefix: "bitcoincash", purpose: .bip44, scheme: .bip143ForkID, rbf: false,230                 genesis: "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"),231        Expected(network: .bitcoinCashTestnet, raw: "bitcoinCashTestnet", coin: .bitcoinCash, ticker: "BCH", test: true, coinType: 1, p2pkh: 111, p2sh: 196, wif: 239,232                 hrp: nil, cashPrefix: "bchtest", purpose: .bip44, scheme: .bip143ForkID, rbf: false,233                 genesis: "000000001dd410c49a788668ce26751718cc797474d3152a5fc073dd44fd9f7b"),234    ]235236    @Test func everyNetworkHasItsPublishedParameters() {237        #expect(BitcoinNetwork.allCases.count == Self.table.count)238        #expect(Set(Self.table.map(\.network)) == Set(BitcoinNetwork.allCases))239        for e in Self.table {240            let n = e.network241            #expect(n.rawValue == e.raw)242            #expect(BitcoinNetwork(rawValue: e.raw) == n)243            #expect(n.coin == e.coin)244            #expect(n.ticker == e.ticker)245            #expect(n.displayTicker == (e.test ? "t" + e.ticker : e.ticker))246            #expect(n.decimals == 8)247            #expect(n.isTest == e.test)248            #expect(n.coinType == e.coinType)249            #expect(n.p2pkhVersion == e.p2pkh)250            #expect(n.p2shVersion == e.p2sh)251            #expect(n.wifVersion == e.wif)252            #expect(n.bech32HRP == e.hrp)253            #expect(n.hrp == (e.hrp ?? ""))254            #expect(n.supportsSegWit == (e.hrp != nil))255            #expect(n.cashAddrPrefix == e.cashPrefix)256            #expect(n.defaultPurpose == e.purpose)257            #expect(n.supports(.bip44))258            #expect(n.supports(.bip84) == (e.hrp != nil))259            #expect(n.sighashScheme == e.scheme)260            #expect(n.supportsRBF == e.rbf)261            #expect(n.supportsPSBT)262            #expect(n.psbtRequiresPreviousTransactions == (e.hrp == nil))263            #expect(n.signatureCommitsToAmounts == (e.scheme != .legacy))264            #expect(n.genesisHash == e.genesis)265            #expect(n.priceID == nil || !e.test)266            #expect(!n.displayName.isEmpty)267            // counterparts stay inside the coin268            #expect(n.mainCounterpart.coin == e.coin && !n.mainCounterpart.isTest)269            #expect(n.testCounterpart.coin == e.coin && n.testCounterpart.isTest)270            #expect(n.isTest ? n.testCounterpart == n : n.mainCounterpart == n)271            #expect(BitcoinNetwork.networks(of: e.coin).contains(n))272        }273        #expect(BitcoinNetwork.mainnet.testCounterpart == .signet)274        #expect(BitcoinNetwork.networks(of: .bitcoin) == [.mainnet, .testnet, .signet])275        #expect(Set(BitcoinNetwork.allCases.compactMap(\.priceID)) == ["bitcoin", "litecoin", "dogecoin", "bitcoin-cash"])276        #expect(BitcoinNetwork.litecoin.deprecatedP2SHVersion == 0x05 && BitcoinNetwork.litecoinTestnet.deprecatedP2SHVersion == 0xc4)277        #expect(BitcoinNetwork.allCases.filter { $0.coin != .litecoin }.allSatisfy { $0.deprecatedP2SHVersion == nil })278    }279280    /// Stored profiles and caches hold the raw value of the network: the first three never change.281    @Test func storedValuesStillDecode() throws {282        let decoded = try JSONDecoder().decode([BitcoinNetwork].self, from: Data(#"["mainnet","testnet","signet"]"#.utf8))283        #expect(decoded == [.mainnet, .testnet, .signet])284        let all = try JSONDecoder().decode([BitcoinNetwork].self, from: try JSONEncoder().encode(BitcoinNetwork.allCases))285        #expect(all == BitcoinNetwork.allCases)286        #expect(throws: (any Error).self) { try JSONDecoder().decode([BitcoinNetwork].self, from: Data(#"["dogecoin2"]"#.utf8)) }287    }288289    @Test func chainFacts() {290        #expect(BitcoinNetwork.mainnet.blockTimeSeconds == 600 && BitcoinNetwork.bitcoinCash.blockTimeSeconds == 600)291        #expect(BitcoinNetwork.litecoin.blockTimeSeconds == 150 && BitcoinNetwork.dogecoin.blockTimeSeconds == 60)292        #expect(BitcoinNetwork.dogecoin.minimumConfirmationsHint == 20 && BitcoinNetwork.litecoin.minimumConfirmationsHint == 6)293        #expect(BitcoinNetwork.mainnet.maximumMoney == 2_100_000_000_000_000)294        #expect(BitcoinNetwork.bitcoinCash.maximumMoney == 2_100_000_000_000_000)295        #expect(BitcoinNetwork.litecoin.maximumMoney == 8_400_000_000_000_000)296        #expect(BitcoinNetwork.dogecoin.maximumMoney == 1_000_000_000_000_000_000)297        // identity: the genesis block, except where another chain shares it298        for n in BitcoinNetwork.allCases where n.coin != .bitcoinCash {299            #expect(n.identityBlock == UTXOChainIdentity(height: 0, hash: n.genesisHash))300        }301        #expect(BitcoinNetwork.bitcoinCash.identityBlock == UTXOChainIdentity(height: 661_648, hash: "0000000000000000029e471c41818d24b8b74c911071c4ef0b4a0509f9b5a8ce"))302        #expect(BitcoinNetwork.bitcoinCashTestnet.identityBlock.height == 200_000)303        #expect(BitcoinNetwork.bitcoinCash.genesisHash == BitcoinNetwork.mainnet.genesisHash)304        for n in BitcoinNetwork.allCases {305            #expect(n.identityBlock.hash.utf8.count == 64 && n.genesisHash.utf8.count == 64)306            #expect(n.indexerAvailable == (n != .dogecoinTestnet))307            if let base = n.explorerBaseURL {308                #expect(base.hasPrefix("https://") && !base.hasSuffix("/"))309                let txid = String(repeating: "ab", count: 32)310                #expect(n.explorerTransactionURL(txid: txid) == base + (n == .dogecoin ? "/transaction/" : "/tx/") + txid)311            }312            #expect(n.explorerTransactionURL(txid: "../../etc") == nil)313            #expect(n.explorerTransactionURL(txid: String(repeating: "AB", count: 32)) == nil)314        }315        #expect(BitcoinNetwork.dogecoinTestnet.explorerBaseURL == nil)316    }317318    @Test func feePolicies() {319        #expect(BitcoinNetwork.mainnet.feePolicy == UTXOFeePolicy(minimumFeeRatePerKiloVByte: 1_000, maximumFeeRatePerKiloVByte: 5_000_000, dust: .relayFee(perKiloVByte: 3_000)))320        #expect(BitcoinNetwork.litecoin.feePolicy == UTXOFeePolicy(minimumFeeRatePerKiloVByte: 1_000, maximumFeeRatePerKiloVByte: 5_000_000, dust: .relayFee(perKiloVByte: 30_000)))321        // 0.01 DOGE per kB, dust 0.01 DOGE322        #expect(BitcoinNetwork.dogecoin.feePolicy == UTXOFeePolicy(minimumFeeRatePerKiloVByte: 1_000_000, maximumFeeRatePerKiloVByte: 100_000_000, dust: .fixed(1_000_000)))323        // 1 sat per byte, dust 546 sat324        #expect(BitcoinNetwork.bitcoinCash.feePolicy == UTXOFeePolicy(minimumFeeRatePerKiloVByte: 1_000, maximumFeeRatePerKiloVByte: 1_000_000, dust: .fixed(546)))325        for n in BitcoinNetwork.allCases {326            #expect(n.feePolicy == n.mainCounterpart.feePolicy)327            #expect(n.feePolicy.minimumFeeRatePerKiloVByte < n.feePolicy.maximumFeeRatePerKiloVByte)328        }329    }330331    @Test func derivationPaths() {332        #expect(StandardPaths.bip84Account(.mainnet).description == "m/84'/0'/0'")333        #expect(StandardPaths.bip84Account(.signet, account: 2).description == "m/84'/1'/2'")334        #expect(StandardPaths.account(.bip84, .litecoin).description == "m/84'/2'/0'")335        #expect(StandardPaths.bip44Account(.dogecoin).description == "m/44'/3'/0'")336        #expect(StandardPaths.bip44Account(.bitcoinCash, account: 1).description == "m/44'/145'/1'")337        #expect(StandardPaths.bip44Account(.bitcoinCashTestnet).description == "m/44'/1'/0'")338        #expect(StandardPaths.account(.bip84, .mainnet, account: 3) == StandardPaths.bip84Account(.mainnet, account: 3))339    }340}341342@Suite struct UTXOMainnetPolicyTests {343    /// The ceilings that existed before the UTXO upgrade are unchanged.344    @Test func existingLimitsAreNotRaised() {345        let l = MainnetPolicy.limits346        #expect(l.bitcoinSatoshisPerTransaction == 200_000)347        #expect(l.etherWeiPerTransaction == UInt256(50_000_000_000_000_000))348        #expect(l.tokenUSDPerTransaction == 150)349        #expect(l.bitcoinFeeSatoshisPerTransaction == 20_000)350        #expect(l.bitcoinFeeRateSatPerVByte == 200)351        #expect(l.etherFeeWeiPerTransaction == UInt256(10_000_000_000_000_000))352        #expect(l.nativeUSDPerTransaction == 150)353        // the same figure bounds the native coins of the EVM networks that are not ether: one policy, two constants354        #expect(l.nativeUSDPerTransaction == MainnetPolicy.evmLimits.nativeUSDPerTransaction)355        #expect(!MainnetPolicy.auditCompleted)356    }357358    @Test func utxoLimitsPerNetwork() throws {359        for n in BitcoinNetwork.allCases where n.isTest { #expect(MainnetPolicy.utxoLimits(n) == nil) }360        let btc = try #require(MainnetPolicy.utxoLimits(.mainnet))361        #expect(btc == MainnetPolicy.UTXOLimits(value: .baseUnits(200_000), feePerTransaction: 20_000, feeRatePerVByte: 200))362        // Litecoin: 0.001 LTC; Dogecoin: 5 DOGE; Bitcoin Cash: 0.0005 BCH — and 150 USD of value each363        #expect(MainnetPolicy.utxoLimits(.litecoin) == MainnetPolicy.UTXOLimits(value: .usd(150), feePerTransaction: 100_000, feeRatePerVByte: 200))364        #expect(MainnetPolicy.utxoLimits(.dogecoin) == MainnetPolicy.UTXOLimits(value: .usd(150), feePerTransaction: 500_000_000, feeRatePerVByte: 100_000))365        #expect(MainnetPolicy.utxoLimits(.bitcoinCash) == MainnetPolicy.UTXOLimits(value: .usd(150), feePerTransaction: 50_000, feeRatePerVByte: 20))366        // every rate ceiling sits inside the network's own bounds367        for n in BitcoinNetwork.allCases where !n.isTest {368            let limits = try #require(MainnetPolicy.utxoLimits(n))369            #expect(limits.feeRatePerVByte * 1000 >= n.feePolicy.minimumFeeRatePerKiloVByte)370            #expect(limits.feeRatePerVByte * 1000 <= n.feePolicy.maximumFeeRatePerKiloVByte)371        }372    }373374    @Test func fiatCeilingConversion() {375        // 150 USD at 100 USD per coin = 1.5 coin376        #expect(MainnetPolicy.nativeCeiling(usd: 150, priceUSD: 100, decimals: 8) == 150_000_000)377        // at 0.25 USD per DOGE = 600 DOGE378        #expect(MainnetPolicy.nativeCeiling(usd: 150, priceUSD: 0.25, decimals: 8) == 60_000_000_000)379        #expect(MainnetPolicy.nativeCeiling(usd: 0, priceUSD: 10, decimals: 8) == 0)380        // rounding is downward381        #expect(MainnetPolicy.nativeCeiling(usd: 1, priceUSD: 3, decimals: 8) == 33_333_333)382        // no usable price, no ceiling: the caller refuses the transaction383        for price in [0, -1, Double.nan, Double.infinity, -Double.infinity] {384            #expect(MainnetPolicy.nativeCeiling(usd: 150, priceUSD: price, decimals: 8) == nil)385        }386        #expect(MainnetPolicy.nativeCeiling(usd: .nan, priceUSD: 1, decimals: 8) == nil)387        #expect(MainnetPolicy.nativeCeiling(usd: -1, priceUSD: 1, decimals: 8) == nil)388        #expect(MainnetPolicy.nativeCeiling(usd: 150, priceUSD: 1, decimals: 19) == nil)389        #expect(MainnetPolicy.nativeCeiling(usd: 150, priceUSD: 1, decimals: -1) == nil)390        // a very small price saturates instead of trapping; one so small that the division overflows is no price at all391        #expect(MainnetPolicy.nativeCeiling(usd: 150, priceUSD: 1e-10, decimals: 18) == UInt64(Int64.max))392        #expect(MainnetPolicy.nativeCeiling(usd: 150, priceUSD: 1e-300, decimals: 18) == nil)393        #expect(MainnetPolicy.nativeCeiling(usd: 150, priceUSD: .leastNonzeroMagnitude, decimals: 18) == nil)394    }395}396
Files main
Menu

Theme