Repository Public
1// SP Wallet iOS2// File: Tests/WalletBaseTests.swift3// Description: Unit tests of the wallet base: grouping and totals never invent a value, the history filter, the offline cache,4// deep links that can only navigate, scanned codes that can only fill a form.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Testing10import SPWalletCore11@testable import SPWallet1213private func decode<T: Decodable>(_ json: String, as: T.Type = T.self) throws -> T { try APICoding.decoder().decode(T.self, from: Data(json.utf8)) }1415private let portfolioJSON = #"""16{"asOf":"2026-11-18T12:00:00.000Z","priceSource":"coingecko","pricesAsOf":"2026-11-18T11:58:00.000Z","pricesStale":false,"halted":false,17 "signer":{"reachable":true,"addressesAsOf":"2026-11-18T12:00:00.000Z"},"pending":[],18 "prices":{"ETH":{"priceAt":"2026-11-18T11:58:00.000Z","stale":false,"usd":2000,"cad":2800,"change24h":-2,"spark":[]},19 "USDC":{"priceAt":"2026-11-18T11:58:00.000Z","stale":false,"usd":1,"cad":1.4,"change24h":0,"spark":[]}},20 "balances":[21 {"network":"base","networkName":"Base","asset":"native","symbol":"ETH","name":"Ether","decimals":18,"amount":"500000000000000000","display":"0.5","error":null},22 {"network":"ethereum","networkName":"Ethereum","asset":"native","symbol":"ETH","name":"Ether","decimals":18,"amount":"250000000000000000","display":"0.25","error":null},23 {"network":"base","networkName":"Base","asset":"0xusdc","symbol":"USDC","name":"USD Coin","decimals":6,"amount":"10000000","display":"10","error":null},24 {"network":"hyperevm","networkName":"HyperEVM","asset":"native","symbol":"HYPE","name":"Hyperliquid","decimals":18,"amount":null,"display":null,"error":"unavailable"},25 {"network":"bitcoin","networkName":"Bitcoin","asset":"native","symbol":"BTC","name":"Bitcoin","decimals":8,"amount":"0","display":"0","error":null}]}26"""#2728@Suite struct HoldingTests {29 @Test func groupingSumsExactAmountsAndKeepsUnreadableBalancesUnreadable() throws {30 let p: Portfolio = try decode(portfolioJSON)31 let h = Holding.group(p, currency: .cad)32 let eth = try #require(h.first { $0.symbol == "ETH" })33 #expect(eth.totalDisplay == "0.75" && eth.balances.count == 2 && eth.isHeld)34 #expect(abs((eth.value ?? 0) - 2100) < 0.0001)35 let hype = try #require(h.first { $0.symbol == "HYPE" })36 #expect(hype.hasUnavailable && hype.value == nil && !hype.isHeld, "an unreadable balance is neither zero nor held")37 #expect(h.first { $0.symbol == "BTC" }?.isHeld == false)38 #expect(h.first?.symbol == "ETH", "sorted by estimated value")39 }40 @Test func theTotalSaysWhenItIsIncomplete() throws {41 let p: Portfolio = try decode(portfolioJSON)42 let t = p.estimatedTotal(in: .cad)43 #expect(abs(t.value - 2114) < 0.0001)44 #expect(t.complete == false, "one balance could not be read: the total is a lower bound")45 }46 @Test func allocationNamesEveryPartAndSumsToOne() throws {47 let p: Portfolio = try decode(portfolioJSON)48 let a = allocation(p, currency: .usd)49 #expect(a.map(\.id) == ["ETH", "USDC"])50 #expect(abs(a.reduce(0) { $0 + $1.share } - 1) < 1e-9)51 }52}5354@Suite struct ActivityFilterTests {55 let items: [ActivityItem] = try! decode(#"""56 [{"id":"a","kind":"send","at":"2026-11-18T10:00:00.000Z","network":"base","symbol":"ETH","amount":"1","amountDisplay":"0.001","to":"0xAbC0000000000000000000000000000000000001","state":"finalized"},57 {"id":"b","kind":"send","at":"2026-11-18T09:00:00.000Z","network":"base","symbol":"ETH","amount":"1","state":"broadcast","txid":"0xdeadbeef"},58 {"id":"c","kind":"receive","at":"2026-11-18T08:00:00.000Z","network":"solana","symbol":"SOL","amount":"1","state":"confirming"},59 {"id":"d","kind":"swap","at":"2026-11-18T07:00:00.000Z","network":"ethereum","symbol":"USDC","amount":"1","state":"failed"},60 {"id":"e","kind":"send","at":"2026-11-18T06:00:00.000Z","network":"base","symbol":"ETH","amount":"1","state":"some_future_state"}]61 """#)62 @Test func statusBucketsNeverCountAnUnconfirmedTransactionAsSettled() {63 var f = ActivityFilter(); f.status = .settled64 #expect(items.filter { f.matches($0, query: "") }.map(\.id) == ["a"])65 f.status = .inProgress66 #expect(items.filter { f.matches($0, query: "") }.map(\.id) == ["b", "c", "e"], "broadcast, confirming and unknown states are not settled")67 f.status = .failed68 #expect(items.filter { f.matches($0, query: "") }.map(\.id) == ["d"])69 }70 @Test func searchAndKindAndNetwork() {71 var f = ActivityFilter()72 #expect(items.filter { f.matches($0, query: "DEADBEEF") }.map(\.id) == ["b"])73 #expect(items.filter { f.matches($0, query: "0xabc") }.map(\.id) == ["a"])74 f.kind = "receive"; #expect(items.filter { f.matches($0, query: "") }.map(\.id) == ["c"])75 f.kind = nil; f.network = "ethereum"; #expect(items.filter { f.matches($0, query: "") }.map(\.id) == ["d"])76 }77 @Test func anUnknownStateIsShownVerbatim() {78 let (label, tone, _) = activityStateLabel(items[4])79 #expect(label == "some_future_state" && tone == .neutral)80 #expect(items[1].isSettled == false && items[0].isSettled)81 }82}8384@Suite struct AppCacheTests {85 @Test func roundTripKeepsTheSaveDateAndRemoveAllErasesEverything() async throws {86 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spw-cache-\(UUID().uuidString)")87 let cache = AppCache(directory: dir)88 let at = Date(timeIntervalSince1970: 1_795_000_000)89 await cache.save(["a": 1], key: "k/../weird key", at: at)90 let again = AppCache(directory: dir) // a new launch reads from disk91 let c = try #require(await again.load([String: Int].self, key: "k/../weird key"))92 #expect(c.value == ["a": 1] && abs(c.savedAt.timeIntervalSince(at)) < 0.01)93 #expect(try FileManager.default.contentsOfDirectory(atPath: dir.path).allSatisfy { !$0.contains("/") && !$0.contains("..") || $0.hasSuffix(".json") })94 await again.removeAll()95 #expect(await again.isEmpty)96 #expect(await AppCache(directory: dir).load([String: Int].self, key: "k/../weird key") == nil)97 }98 @Test func aDamagedSnapshotIsForgottenNotShown() async throws {99 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spw-cache-\(UUID().uuidString)")100 let cache = AppCache(directory: dir)101 await cache.save(["a": 1], key: "x")102 try Data("{ not json".utf8).write(to: dir.appendingPathComponent("x.json"))103 #expect(await AppCache(directory: dir).load([String: Int].self, key: "x") == nil)104 #expect(!FileManager.default.fileExists(atPath: dir.appendingPathComponent("x.json").path))105 }106}107108@MainActor @Suite struct RouterTests {109 @Test func deepLinksOnlyNavigate() {110 let r = Router()111 r.open(URL(string: "spwallet://activity")!); #expect(r.section == .activity)112 r.open(URL(string: "spwallet://asset/USDC")!); #expect(r.section == .portfolio && r.pendingAsset == "USDC")113 r.pendingAsset = nil114 r.open(URL(string: "spwallet://asset/..%2F..%2Fx")!); #expect(r.pendingAsset == nil, "a malformed symbol is ignored")115 r.section = .home116 r.open(URL(string: "https://wallet.spboucher.ai/activity")!); #expect(r.section == .home, "other schemes are ignored")117 r.open(URL(string: "spwallet://send?to=0xabc&amount=1")!)118 #expect(r.section == .home && r.sheet == nil, "no link can open or prefill a send")119 }120}121122@Suite struct ScannedCodeTests {123 let networks: [Network] = try! decode(#"""124 [{"id":"base","name":"Base","family":"evm","chainRef":"8453","native":{"id":"native","symbol":"ETH","name":"Ether","decimals":18},"tokens":[],"explorerAddr":"https://basescan.org/address/","minConf":12},125 {"id":"bitcoin","name":"Bitcoin","family":"btc","chainRef":"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f","native":{"id":"native","symbol":"BTC","name":"Bitcoin","decimals":8},"tokens":[],"explorerAddr":"https://mempool.space/address/","minConf":3},126 {"id":"solana","name":"Solana","family":"sol","chainRef":"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d","native":{"id":"native","symbol":"SOL","name":"Solana","decimals":9},"tokens":[],"explorerAddr":"https://solscan.io/account/","minConf":32}]127 """#)128 private func fields(_ raw: String, current: String? = nil) -> ScannedFields? { if case .success(let f) = ScannedPayment.parse(raw, networks: networks, current: current) { f } else { nil } }129 private func refused(_ raw: String, current: String? = nil) -> Bool { if case .failure = ScannedPayment.parse(raw, networks: networks, current: current) { true } else { false } }130131 @Test func aPlainAddressOrAStandardURIFillsTheForm() {132 #expect(fields("0x52908400098527886E0F7030069857D2E4169EE7", current: "base")?.address == "0x52908400098527886E0F7030069857D2E4169EE7")133 let btc = fields("bitcoin:bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq?amount=0.001")134 #expect(btc?.network == "bitcoin" && btc?.amount == "0.001")135 let eth = fields("ethereum:0x52908400098527886E0F7030069857D2E4169EE7@8453?value=1000000000000000")136 #expect(eth?.network == "base" && eth?.amount == "0.001")137 }138 @Test func linksTransactionRequestsAndWrongNetworksAreRefused() {139 #expect(refused("https://example.com/pay?to=0x52908400098527886E0F7030069857D2E4169EE7"))140 #expect(refused("javascript:alert(1)"))141 #expect(refused("solana:https://example.com/tx"), "a Solana Pay transaction request is never fetched")142 #expect(refused("bitcoin:bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", current: "base") || fields("bitcoin:bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", current: "base")?.network == "bitcoin",143 "a code for another network never fills the current network's form silently")144 #expect(refused("bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", current: "base"), "a Bitcoin address is not a Base address")145 #expect(refused(String(repeating: "a", count: 3000)))146 }147 @Test func theFirstLineCheckNeverSaysValidForAnotherNetworksAddress() {148 let base = networks[0]149 #expect(AddressChecks.check("0x52908400098527886E0F7030069857D2E4169EE7", network: base, own: nil) == .valid)150 if case .invalid = AddressChecks.check("0x5AAeb6053F3E94C9b9A09f33669435E7Ef1BeAeD", network: base, own: nil) {} else { Issue.record("a wrong checksum must be invalid") }151 if case .invalid = AddressChecks.check("0x52908400098527886E0F7030069857D2E4169EE7", network: base, own: "0x52908400098527886E0F7030069857D2E4169EE7") {} else { Issue.record("own address must be refused") }152 if case .invalid = AddressChecks.check("bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", network: base, own: nil) {} else { Issue.record("a Bitcoin address on Base must be invalid") }153 }154}155156@Suite struct WidgetPrivacyTests {157 @Test func aSnapshotWithoutPermissionCarriesNoFigure() throws {158 let s = WidgetSnapshot(savedAt: Date(), signedIn: true, amountsAllowed: false, total: nil, totalComplete: true, change24h: 1, pricesStale: false,159 assets: [.init(symbol: "ETH", name: "Ether", value: nil, share: 1, change24h: 1)],160 transactions: [.init(id: "1", kind: "send", symbol: "ETH", amount: nil, state: "finalized", settled: true, at: Date())],161 unreadAlerts: nil, criticalAlert: nil, halted: false)162 let enc = JSONEncoder(); enc.dateEncodingStrategy = .secondsSince1970163 let text = String(decoding: try enc.encode(s), as: UTF8.self)164 #expect(!text.contains("$") && !text.contains("\"total\":\"") && !text.contains("\"amount\":\""))165 }166}167