diff --git a/Sources/KukaiCoreSwift/Services/WalletCacheService.swift b/Sources/KukaiCoreSwift/Services/WalletCacheService.swift index 466407e..97c6749 100644 --- a/Sources/KukaiCoreSwift/Services/WalletCacheService.swift +++ b/Sources/KukaiCoreSwift/Services/WalletCacheService.swift @@ -135,8 +135,17 @@ public class WalletCacheService { if encryptAndWriteWalletsToDisk(wallets: newWallets) && encryptAndWriteMetadataToDisk(newMetadata) == false { throw WalletCacheError.unableToEncryptAndWrite + } else { + removeNewAddressFromWatchListIfExists(wallet.address, list: newMetadata) } } + + private func removeNewAddressFromWatchListIfExists(_ address: String, list: WalletMetadataList) { + if let _ = list.watchWallets.first(where: { $0.address == address }) { + let _ = deleteWatchWallet(address: address) + } + } + /** Cahce a watch wallet metadata obj, only. Metadata cahcing handled via wallet cache method */ diff --git a/Tests/KukaiCoreSwiftTests/Services/WalletCacheServiceTests.swift b/Tests/KukaiCoreSwiftTests/Services/WalletCacheServiceTests.swift index c295fa4..6b211d9 100644 --- a/Tests/KukaiCoreSwiftTests/Services/WalletCacheServiceTests.swift +++ b/Tests/KukaiCoreSwiftTests/Services/WalletCacheServiceTests.swift @@ -338,7 +338,7 @@ class WalletCacheServiceTests: XCTestCase { do { try walletCacheService.cacheWatchWallet(metadata: watchWallet) - let list = walletCacheService.readMetadataFromDiskAndDecrypt() + let list = walletCacheService.readMetadataFromDiskAndDecrypt() let watch = list.watchWallets XCTAssert(watch.count == 1, watch.count.description) } catch { @@ -364,4 +364,31 @@ class WalletCacheServiceTests: XCTestCase { XCTAssert(error.localizedDescription == "The operation couldn’t be completed. (KukaiCoreSwift.WalletCacheError error 8.)", error.localizedDescription) } } + + func testWatchWalletRemovedAfterImported() { + XCTAssert(walletCacheService.deleteAllCacheAndKeys()) + + // Add watch and confirm + let watchWallet = WalletMetadata(address: MockConstants.defaultLinearWallet.address, hdWalletGroupName: nil, mainnetDomains: [], ghostnetDomains: [], type: .hd, children: [], isChild: false, isWatchOnly: true, bas58EncodedPublicKey: "", backedUp: true) + + do { + try walletCacheService.cacheWatchWallet(metadata: watchWallet) + let list = walletCacheService.readMetadataFromDiskAndDecrypt() + let watch = list.watchWallets + XCTAssert(watch.count == 1, watch.count.description) + } catch let error { + XCTFail("Should not error: \(error)") + } + + + // Add the wallet via an import, test watch is now been removed + do { + try walletCacheService.cache(wallet: MockConstants.defaultLinearWallet, childOfIndex: nil, backedUp: false) + let list = walletCacheService.readMetadataFromDiskAndDecrypt() + let watch = list.watchWallets + XCTAssert(watch.count == 0, watch.count.description) + } catch { + XCTFail("Should not error: \(error)") + } + } }