Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/PriceCeilingAuditRegressionTests.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 QyvoraCore45import QyvoraBitcoin46import QyvoraEthereum47import QyvoraNetworking48import QyvoraSolana49import QyvoraTron50@testable import QyvoraWallet5152// Regression tests of QYV-SVC-087: the dollar ceilings of an unaudited mainnet build are converted into units with a53// price no single source decides. A ceiling is `units × price ≤ dollars`: a price that is too LOW allows MORE units.54// Rules under test: (a) built-in dollar-pegged tokens are valued at max(quote, 0.90) and refused outside 0.50…2.00;55// (b) every other token and (c) every native coin with a dollar ceiling need two independent sources that agree within56// 5 %, the higher of the two being used; (d) the rules hold when a payment is prepared and again when it is signed.5758extension WalletService {59 /// Test hook: writes a custom EVM token into the profile as a modified profile file would.60 func injectCustomTokenForTesting(_ token: TokenInfo) { profile.customTokens.append(token) }61}6263@Suite(.readsMainnetPolicy) struct PriceCeilingPolicyTests {64 @Test func aDollarPeggedTokenIsNeverValuedUnderNinetyCents() {65 #expect(MainnetPolicy.stablecoinCeilingPrice(quote: 0.000001) == nil)66 #expect(MainnetPolicy.stablecoinCeilingPrice(quote: 0.4999) == nil)67 #expect(MainnetPolicy.stablecoinCeilingPrice(quote: 0.50) == 0.90)68 #expect(MainnetPolicy.stablecoinCeilingPrice(quote: 0.89) == 0.90)69 #expect(MainnetPolicy.stablecoinCeilingPrice(quote: 0.9987) == 0.9987)70 #expect(MainnetPolicy.stablecoinCeilingPrice(quote: 1.5) == 1.5)71 #expect(MainnetPolicy.stablecoinCeilingPrice(quote: 2.00) == 2.00)72 #expect(MainnetPolicy.stablecoinCeilingPrice(quote: 2.0001) == nil)73 for hostile in [Double.nan, .infinity, -.infinity, -1, 0] { #expect(MainnetPolicy.stablecoinCeilingPrice(quote: hostile) == nil) }74 // the absolute bound in units: 150 / 0.9075 #expect(abs(MainnetPolicy.stablecoinAbsoluteUnitCeiling - 166.6666) < 0.001)76 }7778 @Test func twoSourcesMustAgreeAndTheHigherPriceIsUsed() {79 // the higher price allows fewer units: it is the conservative one80 #expect(MainnetPolicy.agreedCeilingPrice(100, 104) == 104)81 #expect(MainnetPolicy.agreedCeilingPrice(104, 100) == 104)82 #expect(MainnetPolicy.agreedCeilingPrice(100, 100) == 100)83 // exactly 5 % of the higher is still an agreement, beyond is not84 #expect(MainnetPolicy.agreedCeilingPrice(95, 100) == 100)85 #expect(MainnetPolicy.agreedCeilingPrice(94.99, 100) == nil)86 #expect(MainnetPolicy.agreedCeilingPrice(100, 106) == nil)87 #expect(MainnetPolicy.agreedCeilingPrice(0.000001, 100) == nil)88 #expect(MainnetPolicy.agreedCeilingPrice(100, 1e9) == nil)89 for hostile in [Double.nan, .infinity, -1, 0, 1e12] {90 #expect(MainnetPolicy.agreedCeilingPrice(hostile, 100) == nil)91 #expect(MainnetPolicy.agreedCeilingPrice(100, hostile) == nil)92 }93 }9495 @Test func theTablesAreConsistent() throws {96 // every dollar-pegged built-in token has a price identifier, and none of those identifiers has a pair at the97 // second source (a pegged token never falls back to the two-source rule by accident, nor the reverse)98 var pegged = 099 for network in EthereumNetwork.mainNetworks {100 for token in BuiltInTokens.tokens(for: network) where BuiltInTokens.isDollarPegged(token.address, network: network) {101 pegged += 1102 let id = try #require(token.priceID, "\(network) \(token.symbol)")103 #expect(PriceClient.checkPairs[id] == nil, "\(id)")104 #expect(["USDC", "USDC.e", "USDT", "USDT0", "DAI", "PYUSD", "USDS"].contains(token.symbol), "\(network) \(token.symbol)")105 }106 // EURC is pegged to the euro: never treated as a dollar107 for token in BuiltInTokens.tokens(for: network) where token.symbol == "EURC" {108 #expect(!BuiltInTokens.isDollarPegged(token.address, network: network))109 #expect(PriceClient.checkPairs[try #require(token.priceID)] == "EURCUSD")110 }111 }112 #expect(pegged == 30)113 #expect(SolanaToken.builtIn(.mainnetBeta).allSatisfy(\.pegUSD) && SolanaToken.builtIn(.mainnetBeta).count == 2)114 #expect(TronBuiltInTokens.mainnet.allSatisfy { TronBuiltInTokens.isDollarPegged($0.contract, on: .mainnet) })115 #expect(!TronBuiltInTokens.isDollarPegged(try #require(TronBuiltInTokens.mainnet.first).contract, on: .nile))116 // a test network has no built-in token, hence no pegged one117 let usdc = try #require(BuiltInTokens.mainnet.first { $0.symbol == "USDC" })118 #expect(!BuiltInTokens.isDollarPegged(usdc.address, network: .sepolia) && !BuiltInTokens.isDollarPegged(usdc.address, network: .base))119 // every native coin with a dollar ceiling has a floor and a pair at the second source120 for id in ["polygon-ecosystem-token", "binancecoin", "avalanche-2", "solana", "tron", "litecoin", "dogecoin", "bitcoin-cash"] {121 #expect(MainnetPolicy.minimumPlausibleUSDPrice[id] != nil && PriceClient.checkPairs[id] != nil, "\(id)")122 }123 // the floors as documented in MainnetPolicy (Kraken weekly lows read on 2026-12-05): a change must be deliberate124 #expect(MainnetPolicy.minimumPlausibleUSDPrice == [125 "polygon-ecosystem-token": 0.028, "binancecoin": 190, "avalanche-2": 2.5, "solana": 5, "tron": 0.022, "litecoin": 15,126 "dogecoin": 0.021, "bitcoin-cash": 44,127 ])128 }129}130131extension MainnetPolicyTests {132 static let linkMainnet = "0x514910771AF9Ca656af840dff83E8264EcF986CA"133 static let makerMainnet = "0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2"134135 /// The refusal of `body`, or nil when it went through (unlike `walletError`, success is not a test failure).136 static func attempt<T>(_ body: () async throws -> T) async -> WalletError? {137 do {138 _ = try await body()139 return nil140 } catch let e as WalletError {141 return e142 } catch {143 Issue.record("unexpected error type: \(error)")144 return nil145 }146 }147148 static func unverifiable(_ error: WalletError?) -> String? {149 if case .unauditedLimitUnverifiable(let text)? = error { return text }150 return nil151 }152153 /// A mainnet wallet holding `symbol` (a built-in token of Ethereum).154 static func walletHolding(_ symbol: String, decimals: Int) async throws -> (Harness, TokenInfo) {155 let h = try await mainnetWallet()156 let token = try #require(BuiltInTokens.mainnet.first { $0.symbol == symbol })157 h.backend.balances[EthereumWalletTests.owner] = EthereumWalletTests.oneEther158 var contract = FakeBackend.TokenContract(symbol: symbol, name: token.name, decimals: UInt256(UInt64(decimals)))159 contract.balances[EthereumWalletTests.owner] = UInt256(1_000_000_000).multipliedReportingOverflow(by: UInt256(1_000_000_000_000_000_000)).0160 h.backend.tokens[token.address.checksummed.lowercased()] = contract161 return (h, token)162 }163164 static func units(_ whole: UInt64, millionths: UInt64 = 0, decimals: Int) -> UInt256 {165 var scale = UInt256(1)166 for _ in 0..<(decimals - 6) { scale = scale.multipliedReportingOverflow(by: UInt256(10)).0 }167 return UInt256(whole * 1_000_000 + millionths).multipliedReportingOverflow(by: scale).0168 }169170 /// Rule (a): a price source lying low about a dollar-pegged token does not lift the ceiling.171 @Test func aLyingPriceDoesNotLiftTheCeilingOfADollarPeggedToken() async throws {172 Self.reset()173 defer { Self.reset() }174 let (h, usdc) = try await Self.walletHolding("USDC", decimals: 6)175 defer { h.cleanup() }176 let recipient = EthereumWalletTests.recipient177 let limit = WalletError.exceedsUnauditedLimit(limit: "150 USD per token transfer")178 func prepare(_ amount: UInt64) async -> WalletError? {179 await Self.attempt { try await h.service.prepareEthereumSend(asset: .token(usdc), to: recipient, amount: UInt256(amount)) }180 }181 func setPrice(_ text: String) {182 h.clock.advance(WalletService.quoteFreshness + 1)183 h.backend.markets = ServiceTests.market([("usd-coin", text)])184 }185 // the second source is not needed for a pegged token: it is down for the whole test186 h.backend.checkStatus = 503187188 // lying low, the attack of the finding: one millionth of a dollar per USDC would have allowed 150 million USDC189 setPrice("0.000001")190 #expect(Self.unverifiable(await prepare(1_000_000))?.contains("out of the plausible range") == true)191 #expect(Self.unverifiable(await prepare(150_000_000_000_000))?.contains("out of the plausible range") == true)192 setPrice("0.4999")193 #expect(Self.unverifiable(await prepare(1_000_000))?.contains("out of the plausible range") == true)194 // a quote between 0.50 and 0.90 counts as 0.90: at most 166.666666 USDC, whatever the source says195 for low in ["0.50", "0.6", "0.8999"] {196 setPrice(low)197 #expect(await prepare(166_666_666) == nil, "\(low)")198 #expect(await prepare(166_666_667) == limit, "\(low)")199 }200 // an honest quote slightly under one dollar201 setPrice("0.9987")202 #expect(await prepare(150_000_000) == nil)203 #expect(await prepare(150_190_000) == nil)204 #expect(await prepare(150_200_000) == limit)205 // lying high only tightens206 setPrice("1.9")207 #expect(await prepare(78_900_000) == nil)208 #expect(await prepare(79_000_000) == limit)209 setPrice("2.0001")210 #expect(Self.unverifiable(await prepare(1))?.contains("out of the plausible range") == true)211 setPrice("1e300")212 #expect(Self.unverifiable(await prepare(1)) != nil)213 // no quote at all214 h.clock.advance(WalletService.quoteFreshness + 1)215 h.backend.markets = "[]"216 #expect(Self.unverifiable(await prepare(1))?.contains("No fresh price") == true)217218 // at sign: a review prepared at an honest price is not signed once the source lies low or out of range219 setPrice("1.0")220 let review = try await h.service.prepareEthereumSend(asset: .token(usdc), to: recipient, amount: UInt256(150_000_000))221 setPrice("0.01")222 try await h.service.unlock(password: Harness.password)223 #expect(Self.unverifiable(await walletError { try await h.service.signAndBroadcastEthereum(review) })?.contains("out of the plausible range") == true)224 // at sign: a stale quote is not used (the source is down)225 h.clock.advance(WalletService.quoteFreshness + 1)226 h.backend.priceStatus = 503227 try await h.service.unlock(password: Harness.password)228 #expect(Self.unverifiable(await walletError { try await h.service.signAndBroadcastEthereum(review) })?.contains("No fresh price") == true)229 #expect(h.backend.broadcastEthereum.isEmpty)230 // a 160 USDC review prepared while the source said 0.95 (152 USD at 0.95 is refused; at 0.6 → 0.90 it is 144 USD)231 h.backend.priceStatus = 200232 setPrice("0.6")233 let depeg = try await h.service.prepareEthereumSend(asset: .token(usdc), to: recipient, amount: UInt256(160_000_000))234 setPrice("1.0")235 try await h.service.unlock(password: Harness.password)236 #expect(await walletError { try await h.service.signAndBroadcastEthereum(depeg) } == limit)237 #expect(h.backend.broadcastEthereum.isEmpty)238 _ = try await h.service.signAndBroadcastEthereum(review)239 #expect(h.backend.broadcastEthereum.count == 1)240 }241242 /// Rule (b): a token that is not pegged needs two sources that agree; the higher price is used.243 @Test func aTokenThatIsNotPeggedNeedsTwoAgreeingSources() async throws {244 Self.reset()245 defer { Self.reset() }246 let (h, link) = try await Self.walletHolding("LINK", decimals: 18)247 defer { h.cleanup() }248 let recipient = EthereumWalletTests.recipient249 let limit = WalletError.exceedsUnauditedLimit(limit: "150 USD per token transfer")250 func prepare(_ whole: UInt64, _ millionths: UInt64 = 0) async -> WalletError? {251 await Self.attempt { try await h.service.prepareEthereumSend(asset: .token(link), to: recipient, amount: Self.units(whole, millionths: millionths, decimals: 18)) }252 }253 func set(first: String?, second: String?) {254 h.clock.advance(WalletService.quoteFreshness + 1)255 h.backend.markets = first.map { ServiceTests.market([("chainlink", $0)]) } ?? "[]"256 h.backend.checkPrices = second.map { ["LINKUSD": $0] } ?? [:]257 }258 // both honest at 10 USD: 15 LINK259 set(first: "10", second: "10")260 #expect(await prepare(15) == nil)261 #expect(await prepare(15, 1) == limit)262 // within the tolerance: the HIGHER price decides (150 / 10.4 = 14.42 LINK), whichever source gives it263 set(first: "10", second: "10.4")264 #expect(await prepare(14, 420_000) == nil)265 #expect(await prepare(14, 430_000) == limit)266 set(first: "10.4", second: "10")267 #expect(await prepare(14, 420_000) == nil)268 #expect(await prepare(14, 430_000) == limit)269 // the first source lies low (the attack): refused, even for one base unit270 set(first: "0.000001", second: "10")271 #expect(Self.unverifiable(await prepare(15))?.contains("disagree") == true)272 #expect(Self.unverifiable(await walletError { try await h.service.prepareEthereumSend(asset: .token(link), to: recipient, amount: UInt256(1)) })?.contains("disagree") == true)273 // the second source lies low274 set(first: "10", second: "0.000001")275 #expect(Self.unverifiable(await prepare(15))?.contains("disagree") == true)276 // one source lies high: refused as well (the wallet does not pick a side)277 set(first: "10", second: "20")278 #expect(Self.unverifiable(await prepare(1))?.contains("disagree") == true)279 set(first: "20", second: "10")280 #expect(Self.unverifiable(await prepare(1))?.contains("disagree") == true)281 // both lie low together: nothing in the wallet can tell (residual risk of the finding); recorded, not hidden282 set(first: "0.001", second: "0.001")283 #expect(await prepare(100_000) == nil)284 // the second source does not know the token, is down, or answers something else than one ticker285 set(first: "10", second: nil)286 #expect(Self.unverifiable(await prepare(1))?.contains("Only one price source") == true)287 set(first: "10", second: "10")288 h.backend.checkStatus = 500289 #expect(Self.unverifiable(await prepare(1))?.contains("Only one price source") == true)290 h.backend.checkStatus = 200291 for hostile in ["{\"error\":[],\"result\":{}}", "{\"error\":[],\"result\":{\"A\":{\"a\":[\"10\"],\"b\":[\"10\"],\"c\":[\"10\"]},\"B\":{\"a\":[\"10\"],\"b\":[\"10\"],\"c\":[\"10\"]}}}",292 "{\"error\":[],\"result\":{\"LINKUSD\":{\"a\":[\"1e1\"],\"b\":[\"10\"],\"c\":[\"10\"]}}}", "{\"error\":[],\"result\":{\"LINKUSD\":{\"a\":[10],\"b\":[10],\"c\":[10]}}}",293 "{\"error\":[],\"result\":{\"LINKUSD\":{\"a\":[\"10\"],\"b\":[\"11\"],\"c\":[\"10\"]}}}", "{\"error\":[],\"result\":{\"LINKUSD\":{\"a\":[\"10\"],\"b\":[\"10\"],\"c\":[\"5\"]}}}",294 "{\"error\":[],\"result\":{\"LINKUSD\":{\"a\":[\"-10\"],\"b\":[\"-10\"],\"c\":[\"-10\"]}}}", "[]", "", "{\"error\":[],\"result\":{\"LINKUSD\":{\"a\":[\"" + String(repeating: "9", count: 40) + "\"],\"b\":[\"10\"],\"c\":[\"10\"]}}}"] {295 set(first: "10", second: "10")296 h.backend.checkBody = hostile297 #expect(Self.unverifiable(await prepare(1))?.contains("Only one price source") == true, "\(hostile)")298 }299 h.backend.checkBody = String(repeating: " ", count: 20_000) + FakeBackend.ticker("LINKUSD", "10")300 set(first: "10", second: "10")301 #expect(Self.unverifiable(await prepare(1))?.contains("Only one price source") == true)302 h.backend.checkBody = nil303 // the first source does not know it304 set(first: nil, second: "10")305 #expect(Self.unverifiable(await prepare(1))?.contains("No fresh price") == true)306307 // a stale second quote is not used: read once, then the source goes down and time passes308 set(first: "10", second: "10")309 #expect(await prepare(15) == nil)310 h.clock.advance(WalletService.quoteFreshness + 1)311 h.backend.checkStatus = 503312 #expect(Self.unverifiable(await prepare(15))?.contains("Only one price source") == true)313 h.backend.checkStatus = 200314315 // at sign: prepared while the sources agreed, refused when one of them moved away or disappeared316 set(first: "10", second: "10")317 let review = try await h.service.prepareEthereumSend(asset: .token(link), to: recipient, amount: Self.units(15, decimals: 18))318 set(first: "10", second: "0.01")319 try await h.service.unlock(password: Harness.password)320 #expect(Self.unverifiable(await walletError { try await h.service.signAndBroadcastEthereum(review) })?.contains("disagree") == true)321 set(first: "10", second: nil)322 try await h.service.unlock(password: Harness.password)323 #expect(Self.unverifiable(await walletError { try await h.service.signAndBroadcastEthereum(review) })?.contains("Only one price source") == true)324 // both moved up together: the review is above the ceiling now325 set(first: "20", second: "20")326 try await h.service.unlock(password: Harness.password)327 #expect(await walletError { try await h.service.signAndBroadcastEthereum(review) } == limit)328 #expect(h.backend.broadcastEthereum.isEmpty)329330 // a review object altered after the review (a larger amount in the call data, the description unchanged)331 set(first: "10", second: "10")332 try await h.service.unlock(password: Harness.password)333 var bigger = review.transaction334 bigger.data = ERC20.transfer(to: try #require(EthereumAddress(recipient)), amount: Self.units(15_000, decimals: 18))335 let forged = EthereumSendReview(id: UUID(), network: review.network, createdAt: review.createdAt, from: review.from, asset: review.asset,336 recipient: review.recipient, amount: review.amount, transaction: bigger, call: review.call, feeTier: .normal,337 baseFee: review.baseFee, maximumFee: review.maximumFee, maximumTotalCost: review.maximumTotalCost, isSendMax: false,338 warnings: [])339 #expect(await walletError { try await h.service.signAndBroadcastEthereum(forged) } != nil)340 #expect(h.backend.broadcastEthereum.isEmpty)341 _ = try await h.service.signAndBroadcastEthereum(review)342 #expect(h.backend.broadcastEthereum.count == 1)343 }344345 /// A token the second source does not list cannot be sent by an unaudited build, and a token of the stored profile346 /// never brings its own price identifier.347 @Test func aTokenWithoutSecondSourceOrFromTheProfileIsRefused() async throws {348 Self.reset()349 defer { Self.reset() }350 let (h, maker) = try await Self.walletHolding("MKR", decimals: 18)351 defer { h.cleanup() }352 let recipient = EthereumWalletTests.recipient353 h.backend.markets = ServiceTests.market([("maker", "1000"), ("usd-coin", "1"), ("chainlink", "0.0001")])354 #expect(PriceClient.checkPairs["maker"] == nil)355 #expect(Self.unverifiable(await walletError { try await h.service.prepareEthereumSend(asset: .token(maker), to: recipient, amount: UInt256(1)) })?356 .contains("Only one price source") == true)357358 // the two sources must be two hosts: the same host twice is refused when stored, and counts as one source if359 // a stored profile names it anyway360 var same = FakeBackend.endpoints361 same.priceCheckAPI = "https://PRICES.test/0/public"362 guard case .invalidInput(let why)? = await walletError({ try await h.service.setEndpoints(same) }) else {363 Issue.record("the same host was accepted as second price source")364 return365 }366 #expect(why.contains("another host"))367 #expect(!PriceClient(configuration: same, transport: h.backend).hasCheckSource)368 #expect(try await PriceClient(configuration: same, transport: h.backend).checkPrice(id: "chainlink") == nil)369 // a second source over plain http is refused like any endpoint370 var plain = FakeBackend.endpoints371 plain.priceCheckAPI = "http://check.example.com/0/public"372 guard case .invalidInput? = await walletError({ try await h.service.setEndpoints(plain) }) else {373 Issue.record("a second price source over http was accepted")374 return375 }376377 // a modified profile: a contract of the attacker's choice declared with the price identifier of USDC, or of a378 // token whose two sources agree — neither is a built-in token, so neither has a price for the ceiling379 let other = "0x" + String(repeating: "9a", count: 20)380 var contract = FakeBackend.TokenContract(symbol: "FAKE", name: "Fake", decimals: UInt256(6))381 contract.balances[EthereumWalletTests.owner] = UInt256(1_000_000_000_000)382 h.backend.tokens[other] = contract383 for id in ["usd-coin", "chainlink"] {384 let forged = TokenInfo(network: .mainnet, address: try #require(EthereumAddress(other)), symbol: "FAKE", name: "Fake", decimals: 6, priceID: id, custom: true)385 await h.service.injectCustomTokenForTesting(forged)386 #expect(Self.unverifiable(await walletError { try await h.service.prepareEthereumSend(asset: .token(forged), to: recipient, amount: UInt256(1_000_000)) })?387 .contains("no known price") == true, "\(id)")388 }389 }390391 /// Rule (c): the dollar ceiling of a native coin needs two agreeing sources too, on top of its floor.392 @Test func nativeCoinCeilingsNeedTwoAgreeingSources() async throws {393 Self.reset()394 defer { Self.reset() }395 // POL on Polygon (EVM)396 do {397 let h = try await Self.evmMainnetWallet(.polygon)398 defer { h.cleanup() }399 let coin = EthereumWalletTests.oneEther400 h.backend.balances[EthereumWalletTests.owner] = coin.multipliedReportingOverflow(by: 1_000_000).0401 h.backend.baseFee = UInt256(100_000_000_000)402 h.backend.priorityFee = UInt256(30_000_000_000)403 func prepare(_ coins: UInt64) async -> WalletError? {404 await Self.attempt { try await h.service.prepareEthereumSend(asset: .ether, to: EthereumWalletTests.recipient, amount: coin.multipliedReportingOverflow(by: UInt256(coins)).0) }405 }406 func set(first: String, second: String?) {407 h.clock.advance(WalletService.quoteFreshness + 1)408 h.backend.markets = ServiceTests.market([("polygon-ecosystem-token", first)])409 h.backend.checkPrices = second.map { ["POLUSD": $0] } ?? [:]410 }411 set(first: "1.0", second: "1.0")412 #expect(await prepare(150) == nil)413 #expect(await prepare(151) == .exceedsUnauditedLimit(limit: "150 USD of POL per transaction"))414 // one source lying low, above the floor (0.028): the floor alone would have allowed 5 000 POL415 set(first: "0.03", second: "1.0")416 #expect(Self.unverifiable(await prepare(151))?.contains("disagree") == true)417 set(first: "1.0", second: "0.03")418 #expect(Self.unverifiable(await prepare(151))?.contains("disagree") == true)419 set(first: "1.0", second: nil)420 #expect(Self.unverifiable(await prepare(1))?.contains("Only one price source") == true)421 // within the tolerance, the higher price: 150 / 1.04 = 144.2 POL422 set(first: "1.0", second: "1.04")423 #expect(await prepare(144) == nil)424 #expect(await prepare(145) == .exceedsUnauditedLimit(limit: "150 USD of POL per transaction"))425 // both under the floor together: the floor still refuses426 set(first: "0.02", second: "0.02")427 #expect(Self.unverifiable(await prepare(1))?.contains("not plausible") == true)428 Self.reset()429 }430 // DOGE (UTXO)431 do {432 let h = try await Self.coinMainnetWallet(.dogecoin, .dogecoin)433 defer { h.cleanup() }434 let backend = h.backend435 backend.fundReal(CoinFixture.dogecoin0, 100_000_000_000)436 try await h.service.synchronize(chain: .dogecoin)437 let recipient = CoinFixture.external(.dogecoin)438 func prepare(_ doge: UInt64) async -> WalletError? {439 await Self.attempt { try await h.service.prepareSend(chain: .dogecoin, asset: .native, to: recipient, amount: UInt256(doge * 100_000_000)) }440 }441 func set(first: String, second: String?) {442 h.clock.advance(WalletService.quoteFreshness + 1)443 backend.markets = ServiceTests.market([("dogecoin", first)])444 backend.checkPrices = second.map { ["XDGUSD": $0] } ?? [:]445 }446 set(first: "0.5", second: "0.5")447 #expect(await prepare(300) == nil)448 set(first: "0.03", second: "0.5")449 #expect(Self.unverifiable(await prepare(301))?.contains("disagree") == true)450 set(first: "0.5", second: nil)451 #expect(Self.unverifiable(await prepare(1))?.contains("Only one price source") == true)452 Self.reset()453 }454 }455456 /// Rules (a) and (c) on Solana and TRON: native coin with two sources, built-in stablecoins with the peg rule,457 /// when preparing and when signing.458 @Test func solanaAndTronCeilingsFollowTheSameRules() async throws {459 Self.reset()460 defer { Self.reset() }461 do {462 let h = try await Self.mainnetMultiWallet(chains: [.solana], prices: [("solana", "100"), ("usd-coin", "1")])463 defer { h.cleanup() }464 let node = h.backend.solana465 let me = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))466 let recipient = solanaStranger()467 node.lamports[me.base58] = 100_000 * MultiChainSendTests.sol468 node.lamports[recipient.base58] = MultiChainSendTests.sol469 func set(sol: String, second: String?, usdc: String = "1") {470 h.clock.advance(WalletService.quoteFreshness + 1)471 h.backend.base.markets = ServiceTests.market([("solana", sol), ("usd-coin", usdc)])472 h.backend.base.checkPrices = second.map { ["SOLUSD": $0] } ?? [:]473 }474 func send(_ lamports: UInt64) async -> WalletError? {475 await Self.attempt { try await h.service.prepareSend(chain: .solana, asset: .native, to: recipient.base58, amount: UInt256(lamports)) }476 }477 set(sol: "100", second: "100")478 let review = try await h.service.prepareSend(chain: .solana, asset: .native, to: recipient.base58, amount: UInt256(1_500_000_000))479 // lying low above the floor (5 USD): the floor alone would have allowed 30 SOL480 set(sol: "6", second: "100")481 #expect(Self.unverifiable(await send(20_000_000_000))?.contains("disagree") == true)482 set(sol: "100", second: nil)483 #expect(Self.unverifiable(await send(1_000))?.contains("Only one price source") == true)484 // at sign485 node.lastValidBlockHeight = 9_000486 set(sol: "100", second: "6")487 try await h.service.unlock(password: Harness.password)488 #expect(Self.unverifiable(await walletError { try await h.service.signAndBroadcast(review) })?.contains("disagree") == true)489 #expect(node.sent.isEmpty)490491 // USDC (SPL), pegged: a quote lying low is ignored below 0.90 and refused below 0.50492 let usdc = try #require(await h.service.knownSolanaTokens(.mainnetBeta).first { $0.symbol == "USDC" })493 let mint = try #require(SolanaPublicKey(base58: usdc.address))494 node.mints[usdc.address] = .init(decimals: 6)495 node.tokenAccounts = [.init(address: try SolanaAddress.associatedTokenAccount(owner: me, mint: mint, tokenProgram: .token).base58, mint: usdc.address,496 owner: me.base58, amount: 900_000_000_000)]497 func sendUSDC(_ amount: UInt64) async -> WalletError? {498 await Self.attempt { try await h.service.prepareSend(chain: .solana, asset: .token(usdc), to: recipient.base58, amount: UInt256(amount)) }499 }500 set(sol: "100", second: "100", usdc: "0.6")501 #expect(await sendUSDC(166_666_666) == nil)502 #expect(await sendUSDC(166_666_667) == .exceedsUnauditedLimit(limit: "150 USD per token transfer"))503 set(sol: "100", second: "100", usdc: "0.000001")504 #expect(Self.unverifiable(await sendUSDC(1_000_000))?.contains("out of the plausible range") == true)505 Self.reset()506 }507 do {508 let h = try await Self.mainnetMultiWallet(chains: [.tron], prices: [("tron", "0.25"), ("tether", "1")])509 defer { h.cleanup() }510 let node = h.backend.tron511 let me = try #require(TronAddress(MultiHarness.tronAddress))512 let recipient = tronStranger()513 node.balances[me.hex] = 10_000_000 * MultiChainSendTests.trx514 node.balances[recipient.hex] = 1515 func set(trx: String, second: String?, usdt: String = "1") {516 h.clock.advance(WalletService.quoteFreshness + 1)517 h.backend.base.markets = ServiceTests.market([("tron", trx), ("tether", usdt)])518 h.backend.base.checkPrices = second.map { ["TRXUSD": $0] } ?? [:]519 node.headTimestamp = UInt64(h.clock.now.timeIntervalSince1970 * 1000)520 }521 func send(_ sun: UInt64) async -> WalletError? {522 await Self.attempt { try await h.service.prepareSend(chain: .tron, asset: .native, to: recipient.base58, amount: UInt256(sun)) }523 }524 set(trx: "0.25", second: "0.25")525 #expect(await send(600_000_000) == nil)526 // lying low above the floor (0.022): the floor alone would have allowed 6 000 TRX527 set(trx: "0.025", second: "0.25")528 #expect(Self.unverifiable(await send(6_000_000_000))?.contains("disagree") == true)529 set(trx: "0.25", second: nil)530 #expect(Self.unverifiable(await send(1_000_000))?.contains("Only one price source") == true)531532 // USDT (TRC-20), pegged533 let usdt = try #require(await h.service.knownTronTokens(.mainnet).first { $0.symbol == "USDT" })534 let contract = try #require(TronAddress(usdt.address))535 node.tokens[contract.hex] = .init(decimals: 6, symbol: "USDT", name: "Tether USD", balances: [Hex.encode(me.hash): UInt256(900_000_000_000)])536 func sendUSDT(_ amount: UInt64) async -> WalletError? {537 await Self.attempt { try await h.service.prepareSend(chain: .tron, asset: .token(usdt), to: recipient.base58, amount: UInt256(amount)) }538 }539 set(trx: "0.25", second: "0.25", usdt: "0.6")540 #expect(await sendUSDT(166_666_666) == nil)541 #expect(await sendUSDT(166_666_667) == .exceedsUnauditedLimit(limit: "150 USD per token transfer"))542 set(trx: "0.25", second: "0.25", usdt: "0.000001")543 #expect(Self.unverifiable(await sendUSDT(1_000_000))?.contains("out of the plausible range") == true)544 Self.reset()545 }546 }547}548