diff --git a/DashWallet.xcodeproj/project.pbxproj b/DashWallet.xcodeproj/project.pbxproj index 2e0050376e..5a683edb13 100644 --- a/DashWallet.xcodeproj/project.pbxproj +++ b/DashWallet.xcodeproj/project.pbxproj @@ -871,6 +871,13 @@ 75A0A3F42CA7DBCF003ED48B /* TimeUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75A0A3F22CA7DBCF003ED48B /* TimeUtils.swift */; }; 75A2F3032DE48C860046BE17 /* CTXSpendTokenService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75A2F3022DE48C860046BE17 /* CTXSpendTokenService.swift */; }; 75A2F3042DE48C860046BE17 /* CTXSpendTokenService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75A2F3022DE48C860046BE17 /* CTXSpendTokenService.swift */; }; + A3000001000000000000AA01 /* VoteLimit.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3000002000000000000AA02 /* VoteLimit.swift */; }; + A5000001000000000000BB01 /* VotingStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5000002000000000000BB02 /* VotingStore.swift */; }; + A6010000000000000000CD01 /* RequestDetailsViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6010000000000000000CC01 /* RequestDetailsViewModel.swift */; }; + A6020000000000000000CD02 /* RequestDetailField.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6020000000000000000CC02 /* RequestDetailField.swift */; }; + A6030000000000000000CD03 /* RequestDetailsScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6030000000000000000CC03 /* RequestDetailsScreen.swift */; }; + A5000009000000000000BB09 /* VoteErrorMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5000008000000000000BB08 /* VoteErrorMessage.swift */; }; + A5000005000000000000BB05 /* VotingListViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5000006000000000000BB06 /* VotingListViewModel.swift */; }; 75A8C1692AE6A1AC0042256E /* VotingViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75A8C1682AE6A1AC0042256E /* VotingViewModel.swift */; }; 75AA33CC2BF9C82700F12465 /* ModalDialog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75AA33CB2BF9C82700F12465 /* ModalDialog.swift */; }; 75AA33CD2BF9C82700F12465 /* ModalDialog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75AA33CB2BF9C82700F12465 /* ModalDialog.swift */; }; @@ -2016,6 +2023,13 @@ D8808925848EFF2234755A55 /* VoteFlow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C53D16CE65DEA6123200EB2 /* VoteFlow.swift */; }; F34816414D829A45E0762757 /* ContestDetailScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BA141C505AF0AE495DCAA37 /* ContestDetailScreen.swift */; }; AD24D88215A4E51186112B34 /* CastVoteSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF2C19E8480582798A0155E4 /* CastVoteSheet.swift */; }; + A3000003000000000000AA03 /* VoteLimit.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3000002000000000000AA02 /* VoteLimit.swift */; }; + A5000003000000000000BB03 /* VotingStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5000002000000000000BB02 /* VotingStore.swift */; }; + A6010000000000000000CE01 /* RequestDetailsViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6010000000000000000CC01 /* RequestDetailsViewModel.swift */; }; + A6020000000000000000CE02 /* RequestDetailField.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6020000000000000000CC02 /* RequestDetailField.swift */; }; + A6030000000000000000CE03 /* RequestDetailsScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6030000000000000000CC03 /* RequestDetailsScreen.swift */; }; + A500000A000000000000BB0A /* VoteErrorMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5000008000000000000BB08 /* VoteErrorMessage.swift */; }; + A5000007000000000000BB07 /* VotingListViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5000006000000000000BB06 /* VotingListViewModel.swift */; }; 6181C570B638E07D8B369CDB /* VotingViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75A8C1682AE6A1AC0042256E /* VotingViewModel.swift */; }; E503EDEA94E656CAE70E5A11 /* UsernameRequestStatusScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED4CB35186918CCBD2FFC49F /* UsernameRequestStatusScreen.swift */; }; D19A81C4F6103AC513D737AA /* UsernameRequestStatusScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED4CB35186918CCBD2FFC49F /* UsernameRequestStatusScreen.swift */; }; @@ -2037,7 +2051,12 @@ 149D439536B3216FDAEEB975 /* VotingListSectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4C123B1612DD272D1371C17 /* VotingListSectionTests.swift */; }; C0F7A1D2E3B4C5D6E7F80901 /* CountedPhrasePluralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0F7A1D2E3B4C5D6E7F80902 /* CountedPhrasePluralTests.swift */; }; 9D097D529CF2AF9A63A649DE /* VotingFilterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2ED90B9CB9B2FB3E1259FEA6 /* VotingFilterTests.swift */; }; - B17E5A0C9D3F4E21A6C80B01 /* VoteHistoryPersistenceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B17E5A0C9D3F4E21A6C80B02 /* VoteHistoryPersistenceTests.swift */; }; + 1B3E5A7C9D2F4A6B8C0D1E01 /* VoteLimitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B3E5A7C9D2F4A6B8C0D1E02 /* VoteLimitTests.swift */; }; + 1B3E5A7C9D2F4A6B8C0D1E21 /* VotingListViewModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B3E5A7C9D2F4A6B8C0D1E22 /* VotingListViewModelTests.swift */; }; + 1B3E5A7C9D2F4A6B8C0D1E31 /* RequestDetailsViewModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B3E5A7C9D2F4A6B8C0D1E32 /* RequestDetailsViewModelTests.swift */; }; + 1B3E5A7C9D2F4A6B8C0D1E11 /* VotingStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B3E5A7C9D2F4A6B8C0D1E12 /* VotingStoreTests.swift */; }; + 1B3E5A7C9D2F4A6B8C0D2E03 /* VoteHistoryDAOTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B3E5A7C9D2F4A6B8C0D2E04 /* VoteHistoryDAOTests.swift */; }; + 1B3E5A7C9D2F4A6B8C0D2E01 /* MasternodeVoteCasterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B3E5A7C9D2F4A6B8C0D2E02 /* MasternodeVoteCasterTests.swift */; }; BABA10000000000000000004 /* IdentityBalanceRefreshTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BABA10000000000000000003 /* IdentityBalanceRefreshTests.swift */; }; BABA10000000000000000006 /* DashPayUserLinkTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BABA10000000000000000005 /* DashPayUserLinkTests.swift */; }; BABA10000000000000000008 /* DiagnosticLogExporterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BABA10000000000000000007 /* DiagnosticLogExporterTests.swift */; }; @@ -3083,6 +3102,18 @@ 759AFDE22CC67E89007072D2 /* VotingInfoScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VotingInfoScreen.swift; sourceTree = ""; }; 75A0A3F22CA7DBCF003ED48B /* TimeUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TimeUtils.swift; sourceTree = ""; }; 75A2F3022DE48C860046BE17 /* CTXSpendTokenService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashSpend/CTX/CTXSpendTokenService.swift; sourceTree = ""; }; + A3000002000000000000AA02 /* VoteLimit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoteLimit.swift; sourceTree = ""; }; + A5000002000000000000BB02 /* VotingStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VotingStore.swift; sourceTree = ""; }; + A5000008000000000000BB08 /* VoteErrorMessage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoteErrorMessage.swift; sourceTree = ""; }; + A5000006000000000000BB06 /* VotingListViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VotingListViewModel.swift; sourceTree = ""; }; + A6010000000000000000CC01 /* RequestDetailsViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestDetailsViewModel.swift; sourceTree = ""; }; + A6020000000000000000CC02 /* RequestDetailField.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestDetailField.swift; sourceTree = ""; }; + A6030000000000000000CC03 /* RequestDetailsScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestDetailsScreen.swift; sourceTree = ""; }; + A3000004000000000000AA04 /* Store */ = {isa = PBXGroup; children = ( + A3000002000000000000AA02 /* VoteLimit.swift */, + A5000002000000000000BB02 /* VotingStore.swift */, + A5000008000000000000BB08 /* VoteErrorMessage.swift */, + ); path = Store; sourceTree = ""; }; 75A8C1682AE6A1AC0042256E /* VotingViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VotingViewModel.swift; sourceTree = ""; }; 75AA33CB2BF9C82700F12465 /* ModalDialog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModalDialog.swift; sourceTree = ""; }; 75AA33CE2BF9D44A00F12465 /* ButtonsGroup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ButtonsGroup.swift; sourceTree = ""; }; @@ -3889,7 +3920,12 @@ A4C123B1612DD272D1371C17 /* VotingListSectionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VotingListSectionTests.swift; sourceTree = ""; }; C0F7A1D2E3B4C5D6E7F80902 /* CountedPhrasePluralTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CountedPhrasePluralTests.swift; sourceTree = ""; }; 2ED90B9CB9B2FB3E1259FEA6 /* VotingFilterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VotingFilterTests.swift; sourceTree = ""; }; - B17E5A0C9D3F4E21A6C80B02 /* VoteHistoryPersistenceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoteHistoryPersistenceTests.swift; sourceTree = ""; }; + 1B3E5A7C9D2F4A6B8C0D1E02 /* VoteLimitTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoteLimitTests.swift; sourceTree = ""; }; + 1B3E5A7C9D2F4A6B8C0D1E22 /* VotingListViewModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VotingListViewModelTests.swift; sourceTree = ""; }; + 1B3E5A7C9D2F4A6B8C0D1E32 /* RequestDetailsViewModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestDetailsViewModelTests.swift; sourceTree = ""; }; + 1B3E5A7C9D2F4A6B8C0D1E12 /* VotingStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VotingStoreTests.swift; sourceTree = ""; }; + 1B3E5A7C9D2F4A6B8C0D2E04 /* VoteHistoryDAOTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoteHistoryDAOTests.swift; sourceTree = ""; }; + 1B3E5A7C9D2F4A6B8C0D2E02 /* MasternodeVoteCasterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MasternodeVoteCasterTests.swift; sourceTree = ""; }; BABA10000000000000000003 /* IdentityBalanceRefreshTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IdentityBalanceRefreshTests.swift; sourceTree = ""; }; BABA10000000000000000005 /* DashPayUserLinkTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashPayUserLinkTests.swift; sourceTree = ""; }; BABA10000000000000000007 /* DiagnosticLogExporterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiagnosticLogExporterTests.swift; sourceTree = ""; }; @@ -6948,6 +6984,24 @@ path = Landing; sourceTree = ""; }; + A6000000000000000000CF00 /* Details */ = { + isa = PBXGroup; + children = ( + A6010000000000000000CC01 /* RequestDetailsViewModel.swift */, + A6020000000000000000CC02 /* RequestDetailField.swift */, + A6030000000000000000CC03 /* RequestDetailsScreen.swift */, + ); + path = Details; + sourceTree = ""; + }; + A5000004000000000000BB04 /* List */ = { + isa = PBXGroup; + children = ( + A5000006000000000000BB06 /* VotingListViewModel.swift */, + ); + path = List; + sourceTree = ""; + }; 7502A4852AE401DA00ACDDD3 /* Voting */ = { isa = PBXGroup; children = ( @@ -6963,6 +7017,9 @@ 6BA141C505AF0AE495DCAA37 /* ContestDetailScreen.swift */, FF2C19E8480582798A0155E4 /* CastVoteSheet.swift */, 754495DB2AE91AF700492817 /* Cells */, + A5000004000000000000BB04 /* List */, + A3000004000000000000AA04 /* Store */, + A6000000000000000000CF00 /* Details */, 75A8C1682AE6A1AC0042256E /* VotingViewModel.swift */, ); path = Voting; @@ -7306,7 +7363,12 @@ A4C123B1612DD272D1371C17 /* VotingListSectionTests.swift */, C0F7A1D2E3B4C5D6E7F80902 /* CountedPhrasePluralTests.swift */, 2ED90B9CB9B2FB3E1259FEA6 /* VotingFilterTests.swift */, - B17E5A0C9D3F4E21A6C80B02 /* VoteHistoryPersistenceTests.swift */, + 1B3E5A7C9D2F4A6B8C0D1E02 /* VoteLimitTests.swift */, + 1B3E5A7C9D2F4A6B8C0D1E22 /* VotingListViewModelTests.swift */, + 1B3E5A7C9D2F4A6B8C0D1E32 /* RequestDetailsViewModelTests.swift */, + 1B3E5A7C9D2F4A6B8C0D1E12 /* VotingStoreTests.swift */, + 1B3E5A7C9D2F4A6B8C0D2E04 /* VoteHistoryDAOTests.swift */, + 1B3E5A7C9D2F4A6B8C0D2E02 /* MasternodeVoteCasterTests.swift */, BABA10000000000000000003 /* IdentityBalanceRefreshTests.swift */, BABA10000000000000000005 /* DashPayUserLinkTests.swift */, BABA10000000000000000007 /* DiagnosticLogExporterTests.swift */, @@ -9801,6 +9863,13 @@ C23DCB2DF08950815BCDAE16 /* VotingKeyInputScreen.swift in Sources */, A15BD917294003C8A262FEC6 /* VotingKeysScreen.swift in Sources */, D19A81C4F6103AC513D737AA /* UsernameRequestStatusScreen.swift in Sources */, + A3000003000000000000AA03 /* VoteLimit.swift in Sources */, + A5000003000000000000BB03 /* VotingStore.swift in Sources */, + A6010000000000000000CE01 /* RequestDetailsViewModel.swift in Sources */, + A6020000000000000000CE02 /* RequestDetailField.swift in Sources */, + A6030000000000000000CE03 /* RequestDetailsScreen.swift in Sources */, + A500000A000000000000BB0A /* VoteErrorMessage.swift in Sources */, + A5000007000000000000BB07 /* VotingListViewModel.swift in Sources */, 6181C570B638E07D8B369CDB /* VotingViewModel.swift in Sources */, AD24D88215A4E51186112B34 /* CastVoteSheet.swift in Sources */, F34816414D829A45E0762757 /* ContestDetailScreen.swift in Sources */, @@ -10642,7 +10711,12 @@ 149D439536B3216FDAEEB975 /* VotingListSectionTests.swift in Sources */, C0F7A1D2E3B4C5D6E7F80901 /* CountedPhrasePluralTests.swift in Sources */, 9D097D529CF2AF9A63A649DE /* VotingFilterTests.swift in Sources */, - B17E5A0C9D3F4E21A6C80B01 /* VoteHistoryPersistenceTests.swift in Sources */, + 1B3E5A7C9D2F4A6B8C0D1E01 /* VoteLimitTests.swift in Sources */, + 1B3E5A7C9D2F4A6B8C0D1E21 /* VotingListViewModelTests.swift in Sources */, + 1B3E5A7C9D2F4A6B8C0D1E31 /* RequestDetailsViewModelTests.swift in Sources */, + 1B3E5A7C9D2F4A6B8C0D1E11 /* VotingStoreTests.swift in Sources */, + 1B3E5A7C9D2F4A6B8C0D2E03 /* VoteHistoryDAOTests.swift in Sources */, + 1B3E5A7C9D2F4A6B8C0D2E01 /* MasternodeVoteCasterTests.swift in Sources */, BABA10000000000000000004 /* IdentityBalanceRefreshTests.swift in Sources */, BABA10000000000000000006 /* DashPayUserLinkTests.swift in Sources */, BABA10000000000000000008 /* DiagnosticLogExporterTests.swift in Sources */, @@ -11511,6 +11585,13 @@ 754565D12DABA5F300DA4E8E /* MerchantTypesDialog.swift in Sources */, C9D2C8F22A320AA000D15901 /* BaseViewController+NetworkReachability.swift in Sources */, C9D2C8F32A320AA000D15901 /* main.m in Sources */, + A3000001000000000000AA01 /* VoteLimit.swift in Sources */, + A5000001000000000000BB01 /* VotingStore.swift in Sources */, + A6010000000000000000CD01 /* RequestDetailsViewModel.swift in Sources */, + A6020000000000000000CD02 /* RequestDetailField.swift in Sources */, + A6030000000000000000CD03 /* RequestDetailsScreen.swift in Sources */, + A5000009000000000000BB09 /* VoteErrorMessage.swift in Sources */, + A5000005000000000000BB05 /* VotingListViewModel.swift in Sources */, 75A8C1692AE6A1AC0042256E /* VotingViewModel.swift in Sources */, AA0001032AA9F58E00A1B201 /* MayaPortalView.swift in Sources */, AA0001062AA9F58E00A1B202 /* MayaPortalViewController.swift in Sources */, diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/ContestedNamesService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/ContestedNamesService.swift index cf9802949a..039a38d7dc 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/ContestedNamesService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/ContestedNamesService.swift @@ -110,15 +110,9 @@ final class ContestedNamesService { /// never contested, or the poll has been pruned since it resolved. func voteState(normalizedLabel: String) async throws -> DPNSContestVoteState? { let sdk = try requireSDK() - // FIXME(sdk): this blocks the main thread. `SDK.dpnsContestVoteState` - // is a synchronous `@MainActor` method around a blocking FFI call that - // goes to an evonode, so the round-trip runs on the main thread and the - // UI freezes until it answers — opening "Request details" hangs the app - // for seconds. It cannot be fixed here: the method's isolation forbids - // calling it off the main actor. The fix belongs in swift-sdk, where - // `dpnsActiveContests` in the same file already shows the shape - // (continuation + a dedicated GCD queue). - return try sdk.dpnsContestVoteState(normalizedLabel: normalizedLabel) + // The off-main read runs the FFI round trip on the SDK's Platform + // query queue, so the main thread only awaits it. + return try await sdk.dpnsContestVoteStateOffMain(normalizedLabel: normalizedLabel) } /// Whether a vote cast right now on `normalizedLabel` can still be @@ -126,8 +120,7 @@ final class ContestedNamesService { /// instead of after a long broadcast retry. func contestIsOpen(normalizedLabel: String) async throws -> Bool { let sdk = try requireSDK() - // Same main-thread problem as `voteState`, same place to fix it. - return try sdk.dpnsContestIsOpen(normalizedLabel: normalizedLabel) + return try await sdk.dpnsContestIsOpenOffMain(normalizedLabel: normalizedLabel) } /// Homograph-normalize a user-typed label into the form Platform indexes diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoteCaster.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoteCaster.swift index 3ec2630e71..e527cbc213 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoteCaster.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoteCaster.swift @@ -71,8 +71,11 @@ enum VoteChoice: Hashable { /// so a partial run is reported as a partial run rather than as an error. struct VoteOutcome: Identifiable { let node: VoterNode - /// `nil` on success; the Platform or local error message otherwise. + /// `nil` on success; the reason in plain words otherwise. let failure: String? + /// `false` when Platform accepted the vote but the local history write + /// failed, so the stored cast count is one low. + var historyRecorded: Bool = true var id: Data { node.proTxHash } var succeeded: Bool { failure == nil } @@ -108,8 +111,6 @@ final class MasternodeVoteCaster { subsystem: "org.dashfoundation.dash", category: "swift-sdk-migration.voting") - private static let history: VoteHistoryDAO = VoteHistoryDAOImpl.shared - /// Vote history is per Platform network — a testnet contest and a mainnet /// one can share a label, and their counts must never merge. static var networkKey: String { @@ -118,12 +119,40 @@ final class MasternodeVoteCaster { WalletEnvironment.network?.persistenceScope ?? "mainnet" } - private let registry: MasternodeVoterRegistry private let contests: ContestedNamesService + private let history: VoteHistoryDAO + private let votingKey: (VoterNode) -> Data? + private let send: VoteSender + + /// Broadcasts one vote for one node. Throws on any failure. + typealias VoteSender = ( + _ node: VoterNode, _ votingKey: Data, _ choice: VoteChoice, _ normalizedLabel: String + ) async throws -> Void - init(registry: MasternodeVoterRegistry, contests: ContestedNamesService) { - self.registry = registry + /// - Parameters: + /// - votingKey: derives a node's voting key; `nil` uses the registry. + /// - send: broadcasts one vote; `nil` uses the SDK. + init( + registry: MasternodeVoterRegistry, + contests: ContestedNamesService, + history: VoteHistoryDAO, + votingKey: ((VoterNode) -> Data?)? = nil, + send: VoteSender? = nil + ) { self.contests = contests + self.history = history + self.votingKey = votingKey ?? { registry.votingPrivateKey(for: $0) } + self.send = send ?? { node, votingKey, choice, normalizedLabel in + guard let sdk = SwiftDashSDKHost.shared.sdk else { throw CastError.sdkUnavailable } + try await sdk.castContestedResourceVote( + dataContractId: DPNSVotePoll.contractId, + documentTypeName: DPNSVotePoll.documentTypeName, + indexName: DPNSVotePoll.indexName, + indexValues: DPNSVotePoll.indexValues(normalizedLabel: normalizedLabel), + choice: choice.sdkChoice, + proTxHash: node.proTxHash, + votingPrivateKey: votingKey) + } } enum CastError: LocalizedError { @@ -156,7 +185,7 @@ final class MasternodeVoteCaster { /// Cast `choice` on `normalizedLabel` with each node in `nodes`. /// /// Prompts for PIN/biometric once, then hands off to - /// ``castAuthenticated(choice:onNormalizedLabel:with:sdk:)``. + /// ``castAuthenticated(choice:onNormalizedLabel:with:)``. /// /// - Throws: ``CastError`` when the run cannot start at all (auth refused, /// poll already closed). Once broadcasting starts, per-node failures are @@ -168,7 +197,7 @@ final class MasternodeVoteCaster { with nodes: [VoterNode] ) async throws -> VoteCastReport { guard !nodes.isEmpty else { throw CastError.noNodesSelected } - guard let sdk = SwiftDashSDKHost.shared.sdk else { throw CastError.sdkUnavailable } + guard SwiftDashSDKHost.shared.sdk != nil else { throw CastError.sdkUnavailable } // Pre-flight: a closed poll otherwise fails only after a long // broadcast retry, with an error that says nothing useful. @@ -187,7 +216,7 @@ final class MasternodeVoteCaster { } return await castAuthenticated( - choice: choice, onNormalizedLabel: normalizedLabel, with: nodes, sdk: sdk) + choice: choice, onNormalizedLabel: normalizedLabel, with: nodes) } /// The per-node broadcast loop, after authentication and pre-flight. @@ -197,18 +226,34 @@ final class MasternodeVoteCaster { /// the same node would race on it. Never throws — a node that fails is /// recorded and the loop continues, so one failure cannot discard the /// nodes that already succeeded. - private func castAuthenticated( + func castAuthenticated( choice: VoteChoice, onNormalizedLabel normalizedLabel: String, - with nodes: [VoterNode], - sdk: SDK + with nodes: [VoterNode] ) async -> VoteCastReport { - let indexValues = DPNSVotePoll.indexValues(normalizedLabel: normalizedLabel) var outcomes: [VoteOutcome] = [] outcomes.reserveCapacity(nodes.count) for node in nodes { - guard let votingKey = registry.votingPrivateKey(for: node) else { + // Re-read the count before every cast: Platform refuses the sixth, + // and an unreadable count is unknown, never zero. + guard let votes = await history.votes(forContest: normalizedLabel, network: Self.networkKey) else { + outcomes.append(VoteOutcome( + node: node, + failure: NSLocalizedString( + "Could not check how many votes this node has left.", + comment: "Voting"))) + continue + } + let castCount = votes.first { $0.proTxHash == node.proTxHash }?.castCount ?? 0 + guard castCount < VoteLimit.maxCastsPerNode else { + outcomes.append(VoteOutcome( + node: node, + failure: NSLocalizedString("No votes left", comment: "Voting"))) + continue + } + + guard let votingKey = votingKey(node) else { outcomes.append(VoteOutcome( node: node, failure: NSLocalizedString( @@ -218,36 +263,39 @@ final class MasternodeVoteCaster { } do { - try await sdk.castContestedResourceVote( - dataContractId: DPNSVotePoll.contractId, - documentTypeName: DPNSVotePoll.documentTypeName, - indexName: DPNSVotePoll.indexName, - indexValues: indexValues, - choice: choice.sdkChoice, - proTxHash: node.proTxHash, - votingPrivateKey: votingKey) - outcomes.append(VoteOutcome(node: node, failure: nil)) - // Recorded only on success, so the count the UI shows is - // votes Platform accepted — not votes attempted. - await Self.history.record( + try await send(node, votingKey, choice, normalizedLabel) + } catch { + // Stored in plain words: Platform's own text is never shown, + // and never logged beyond the error's type. + let message = VoteErrorMessage.plain(for: error) + outcomes.append(VoteOutcome(node: node, failure: message)) + let errorType = String(describing: type(of: error)) + let nodeName = node.displayName + Self.logger.error( + "🗳️ VOTING :: cast failed on \(normalizedLabel, privacy: .public) with \(nodeName, privacy: .public): \(errorType, privacy: .public)") + continue + } + + // Recorded only on success, so the count the UI shows is + // votes Platform accepted — not votes attempted. + var historyRecorded = true + do { + try await history.record( CastVoteRecord( proTxHash: node.proTxHash, normalizedLabel: normalizedLabel, choice: choice, castAt: Date()), network: Self.networkKey) - Self.logger.info( - "🗳️ VOTING :: cast \(choice.logDescription, privacy: .public) on \(normalizedLabel, privacy: .public) with \(node.displayName, privacy: .public)") } catch { - // Platform's message is the useful one here — "already voted", - // "too many vote changes", "masternode not found" each tell - // the user something different. Surface it verbatim. - let message = (error as? LocalizedError)?.errorDescription - ?? String(describing: error) - outcomes.append(VoteOutcome(node: node, failure: message)) + historyRecorded = false + let errorType = String(describing: type(of: error)) Self.logger.error( - "🗳️ VOTING :: cast failed on \(normalizedLabel, privacy: .public) with \(node.displayName, privacy: .public): \(message, privacy: .public)") + "🗳️ VOTING :: history write failed on \(normalizedLabel, privacy: .public): \(errorType, privacy: .public)") } + outcomes.append(VoteOutcome(node: node, failure: nil, historyRecorded: historyRecorded)) + Self.logger.info( + "🗳️ VOTING :: cast \(choice.logDescription, privacy: .public) on \(normalizedLabel, privacy: .public) with \(node.displayName, privacy: .public)") } return VoteCastReport( diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoterRegistry.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoterRegistry.swift index 89e5c50431..070b8ebaeb 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoterRegistry.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/MasternodeVoterRegistry.swift @@ -104,6 +104,17 @@ final class MasternodeVoterRegistry { static let empty = Resolution(nodes: [], mayBeIncomplete: false) } + /// The SDK is running and the wallet's sync is done, so an empty + /// ``votableNodes()`` is this wallet's answer rather than a list that is + /// not there yet. The wallet's own masternodes come from its provider + /// transactions, which the filter scan finds after the masternode list + /// has synced, so the gate is the whole sync (`.syncDone`), not the + /// masternode phase. + var isNodeListSynced: Bool { + SwiftDashSDKHost.shared.manager != nil && SwiftDashSDKHost.shared.wallet != nil + && SyncingActivityMonitor.shared.state == .syncDone + } + /// The wallet's votable nodes, ordered by registration. /// /// A masternode is votable when all of the following hold: diff --git a/DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift b/DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift index 5af7e2b92f..e7982ce282 100644 --- a/DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift +++ b/DashWallet/Sources/Models/Voting/VoteHistoryDAO.swift @@ -46,7 +46,9 @@ struct CastVoteRecord: Hashable { protocol VoteHistoryDAO { /// Upsert — a node re-voting on the same contest replaces its own row, /// mirroring Platform, where a masternode has one live vote per poll. - func record(_ record: CastVoteRecord, network: String) async + /// - Throws: the store's error, so a caller whose vote already landed can + /// still count it as a spent cast. + func record(_ record: CastVoteRecord, network: String) async throws /// Votes this device cast on one contest, newest first. `nil` when the /// store could not be read — unknown, not "no votes". func votes(forContest normalizedLabel: String, network: String) async -> [CastVoteRecord]? @@ -71,7 +73,7 @@ actor VoteHistoryDAOImpl: VoteHistoryDAO { self.connection = connection } - func record(_ record: CastVoteRecord, network: String) async { + func record(_ record: CastVoteRecord, network: String) async throws { let query = """ INSERT INTO masternode_vote_history (proTxHash, normalizedLabel, network, choice, contenderIdentityId, castAt, castCount) @@ -94,11 +96,7 @@ actor VoteHistoryDAOImpl: VoteHistoryDAO { Int64(record.castAt.timeIntervalSince1970 * 1000), ] - do { - try db.run(query, bindings) - } catch { - DWLogger.log("VoteHistoryDAO: record failed: \(error)") - } + try db.run(query, bindings) } func votes(forContest normalizedLabel: String, network: String) async -> [CastVoteRecord]? { diff --git a/DashWallet/Sources/UI/DashPay/Voting/CastVoteSheet.swift b/DashWallet/Sources/UI/DashPay/Voting/CastVoteSheet.swift index c6077b8593..bf596181e7 100644 --- a/DashWallet/Sources/UI/DashPay/Voting/CastVoteSheet.swift +++ b/DashWallet/Sources/UI/DashPay/Voting/CastVoteSheet.swift @@ -28,6 +28,9 @@ import SwiftUI struct CastVoteSheet: View { let contest: DPNSContest let choice: VoteChoice + /// Set when this abstain takes back a choice: only the nodes holding it + /// are offered (AC-17). + var cancelling: VoteChoice? @ObservedObject var viewModel: VotingViewModel @Environment(\.dismiss) @@ -36,52 +39,34 @@ struct CastVoteSheet: View { /// What the sheet showed when Cast was tapped. A successful cast reloads /// the history while the sheet is still closing, and the live lists would /// then flash "already voted" with nothing left to cast. - @State private var castSnapshot: (candidates: [VoterNode], holding: Int)? + @State private var castSnapshot: VotingStore.CastCandidates? - private var selectedNodes: [VoterNode] { - candidateNodes.filter { selectedNodeIDs.contains($0.proTxHash) } + /// The nodes this choice can be cast with, and why ticked nodes are not + /// among them. A node holding a different choice is offered: replacing its + /// vote is a single state transition. + private var candidates: VotingStore.CastCandidates { + castSnapshot ?? viewModel.castCandidates(for: choice, cancelling: cancelling, on: contest.normalizedLabel) } - /// The nodes this choice can be cast with: everything except nodes that - /// already hold *this* choice — Platform rejects a repeat of the same vote - /// — and nodes that have spent the five casts it allows per contest. - /// - /// A node holding a different choice belongs here. Replacing its vote is a - /// single state transition, and excluding it was what made changing your - /// mind impossible from this sheet. - private var candidateNodes: [VoterNode] { - castSnapshot?.candidates ?? viewModel.nodesForVote(choice, on: contest.normalizedLabel) - } + private var candidateNodes: [VoterNode] { candidates.nodes } - /// The nodes this sheet is talking about at all: `candidateNodes` is - /// already filtered by the remembered selection, so the counts explaining - /// what was left out have to be filtered the same way — otherwise nodes - /// the user never selected are reported as having used up their votes. - private var selectedVotableNodes: [VoterNode] { - let selected = viewModel.effectiveSelectedNodeIDs - return viewModel.votableNodes.filter { selected.contains($0.proTxHash) } + private var selectedNodes: [VoterNode] { + candidateNodes.filter { selectedNodeIDs.contains($0.proTxHash) } } /// Nodes left out because they already hold this exact choice. - private var holdingThisChoice: Int { - if let castSnapshot { return castSnapshot.holding } - return selectedVotableNodes.filter { - viewModel.liveChoice(of: $0, on: contest.normalizedLabel) == choice - }.count - } + private var holdingThisChoice: Int { candidates.holdingThisChoice } /// Nodes left out because they have no casts left on this contest. - private var outOfCasts: Int { - max(0, selectedVotableNodes.count - candidateNodes.count - holdingThisChoice) - } + private var outOfCasts: Int { candidates.outOfCasts } var body: some View { DashUIKit.BottomSheet( title: NSLocalizedString("Cast vote", comment: "Voting"), showBackButton: .constant(false), // No swipe-down while a vote is being cast, same as the close button. - isDismissalEnabled: .constant(!viewModel.isCasting), - isCloseButtonEnabled: !viewModel.isCasting, + isDismissalEnabled: .constant(!viewModel.isSending(normalizedLabel: contest.normalizedLabel)), + isCloseButtonEnabled: !viewModel.isSending(normalizedLabel: contest.normalizedLabel), onClose: { viewModel.dismissCastResult() dismiss() @@ -99,7 +84,7 @@ struct CastVoteSheet: View { } // Not swiped away mid-cast: the outcome belongs to this sheet, and the // next sheet would otherwise open into it. - .interactiveDismissDisabled(viewModel.isCasting) + .interactiveDismissDisabled(viewModel.isSending(normalizedLabel: contest.normalizedLabel)) .onAppear { if selectedNodeIDs.isEmpty { // Honour the privacy mode: one node preselected by default, @@ -175,7 +160,7 @@ struct CastVoteSheet: View { Section { Button { - castSnapshot = (candidateNodes, holdingThisChoice) + castSnapshot = candidates Task { // Every node's vote landed: the screen behind says so in // a toast. A partial or failed cast stays here, where the @@ -189,7 +174,7 @@ struct CastVoteSheet: View { } label: { HStack { Spacer() - if viewModel.isCasting { + if viewModel.isSending(normalizedLabel: contest.normalizedLabel) { SwiftUI.ProgressView() } else { Text(castButtonTitle).fontWeight(.semibold) @@ -197,7 +182,7 @@ struct CastVoteSheet: View { Spacer() } } - .disabled(selectedNodes.isEmpty || viewModel.isCasting) + .disabled(selectedNodes.isEmpty || viewModel.isSending(normalizedLabel: contest.normalizedLabel)) } } } @@ -366,3 +351,139 @@ private struct VoteResultView: View { report.succeeded.count, report.outcomes.count) } } + +// MARK: - Previews + +#if DEBUG +/// Shows the sheet once the store has loaded the contest's history, as the +/// vote flow does. +private struct CastVoteSheetPreview: View { + let contest: DPNSContest + let choice: VoteChoice + var cancelling: VoteChoice? + let viewModel: VotingViewModel + @State private var loaded = false + + var body: some View { + Group { + if loaded { + CastVoteSheet(contest: contest, choice: choice, cancelling: cancelling, viewModel: viewModel) + } else { + SwiftUI.ProgressView() + } + } + .task { + await viewModel.store.refresh() + loaded = true + } + } +} + +private let castPreviewEnd = Date(timeIntervalSince1970: 1_800_000_000) +private let castPreviewCastAt = Date(timeIntervalSince1970: 1_799_000_000) + +private func castPreviewNode(_ byte: UInt8, address: String) -> VoterNode { + VoterNode(proTxHash: Data([byte]), isEvonode: byte == 3, typeIndex: UInt32(byte), + serviceAddress: address, keySource: .walletIndex(UInt32(byte))) +} + +private let castPreviewNodes = [ + castPreviewNode(1, address: "203.0.113.10:9999"), + castPreviewNode(2, address: "203.0.113.11:9999"), + castPreviewNode(3, address: "203.0.113.12:9999"), +] + +private func castPreviewContest(_ label: String) -> DPNSContest { + DPNSContest( + normalizedLabel: label, endTime: castPreviewEnd, hasWinner: false, abstainVotes: 0, lockVotes: 2, + contenders: [DPNSContender(identityId: "8Xq3Yz1mWd4k9PnVtR2sLbHc7JfEuAo5GiQwKx6TyMnZ", voteTally: 4, + displayLabel: label)]) +} + +private func castPreviewRecord( + _ node: VoterNode, _ label: String, _ choice: VoteChoice, casts: Int = 1 +) -> CastVoteRecord { + CastVoteRecord(proTxHash: node.proTxHash, normalizedLabel: label, choice: choice, + castAt: castPreviewCastAt, castCount: casts) +} + +/// Holds no keys and touches no keychain. +private struct CastPreviewVault: TrackedMasternodeKeyVaulting { + func key(for proTxHash: Data, role: MasternodeKeyRole) -> String? { nil } + func store(_ keyText: String, for proTxHash: Data, role: MasternodeKeyRole) -> Bool { false } + func removeKey(for proTxHash: Data, role: MasternodeKeyRole) -> Bool { false } + func attachedRoles(for proTxHash: Data) -> Set { [] } + func keyPresence(for proTxHash: Data, role: MasternodeKeyRole) -> TrackedMasternodeKeyPresence { .absent } + func removeAllKeys(for proTxHash: Data) {} +} + +@MainActor +private func castPreview( + _ contest: DPNSContest, + choice: VoteChoice, + cancelling: VoteChoice? = nil, + records: [CastVoteRecord] = [], + castError: String? = nil, + report: VoteCastReport? = nil +) -> some View { + let store = VotingStore( + contests: PreviewContests(contests: [contest]), + nodes: PreviewNodes(nodes: castPreviewNodes), + caster: PreviewCaster(), + history: PreviewHistory(records: records), + prefs: PreviewPrefs(selection: Set(castPreviewNodes.map(\.proTxHash)))) + let viewModel = VotingViewModel(vault: CastPreviewVault(), tracker: { nil }, store: store) + viewModel.castError = castError + viewModel.lastCastReport = report + return CastVoteSheetPreview(contest: contest, choice: choice, cancelling: cancelling, viewModel: viewModel) +} + +private let castPreviewApprove = VoteChoice.towards(identityId: "8Xq3Yz1mWd4k9PnVtR2sLbHc7JfEuAo5GiQwKx6TyMnZ") + +#Preview("Vote") { + castPreview(castPreviewContest("johndoe"), choice: castPreviewApprove) +} + +#Preview("Block, one node already blocks") { + castPreview(castPreviewContest("johndoe"), choice: .lock, + records: [castPreviewRecord(castPreviewNodes[0], "johndoe", .lock)]) +} + +#Preview("Some nodes out of casts") { + castPreview(castPreviewContest("johndoe"), choice: castPreviewApprove, records: [ + castPreviewRecord(castPreviewNodes[0], "johndoe", .lock, casts: VoteLimit.maxCastsPerNode), + castPreviewRecord(castPreviewNodes[1], "johndoe", castPreviewApprove), + ]) +} + +#Preview("Cancel approval") { + castPreview(castPreviewContest("johndoe"), choice: .abstain, cancelling: castPreviewApprove, records: [ + castPreviewRecord(castPreviewNodes[0], "johndoe", castPreviewApprove), + castPreviewRecord(castPreviewNodes[1], "johndoe", .lock), + castPreviewRecord(castPreviewNodes[2], "johndoe", castPreviewApprove, casts: VoteLimit.maxCastsPerNode), + ]) +} + +#Preview("Error") { + castPreview(castPreviewContest("johndoe"), choice: castPreviewApprove, + castError: "Authentication cancelled. Your vote was not cast.") +} + +#Preview("Result (mixed)") { + castPreview(castPreviewContest("johndoe"), choice: castPreviewApprove, report: VoteCastReport( + normalizedLabel: "johndoe", choice: castPreviewApprove, outcomes: [ + VoteOutcome(node: castPreviewNodes[0], failure: nil), + VoteOutcome(node: castPreviewNodes[1], failure: nil), + VoteOutcome(node: castPreviewNodes[2], failure: "No votes left"), + ])) +} + +#Preview("No node can cast this") { + castPreview(castPreviewContest("johndoe"), choice: .lock, + records: castPreviewNodes.map { castPreviewRecord($0, "johndoe", .lock) }) +} + +#Preview("Long name") { + castPreview(castPreviewContest("somelongusernamethatkeepsgoingandgoingandgoing"), choice: .lock) +} +#endif diff --git a/DashWallet/Sources/UI/DashPay/Voting/ContestDetailScreen.swift b/DashWallet/Sources/UI/DashPay/Voting/ContestDetailScreen.swift index 6c11f8cf8f..728ab5b60c 100644 --- a/DashWallet/Sources/UI/DashPay/Voting/ContestDetailScreen.swift +++ b/DashWallet/Sources/UI/DashPay/Voting/ContestDetailScreen.swift @@ -150,7 +150,7 @@ struct ContestDetailScreen: View { ContenderRow( contender: contender, normalizedLabel: contest.normalizedLabel, - votingEndsAt: current.endTime, + voting: viewModel, // Nobody leads before the first vote: with every tally at // zero the first row was highlighted as if it were ahead. isLeading: contender.id == current.leadingContender?.id @@ -236,7 +236,7 @@ private struct ContenderRow: View { /// Passed through to the details screen, which shows the stored form and /// looks this contender's published link up by it. let normalizedLabel: String - let votingEndsAt: Date? + let voting: VotingViewModel let isLeading: Bool let canVote: Bool let voteTitle: String @@ -248,13 +248,10 @@ private struct ContenderRow: View { // one row, so the link wraps only the text — wrapping the row would // swallow the button's tap. NavigationLink { - ContenderDetailScreen( - contender: contender, + RequestDetailsScreen( + voting: voting, normalizedLabel: normalizedLabel, - votingEndsAt: votingEndsAt, - canVote: canVote, - voteTitle: voteTitle, - onVote: onVote) + identityId: contender.identityId) } label: { HStack(spacing: 6) { VStack(alignment: .leading, spacing: 2) { @@ -339,195 +336,3 @@ extension VoteChoice: Identifiable { } } } - -// MARK: - ContenderDetailScreen - -/// One contender, in the same four fields — and the same shape — as the -/// requester's own "Request details": the name as this person typed it, the -/// proof of identity they published, who they are on Platform, and when the -/// result is due. The vote control comes along so the decision can be made -/// where the evidence is. -private struct ContenderDetailScreen: View { - let contender: DPNSContender - let normalizedLabel: String - let votingEndsAt: Date? - let canVote: Bool - let voteTitle: String - let onVote: () -> Void - - @Environment(\.dismiss) private var dismiss - /// What the link lookup has to say. Reading, a link, nothing published, or - /// a failure — four answers, because collapsing the last two tells a voter - /// this contender published no proof when in truth the query did not run. - private enum LinkState { - case reading - case published(URL) - case none - case failed - } - @State private var link: LinkState = .reading - - private enum Layout { - static let cardSpacing: CGFloat = 2 - static let rowHPadding: CGFloat = 14 - static let rowVPadding: CGFloat = 12 - static let labelSpacing: CGFloat = 20 - static let rowMinHeight: CGFloat = 46 - } - - private var requestedLabel: String { - contender.displayLabel ?? normalizedLabel - } - - var body: some View { - VStack(spacing: 0) { - DashUIKit.NavigationBar( - leading: { DashUIKit.NavigationBarElement.back.button(action: { dismiss() }) }) - - ScrollView { - VStack(alignment: .leading, spacing: 20) { - DashUIKit.TopIntroView( - title: NSLocalizedString("Contender details", comment: "Voting"), - mainDescription: NSLocalizedString( - "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on.", - comment: "Voting")) - .padding(.horizontal, 20) - - VStack(spacing: Layout.cardSpacing) { - detailRow(NSLocalizedString("Username", comment: "Voting")) { - Text(requestedLabel) - } - detailRow(NSLocalizedString("Link", comment: "Voting")) { - linkValue - } - detailRow(NSLocalizedString("Identity", comment: "Voting")) { - Text(contender.identityId) - .lineLimit(1) - .truncationMode(.middle) - } - detailRow(NSLocalizedString("Results", comment: "Voting")) { - Text(votingEndsAt.map { DWDateFormatter.sharedInstance.dateAndTime(from: $0) } - ?? NSLocalizedString("Unknown", comment: "Voting")) - } - } - .modifier(DashUIKit.MenuViewModifier(shadowRadius: 20)) - .padding(.horizontal, 20) - - if canVote { - DashUIKit.DashButton( - text: voteTitle, - fillsWidth: true, - size: .large, - style: .filledBlue, - action: { - // The cast sheet belongs to the screen behind - // this one; step back rather than stack a - // second presentation on top of it. - dismiss() - onVote() - }) - .padding(.horizontal, 20) - } - } - .padding(.vertical, 20) - .frame(maxWidth: .infinity, alignment: .leading) - } - .scrollBounceBehavior(.basedOnSize) - } - .background(Color.dash.primaryBackground) - .navigationBarHidden(true) - .task { - guard case .reading = link else { return } - await loadLink() - } - } - - private func loadLink() async { - link = .reading - do { - if let url = try await IdentityVerifyService.shared.publishedURL( - forLabel: normalizedLabel, ownedBy: contender.identityId) { - link = .published(url) - } else { - link = .none - } - } catch { - link = .failed - } - } - - @ViewBuilder - private var linkValue: some View { - switch link { - case .reading: - HStack(spacing: 6) { - SwiftUI.ProgressView() - Text(NSLocalizedString("Checking…", comment: "Voting")) - } - .foregroundColor(Color.dash.secondaryText) - case .none: - Text(NSLocalizedString("None", comment: "Voting")) - .foregroundColor(Color.dash.secondaryText) - case .failed: - // Not "None": the difference between "published nothing" and "we - // could not ask" is the whole value of this row to a voter. - Button { - Task { await loadLink() } - } label: { - HStack(spacing: 6) { - Text(NSLocalizedString("Could not check — retry", comment: "Voting")) - Image(systemName: "arrow.clockwise") - } - .foregroundStyle(Color.dash.blue) - } - case .published(let url) where !Self.isOpenableInBrowser(url): - // Written by another contender, through any client or straight - // against the contract, so the read path cannot assume what the - // write path enforces. A `someapp://…` value handed to the system - // opener is an attacker's choice of action, taken by a masternode - // owner who only meant to read; show it, do not offer it. - Text(url.absoluteString) - .lineLimit(1) - .truncationMode(.middle) - .foregroundColor(Color.dash.secondaryText) - case .published(let url): - Link(destination: url) { - HStack(spacing: 6) { - Text(url.absoluteString) - .lineLimit(1) - .truncationMode(.middle) - Image(systemName: "arrow.up.right.square") - } - .foregroundStyle(Color.dash.blue) - } - } - } - - /// Whether this is a link a browser will take: `http` or `https` and - /// nothing else, matching what the publish path accepts. - private static func isOpenableInBrowser(_ url: URL) -> Bool { - guard let scheme = url.scheme?.lowercased() else { return false } - return scheme == "http" || scheme == "https" - } - - private func detailRow( - _ label: String, - @ViewBuilder value: () -> Value - ) -> some View { - HStack(alignment: .top, spacing: Layout.labelSpacing) { - Text(label) - .dashFont(.subheadMedium) - .foregroundColor(Color.dash.tertiaryText) - .fixedSize() - - value() - .dashFont(.subhead) - .foregroundColor(Color.dash.primaryText) - .multilineTextAlignment(.trailing) - .frame(maxWidth: .infinity, alignment: .trailing) - } - .padding(.horizontal, Layout.rowHPadding) - .padding(.vertical, Layout.rowVPadding) - .frame(minHeight: Layout.rowMinHeight) - } -} diff --git a/DashWallet/Sources/UI/DashPay/Voting/Details/RequestDetailField.swift b/DashWallet/Sources/UI/DashPay/Voting/Details/RequestDetailField.swift new file mode 100644 index 0000000000..9c897b1a99 --- /dev/null +++ b/DashWallet/Sources/UI/DashPay/Voting/Details/RequestDetailField.swift @@ -0,0 +1,81 @@ +// +// RequestDetailField.swift +// DashWallet +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import DashUIKit +import SwiftUI + +// MARK: - RequestDetailField + +/// A read-only field: a label above a wrapping value on a gray card. The value +/// is any view, so a field can show text, a link, or a spinner. +struct RequestDetailField: View { + let label: String + @ViewBuilder let value: () -> Value + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Text(label) + .dashFont(.footnoteMedium) + .foregroundStyle(Color.dash.tertiaryText) + value() + .dashFont(.subhead) + .foregroundStyle(Color.dash.primaryText) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 14) + .padding(.vertical, 12) + .background(Color.dash.gray300Alpha10, in: RoundedRectangle(cornerRadius: 12)) + .accessibilityElement(children: .contain) + } +} + +extension RequestDetailField where Value == Text { + init(label: String, text: String) { + self.init(label: label) { Text(text) } + } +} + +// MARK: - Previews + +#if DEBUG +#Preview("Text") { + RequestDetailField(label: "Username", text: "johndoe").padding(20) +} +#Preview("Long value") { + RequestDetailField( + label: "Identity", + text: "90f95ff7bc2438a748dc8470255b888e1a2b3c4d5e6f708192a3b4c5d6e7f809").padding(20) +} +#Preview("Checking") { + RequestDetailField(label: "Link") { SwiftUI.ProgressView() }.padding(20) +} +#Preview("Link") { + RequestDetailField(label: "Link") { + Link("https://x.com/johndoe/status/1234567890123456789", destination: URL(string: "https://x.com/johndoe")!) + } + .padding(20) +} +#Preview("Dark") { + RequestDetailField(label: "Voting period", text: "Not provided – Oct 25, 2026") + .padding(20) + .preferredColorScheme(.dark) +} +#endif diff --git a/DashWallet/Sources/UI/DashPay/Voting/Details/RequestDetailsScreen.swift b/DashWallet/Sources/UI/DashPay/Voting/Details/RequestDetailsScreen.swift new file mode 100644 index 0000000000..5cab2b9521 --- /dev/null +++ b/DashWallet/Sources/UI/DashPay/Voting/Details/RequestDetailsScreen.swift @@ -0,0 +1,224 @@ +// +// RequestDetailsScreen.swift +// DashWallet +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import DashUIKit +import SwiftDashSDK +import SwiftUI + +// MARK: - RequestDetailsScreen + +/// One request for a username: what its author published to show the name is +/// theirs, and the control to approve it (or take the approval back). Opened +/// straight from a request row. +struct RequestDetailsScreen: View { + @ObservedObject var voting: VotingViewModel + @StateObject private var viewModel: RequestDetailsViewModel + @State private var voteRequest: VoteFlowRequest? + @Environment(\.dismiss) private var dismiss + + init(voting: VotingViewModel, normalizedLabel: String, identityId: String) { + self.voting = voting + let formatter = DateFormatter() + formatter.dateStyle = .medium + formatter.timeStyle = .none + _viewModel = StateObject(wrappedValue: RequestDetailsViewModel( + store: voting.store, + normalizedLabel: normalizedLabel, + identityId: identityId, + linkLookup: RequestDetailsViewModel.publishedLink, + dateFormatter: formatter, + openLink: { UIApplication.shared.open($0) })) + } + + var body: some View { + RequestDetailsContent( + username: viewModel.username, + identityId: viewModel.identityId, + linkState: viewModel.linkState, + linkText: viewModel.linkText, + votingPeriodText: viewModel.votingPeriodText, + approveTitle: viewModel.approveTitle, + isApproveEnabled: viewModel.canApprove, + isSending: voting.isSending(normalizedLabel: viewModel.normalizedLabel), + onBack: { dismiss() }, + onRetry: { Task { await viewModel.loadLink() } }, + onOpenLink: viewModel.open, + onApprove: { voteRequest = viewModel.voteRequest() }) + .task { await viewModel.loadLink() } + .task { + // The list already loaded it in most cases. + if !voting.hasLoadedVoteHistory(for: viewModel.normalizedLabel) { + await voting.loadVotedNodes(for: viewModel.normalizedLabel) + } + } + .voteFlow($voteRequest, viewModel: voting) + } +} + +// MARK: - RequestDetailsContent + +/// The screen's layout, from plain values so it previews without a wallet. +struct RequestDetailsContent: View { + let username: String + let identityId: String + let linkState: RequestDetailsViewModel.LinkState + let linkText: String? + let votingPeriodText: String + let approveTitle: String + let isApproveEnabled: Bool + let isSending: Bool + let onBack: () -> Void + let onRetry: () -> Void + let onOpenLink: (URL) -> Void + let onApprove: () -> Void + + var body: some View { + VStack(spacing: 0) { + DashUIKit.NavigationBar( + leading: { DashUIKit.NavigationBarElement.back.button(action: onBack) }) + + ScrollView { + VStack(alignment: .leading, spacing: 20) { + DashUIKit.TopIntroView( + title: NSLocalizedString("Request details", comment: "Voting"), + mainDescription: NSLocalizedString( + "Review the posting below to verify the ownership of this username", + comment: "Voting")) + .padding(.horizontal, 20) + + VStack(spacing: 10) { + RequestDetailField(label: NSLocalizedString("Username", comment: "Voting"), text: username) + RequestDetailField(label: NSLocalizedString("Link", comment: "Voting")) { linkValue } + RequestDetailField(label: NSLocalizedString("Identity", comment: "Voting"), text: identityId) + RequestDetailField( + label: NSLocalizedString("Voting period", comment: "Voting"), + text: votingPeriodText) + } + .padding(.horizontal, 20) + } + .padding(.vertical, 20) + .frame(maxWidth: .infinity, alignment: .leading) + } + .scrollBounceBehavior(.basedOnSize) + + DashUIKit.DashButton( + text: approveTitle, + isEnabled: isApproveEnabled, + isLoading: isSending, + fillsWidth: true, + size: .large, + style: .filledBlue, + action: onApprove) + .padding(20) + } + .background(Color.dash.primaryBackground) + .navigationBarHidden(true) + } + + @ViewBuilder + private var linkValue: some View { + switch linkState { + case .reading: + SwiftUI.ProgressView() + .accessibilityLabel(NSLocalizedString("Checking…", comment: "Voting")) + case .none: + Text(linkText ?? "").foregroundStyle(Color.dash.secondaryText) + case .failed: + // Not «Not provided»: the check never ran. + VStack(alignment: .leading, spacing: 8) { + Text(linkText ?? "").foregroundStyle(Color.dash.secondaryText) + DashUIKit.DashButton( + text: NSLocalizedString("Try again", comment: ""), + size: .small, + style: .plainBlue, + action: onRetry) + } + case .published(let url) where RequestDetailsViewModel.isOpenableInBrowser(url): + // The full address is the text, so the owner sees the real + // destination before tapping; it opens outside the app. + Button { onOpenLink(url) } label: { + Text(url.absoluteString) + .foregroundStyle(Color.dash.blue) + .multilineTextAlignment(.leading) + } + .buttonStyle(.plain) + .accessibilityAddTraits(.isLink) + .accessibilityRemoveTraits(.isButton) + case .published(let url): + // Written by anyone, through any client; a custom-scheme value + // handed to the system opener is an attacker's choice of action. + // Show it, do not offer it. + Text(url.absoluteString).foregroundStyle(Color.dash.secondaryText) + } + } +} + +// MARK: - Previews + +#if DEBUG +private enum DetailsPreview { + static let identity = "90f95ff7bc2438a748dc8470255b888e1a2b3c4d5e6f708192a3b4c5d6e7f809" + + static func content( + username: String = "johndoe", + identity: String = identity, + link: RequestDetailsViewModel.LinkState, + linkText: String?, + period: String = "Not provided – Oct 25, 2026", + approve: String = "Vote to approve", + isApproveEnabled: Bool = true + ) -> some View { + RequestDetailsContent( + username: username, identityId: identity, linkState: link, linkText: linkText, + votingPeriodText: period, approveTitle: approve, isApproveEnabled: isApproveEnabled, isSending: false, + onBack: {}, onRetry: {}, onOpenLink: { _ in }, onApprove: {}) + } +} + +#Preview("Link published") { + DetailsPreview.content( + link: .published(URL(string: "https://x.com/johndoe/status/1")!), + linkText: "https://x.com/johndoe/status/1") +} +#Preview("Link reading") { DetailsPreview.content(link: .reading, linkText: nil) } +#Preview("Link none") { DetailsPreview.content(link: .none, linkText: "Not provided") } +#Preview("Link failed") { DetailsPreview.content(link: .failed, linkText: "Couldn't check for a link") } +#Preview("My approve") { + DetailsPreview.content( + link: .none, linkText: "Not provided", approve: "Cancel approval") +} +#Preview("Long username and identity") { + DetailsPreview.content( + username: "averyveryveryverylongusernamethatkeepsgoingandgoingtowrap", + identity: DetailsPreview.identity + DetailsPreview.identity, + link: .published(URL(string: "https://example.com/a/very/long/path/that/wraps/over/lines/johndoe")!), + linkText: "https://example.com/a/very/long/path/that/wraps/over/lines/johndoe") +} +#Preview("Approve disabled") { + DetailsPreview.content(link: .none, linkText: "Not provided", isApproveEnabled: false) +} +#Preview("No voting end") { + DetailsPreview.content(link: .none, linkText: "Not provided", period: "Not provided") +} +#Preview("Dark") { + DetailsPreview.content( + link: .published(URL(string: "https://x.com/johndoe")!), linkText: "https://x.com/johndoe") + .preferredColorScheme(.dark) +} +#endif diff --git a/DashWallet/Sources/UI/DashPay/Voting/Details/RequestDetailsViewModel.swift b/DashWallet/Sources/UI/DashPay/Voting/Details/RequestDetailsViewModel.swift new file mode 100644 index 0000000000..dd7a49ca4d --- /dev/null +++ b/DashWallet/Sources/UI/DashPay/Voting/Details/RequestDetailsViewModel.swift @@ -0,0 +1,200 @@ +// +// RequestDetailsViewModel.swift +// DashWallet +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import Combine +import Foundation +import SwiftDashSDK + +// MARK: - RequestDetailsViewModel + +/// One request for a username, as the owner checks it before approving: the +/// name, the identity behind it, the proof it published and the voting period. +/// Everything but the link comes from the already-loaded ``VotingStore``. +@MainActor +final class RequestDetailsViewModel: ObservableObject { + /// What the link lookup has to say. Four answers, because collapsing + /// "nothing published" and "the check failed" tells the owner there is no + /// proof when in truth the query did not run. + enum LinkState: Equatable { + case reading + case published(URL) + case none + case failed + } + + enum ApproveAction: Equatable { + case voteToApprove + case cancelApproval + } + + let identityId: String + let normalizedLabel: String + + @Published private(set) var linkState: LinkState = .reading + + private let store: VotingStore + private let linkLookup: (_ normalizedLabel: String, _ identityId: String) async throws -> URL? + private let dateFormatter: DateFormatter + private let openLink: @MainActor (URL) -> Void + private var changes = Set() + /// The contest as last seen in the store, so the fields keep what they + /// showed once it leaves the list. + private var lastKnownContest: DPNSContest? + + init( + store: VotingStore, + normalizedLabel: String, + identityId: String, + linkLookup: @escaping (_ normalizedLabel: String, _ identityId: String) async throws -> URL?, + dateFormatter: DateFormatter, + openLink: @escaping @MainActor (URL) -> Void + ) { + self.store = store + self.normalizedLabel = normalizedLabel + self.identityId = identityId + self.linkLookup = linkLookup + self.dateFormatter = dateFormatter + self.openLink = openLink + self.lastKnownContest = store.contests.first { $0.normalizedLabel == normalizedLabel } + // The approve button follows votes cast from the sheet this screen opens. + store.objectWillChange.sink { [weak self] in self?.objectWillChange.send() }.store(in: &changes) + } + + /// The screen's lookup: the link this identity published for the name. + static func publishedLink(normalizedLabel: String, identityId: String) async throws -> URL? { + try await IdentityVerifyService.shared.publishedURL(forLabel: normalizedLabel, ownedBy: identityId) + } + + // MARK: Fields + + /// The contest in the store, or the last one seen there. + var contest: DPNSContest? { + if let live = liveContest { lastKnownContest = live } + return lastKnownContest + } + + private var liveContest: DPNSContest? { store.contests.first { $0.normalizedLabel == normalizedLabel } } + + var username: String { + contest?.contenders.first { $0.identityId == identityId }?.displayLabel ?? normalizedLabel + } + + var votingEnd: Date? { contest?.endTime } + + // TODO(voting-5b): the request's date, once the request dates are read. + /// Always unknown for now; `createdAt` is not the request date. + var requestDate: Date? { nil } + + /// « – ». Without a request date the start reads «Not provided»; + /// without a voting end either, the whole field does. + var votingPeriodText: String { + let notProvided = NSLocalizedString("Not provided", comment: "Voting") + guard let votingEnd else { return notProvided } + let end = dateFormatter.string(from: votingEnd) + guard let requestDate else { + return String(format: NSLocalizedString("Not provided – %@", comment: "Voting"), end) + } + return "\(dateFormatter.string(from: requestDate)) – \(end)" + } + + // MARK: Link + + /// `nil` while the check is in flight. + var linkText: String? { + switch linkState { + case .reading: return nil + case .none: return NSLocalizedString("Not provided", comment: "Voting") + case .failed: return NSLocalizedString("Couldn't check for a link", comment: "Voting") + case .published(let url): return url.absoluteString + } + } + + /// Hands a web link to the system to open outside the app. Anything else + /// is written by anyone, through any client, and is never opened. + func open(_ url: URL) { + guard Self.isOpenableInBrowser(url) else { return } + openLink(url) + } + + /// `http` or `https` and nothing else, matching what the publish path accepts. + static func isOpenableInBrowser(_ url: URL) -> Bool { + guard let scheme = url.scheme?.lowercased() else { return false } + return scheme == "http" || scheme == "https" + } + + func loadLink() async { + linkState = .reading + do { + if let url = try await linkLookup(normalizedLabel, identityId) { + linkState = .published(url) + } else { + linkState = .none + } + } catch { + linkState = .failed + } + } + + // MARK: Approve + + /// Cancel approval when a ticked node's last choice approves this request. + var approveAction: ApproveAction { + let ticked = store.tickedNodeIDs ?? [] + let mine = store.votableNodes.contains { node in + ticked.contains(node.proTxHash) + && store.liveChoice(of: node, on: normalizedLabel) == .towards(identityId: identityId) + } + return mine ? .cancelApproval : .voteToApprove + } + + /// Whether the button can start anything: the contest is still on the + /// list and open, and a ticked node can cast it — or, without voting keys, + /// the tap opens the key flow. + var canApprove: Bool { + guard liveContest != nil else { return false } + switch approveAction { + case .voteToApprove: + return store.canStartVote(.towards(identityId: identityId), on: normalizedLabel) + case .cancelApproval: + return !store.isClosed(normalizedLabel: normalizedLabel) + && !store.nodesToCancel(.towards(identityId: identityId), on: normalizedLabel).isEmpty + } + } + + // TODO(voting-4): the button's gates (No votes left, One vote left) run in the vote-attempt coordinator. + /// The vote the button asks for: this request's approve, or an abstain + /// from the nodes holding it. + func voteRequest() -> VoteFlowRequest? { + guard let contest = liveContest else { return nil } + let approve = VoteChoice.towards(identityId: identityId) + switch approveAction { + case .voteToApprove: + return VoteFlowRequest(contest: contest, choice: approve) + case .cancelApproval: + return VoteFlowRequest(contest: contest, choice: .abstain, cancelling: approve) + } + } + + var approveTitle: String { + switch approveAction { + case .voteToApprove: return NSLocalizedString("Vote to approve", comment: "Voting") + case .cancelApproval: return NSLocalizedString("Cancel approval", comment: "Voting") + } + } +} diff --git a/DashWallet/Sources/UI/DashPay/Voting/List/VotingListViewModel.swift b/DashWallet/Sources/UI/DashPay/Voting/List/VotingListViewModel.swift new file mode 100644 index 0000000000..ad61e913d6 --- /dev/null +++ b/DashWallet/Sources/UI/DashPay/Voting/List/VotingListViewModel.swift @@ -0,0 +1,439 @@ +// +// VotingListViewModel.swift +// DashWallet +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import Combine +import Foundation +import SwiftDashSDK + +// MARK: - VotingListViewModel + +/// Presentation state of the username list: the search, the filter, the +/// day-grouped rows and the toast. The contests, masternodes and votes they +/// are computed from live on ``VotingStore``. +@MainActor +final class VotingListViewModel: ObservableObject { + @Published var searchQuery: String = "" { + didSet { + normalizedNeedle = normalizedLabel(searchQuery.trimmingCharacters(in: .whitespacesAndNewlines)) + recomputeVisible() + } + } + /// The search query, homograph-normalized once per edit rather than on + /// every recompute of the list. + private var normalizedNeedle: String? + @Published var filter: VotingFilter = .default { + didSet { + guard filter != oldValue else { return } + recomputeVisible() + } + } + + /// Contests matching the search box and the filter, in the filter's order. + /// Recomputed when the contests, the search, the filter or this wallet's + /// votes change — not on every render, since matching a search normalizes + /// it through the SDK. + @Published private(set) var visibleContests: [DPNSContest] = [] + /// How many open contests the filter keeps, whatever the search narrows + /// the list to: the count next to the filter's name in the header. + @Published private(set) var filterMatchCount = 0 + /// Whether the types that read this wallet's votes can classify every + /// listed contest: the votes can be told, and each contest's history has + /// loaded. Until then their count and an empty list say nothing. + @Published private(set) var myVotesKnownForList = false + /// ``visibleContests`` grouped by the day voting ends. + @Published private(set) var sections: [VotingListSection] = [] + + /// The outcome of the last vote, shown in the list's bottom bar and over + /// the contest screen. + @Published private(set) var toast: VotingToast? + + /// How long a toast stays before it clears itself. + static let toastDuration: Duration = .seconds(3) + + private let store: VotingStore + private let normalizedLabel: @MainActor (String) -> String? + private let now: () -> Date + /// Read on every recompute: the user's time zone can change while the + /// list is open. + private let calendar: () -> Calendar + private var storeChanges: AnyCancellable? + + init( + store: VotingStore, + normalizedLabel: @escaping @MainActor (String) -> String? = { + ContestedNamesService().normalizedLabel(for: $0) + }, + now: @escaping () -> Date = Date.init, + calendar: @escaping () -> Calendar = { .autoupdatingCurrent } + ) { + self.store = store + self.normalizedLabel = normalizedLabel + self.now = now + self.calendar = calendar + storeChanges = store.stateDidChange.sink { [weak self] in self?.recomputeVisible() } + recomputeVisible() + } + + /// What the list shows in place of, or above, its rows. + var loadState: VotingListLoadState { + if !store.hasLoadedOnce { return .loading } + if store.loadFailed && store.contests.isEmpty { return .couldNotLoad } + if store.contests.isEmpty { return .noContests } + return .contests(refreshFailed: store.loadFailed) + } + + /// The banner over the kept rows when the last refresh failed (AC-02). + var refreshFailedText: String? { + guard loadState == .contests(refreshFailed: true) else { return nil } + return NSLocalizedString("Couldn't refresh.", comment: "Voting") + } + + /// What the list shows instead of rows; `nil` when rows show. + var emptyState: VotingListEmptyState? { + switch loadState { + case .loading: + return .loading + case .couldNotLoad: + // Try again is running: show it rather than the old failure. + return store.isRefreshing ? .loading : .couldNotLoad + case .noContests: + return .noContests + case .contests: + break + } + guard visibleContests.isEmpty else { return nil } + if filter.type.readsMyVotes { + // Not the filter's fault: this wallet's votes cannot be told (AC-09). + if let reason = myVotesUnavailableReason { return .cannotFilterByMyVotes(reason: reason) } + // Still loading for some contests: nothing can be said to match yet. + if !myVotesKnownForList { return .loading } + } + // The filter alone hides every open contest (AC-08); otherwise the search does. + return filterMatchCount == 0 ? .filterMatchesNothing : .searchMatchesNothing + } + + /// Also called when the day changes, so "Voting ends today / in N days" + /// stays true on a screen left open past midnight. + func recomputeVisible() { + // Search matching keeps order and does not depend on the filter, so + // filtering first gives both the header count and the rows. + myVotesKnownForList = canFilterByMyVotes + && store.contests.allSatisfy { store.hasLoadedVoteHistory(for: $0.normalizedLabel) } + // A filter by my vote shows nothing until every contest can be told: + // after a refresh the new contests' history is still loading, and + // showing only the contests already known would be a partial list. + let kept = filter.type.readsMyVotes && !myVotesKnownForList ? [] : filtered(store.contests) + filterMatchCount = kept.count + let visible = searchMatches(in: kept) + // Days always go soonest first; the sort orders names inside a day. + // The flat list takes the same order as the grouped one. + sections = VotingListSection.group(visible, now: now(), calendar: calendar()) + visibleContests = sections.flatMap(\.contests) + } + + /// Whether this wallet's own votes can be told for the types that read + /// them: not when the history could not be read, nor while a voting node + /// may be missing from the store's votable nodes (its votes would not count), + /// which is also so until the wallet's sync is done. + var canFilterByMyVotes: Bool { + !store.historyUnavailable && store.nodeListSynced && !store.nodeListMayBeIncomplete && store.canVote + } + + /// Why this wallet's own votes cannot be told, as the next step for the + /// user; `nil` when they can. Without a voting node the wallet holds no + /// vote to tell, so the types that read them have nothing to go on. + var myVotesUnavailableReason: String? { + if store.historyUnavailable { + return NSLocalizedString("Pull down to try again.", comment: "Voting") + } + if store.nodeListMayBeIncomplete { + return NSLocalizedString( + "Some of your masternodes may be missing from this list — the wallet could not read your full voting-key pool. Finish syncing and reopen this screen.", + comment: "Voting") + } + if !store.nodeListSynced { + return NSLocalizedString("The masternode list is still syncing. Try again in a moment.", comment: "Voting") + } + if !store.canVote { + return NSLocalizedString( + "This wallet's masternode voting keys aren't available right now, so it has no votes to filter by.", + comment: "Voting") + } + return nil + } + + /// The contests in `input` matching the search box, in their order. + /// + /// The query is homograph-normalized before matching because Platform + /// stores normalized labels — someone typing "alice" is looking for + /// "a11ce", and a raw substring match would find nothing. + private func searchMatches(in input: [DPNSContest]) -> [DPNSContest] { + let trimmed = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return input } + + // Normalization needs the SDK, and so does `contests` — a non-empty + // list means the handle is up, so this only returns nil when there is + // nothing to filter anyway. Leaving the list unfiltered beats + // matching against a locally-guessed spelling of the label. + // Normalized when the query was typed; again here only if the SDK was + // not up yet then. + if normalizedNeedle == nil { + normalizedNeedle = normalizedLabel(trimmed) + } + guard let needle = normalizedNeedle else { + return input + } + // Match the normalized form *and* the spellings people actually typed, + // so searching "pizza" finds the contest whether the row is showing + // "pizza" or the normalized "p1zza". + let raw = trimmed.lowercased() + return input.filter { contest in + contest.normalizedLabel.contains(needle) + || contest.requestedLabels.contains { $0.lowercased().contains(raw) } + } + } + + private func filtered(_ input: [DPNSContest]) -> [DPNSContest] { + filter.apply(to: input, myChoices: knownChoices(on:)) + } + + /// This wallet's choices on a contest, or `nil` while they are not known + /// (history not loaded or unreadable, node list maybe incomplete): the + /// filters by my vote then leave the contest out rather than guess. + private func knownChoices(on normalizedLabel: String) -> Set? { + guard canFilterByMyVotes, store.hasLoadedVoteHistory(for: normalizedLabel) else { return nil } + return store.myChoices(on: normalizedLabel) + } + + // MARK: Expanded rows (session only) + + /// The names whose several requests are open in place. + @Published private var expandedLabels: Set = [] + + func isExpanded(_ normalizedLabel: String) -> Bool { + expandedLabels.contains(normalizedLabel) + } + + /// A name with a single request has no expand pill, so nothing to open. + func isExpandable(_ contest: DPNSContest) -> Bool { + contest.contenders.count > 1 + } + + func toggleExpanded(_ normalizedLabel: String) { + guard let contest = store.contests.first(where: { $0.normalizedLabel == normalizedLabel }), + isExpandable(contest) else { return } + if !expandedLabels.insert(normalizedLabel).inserted { + expandedLabels.remove(normalizedLabel) + } + } + + /// One row per request, in the contender order, each with its own approve + /// pill state: filled where a ticked node's vote lands on that request. + func requestRows(for contest: DPNSContest) -> [VotingRequestRow] { + let mine = store.myChoices(on: contest.normalizedLabel) + return contest.contenders.map { contender in + VotingRequestRow( + identityId: contender.identityId, + votes: Int(contender.voteTally), + isMine: mine.contains(.towards(identityId: contender.identityId))) + } + } + + // MARK: Pills + + /// Whether a tap on a list pill can start anything. A filled pill takes my + /// vote back (AC-17), so it stays tappable while a ticked node holding that + /// choice can still abstain; an outlined pill follows + /// ``VotingStore/canStartVote(_:on:)``. + func canTapPill(_ choice: VoteChoice, on normalizedLabel: String) -> Bool { + guard store.myChoices(on: normalizedLabel).contains(choice) else { + return store.canStartVote(choice, on: normalizedLabel) + } + return !store.isClosed(normalizedLabel: normalizedLabel) + && !store.nodesToCancel(choice, on: normalizedLabel).isEmpty + } + + // TODO(voting-4): the pill gates (No votes left, One vote left) run in the vote-attempt coordinator. + /// The vote a pill tap asks for: the pill's choice, or, on a filled pill, + /// an abstain from the ticked nodes holding it. + func voteRequest(for choice: VoteChoice, on contest: DPNSContest) -> VoteFlowRequest { + guard store.myChoices(on: contest.normalizedLabel).contains(choice) else { + return VoteFlowRequest(contest: contest, choice: choice) + } + return VoteFlowRequest(contest: contest, choice: .abstain, cancelling: choice) + } + + /// What a tap on the row's name does: one request opens its details, + /// several open or close in place. + func headerAccessibilityHint(for contest: DPNSContest) -> String { + guard isExpandable(contest) else { + return NSLocalizedString("Opens the request details", comment: "Voting") + } + return isExpanded(contest.normalizedLabel) + ? NSLocalizedString("Hides the requests for this name", comment: "Voting") + : NSLocalizedString("Opens the requests for this name", comment: "Voting") + } + + func requestCountText(for contest: DPNSContest) -> String { + String.localizedStringWithFormat( + NSLocalizedString("%d requests", comment: "Voting"), contest.contenders.count) + } + + func expandAccessibilityLabel(for contest: DPNSContest, isExpanded: Bool) -> String { + let format = isExpanded + ? NSLocalizedString("Hide requests for %@", comment: "Voting") + : NSLocalizedString("Show requests for %@", comment: "Voting") + return String(format: format, contest.displayTitle) + } + + func expandAccessibilityValue(for contest: DPNSContest) -> String { + requestCountText(for: contest) + } + + // MARK: Toast + + func showToast(_ toast: VotingToast) { + self.toast = toast + Task { [weak self, id = toast.id] in + try? await Task.sleep(for: Self.toastDuration) + // Only the toast this task was started for: a newer one has its own timer. + if self?.toast?.id == id { self?.toast = nil } + } + } + + func clearToast() { + toast = nil + } +} + +// MARK: - VotingRequestRow + +/// One request of a several-request name, as listed when its row is open. +struct VotingRequestRow: Equatable { + let identityId: String + let votes: Int + /// A ticked node's vote lands on this request: its approve pill is filled. + let isMine: Bool + + /// The identity as VoiceOver reads it: its first and last four + /// characters, enough to tell a row's requests apart; Request details + /// shows the whole id. + var spokenIdentity: String { + guard identityId.count > 8 else { return identityId } + return "\(identityId.prefix(4)) … \(identityId.suffix(4))" + } + + var accessibilityLabel: String { + String(format: NSLocalizedString("Approve %@", comment: "Voting"), spokenIdentity) + } + + var accessibilityValue: String { + String.localizedStringWithFormat(NSLocalizedString("%d votes", comment: "Voting"), votes) + } +} + +// MARK: - VotingListLoadState + +enum VotingListLoadState: Equatable { + /// The first load has not finished. + case loading + /// The load failed and nothing is cached. + case couldNotLoad + /// The load succeeded and no contest is open. + case noContests + /// Contests are held; `refreshFailed` when the last refresh failed. + case contests(refreshFailed: Bool) +} + +// MARK: - VotingListEmptyState + +/// What the list shows in place of its rows. +enum VotingListEmptyState: Equatable { + case loading + /// The load failed and nothing is cached (AC-02). + case couldNotLoad + /// A type by my vote while this wallet's votes cannot be told, and why (AC-09). + case cannotFilterByMyVotes(reason: String) + /// Open contests exist and the filter keeps none (AC-08). + case filterMatchesNothing + /// The load succeeded and no contest is open. + case noContests + /// The filter keeps some, the search none. + case searchMatchesNothing +} + +// MARK: - VotingListSection + +/// The voting list's groups: contests whose voting ends on the same calendar +/// day, soonest first. Rows inside a group keep the order they came in, which +/// is the list's chosen sort. +struct VotingListSection: Identifiable, Equatable { + /// Days from today to the day voting ends; `nil` when the end is unknown. + let daysLeft: Int? + let contests: [DPNSContest] + + var id: Int { daysLeft ?? Int.max } + + var title: String { + switch daysLeft { + case nil: + return NSLocalizedString("Voting end unknown", comment: "Voting") + case 0: + return NSLocalizedString("Voting ends today", comment: "Voting") + case let days?: + return String.localizedStringWithFormat( + NSLocalizedString("Voting ends in %d days", comment: "Voting"), days) + } + } + + /// Group `contests` by end day relative to `now` in `calendar`. A contest + /// whose end has already passed today is still "today" (it is closing); an + /// end on an earlier day also counts as today rather than a negative count. + static func group(_ contests: [DPNSContest], now: Date, calendar: Calendar) -> [VotingListSection] { + let today = calendar.startOfDay(for: now) + var order: [Int?] = [] + var buckets: [Int?: [DPNSContest]] = [:] + for contest in contests { + let key: Int? = contest.endTime.map { end in + let days = calendar.dateComponents([.day], from: today, to: calendar.startOfDay(for: end)).day ?? 0 + return max(days, 0) + } + if buckets[key] == nil { order.append(key) } + buckets[key, default: []].append(contest) + } + return order + .sorted { ($0 ?? Int.max) < ($1 ?? Int.max) } + .map { VotingListSection(daysLeft: $0, contests: buckets[$0] ?? []) } + } +} + +// MARK: - VotingToast + +/// A vote that landed on every node, told briefly in the list's bottom bar or +/// over the contest screen. A +/// partial or failed vote is not a toast: the cast sheet stays open and lists +/// each node's outcome. +struct VotingToast: Identifiable, Equatable { + let id = UUID() + let message: String + + static func voted(username: String) -> VotingToast { + VotingToast(message: String(format: NSLocalizedString("Voted %@ username", comment: "Voting"), username)) + } +} diff --git a/DashWallet/Sources/UI/DashPay/Voting/Store/VoteErrorMessage.swift b/DashWallet/Sources/UI/DashPay/Voting/Store/VoteErrorMessage.swift new file mode 100644 index 0000000000..c7c32c9eb2 --- /dev/null +++ b/DashWallet/Sources/UI/DashPay/Voting/Store/VoteErrorMessage.swift @@ -0,0 +1,94 @@ +// +// VoteErrorMessage.swift +// DashWallet +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import Foundation +import SwiftDashSDK + +/// Turns the errors a vote can fail with into one short sentence in plain +/// words. Platform's own text is never passed through: an error that is not +/// mapped here reads as the generic "try again" message. +enum VoteErrorMessage { + // Platform voting consensus codes, rs-dpp `src/errors/consensus/codes.rs` + // ("Voting Errors: 40300-40399"). + /// `MasternodeNotFoundError` + private static let voterNotFound: UInt32 = 40300 + /// `VotePollNotAvailableForVotingError` + private static let votePollNotAvailable: UInt32 = 40302 + /// `MasternodeVotedTooManyTimesError` + private static let votedTooManyTimes: UInt32 = 40303 + /// `MasternodeIncorrectVotingAddressError` + private static let incorrectVotingAddress: UInt32 = 40305 + /// `MasternodeIncorrectVoterIdentityIdError` + private static let incorrectVoterIdentityId: UInt32 = 40306 + + static func plain(for error: Error) -> String { + if let castError = error as? MasternodeVoteCaster.CastError { + switch castError { + case .authenticationCancelled, .authenticationFailed, .noNodesSelected, .sdkUnavailable: + // The app's own sentences, already in plain words. + return castError.errorDescription ?? generic + case .contestClosed: + return closed + } + } + + if let sdkError = error as? SDKError { + switch sdkError { + case .networkError, .timeout: + return connection + case .consensusRejection(let consensus, _): + return message(forConsensusCode: consensus.code) + default: + return generic + } + } + + if error is URLError { + return connection + } + return generic + } + + private static func message(forConsensusCode code: UInt32) -> String { + switch code { + case votedTooManyTimes: + return NSLocalizedString("No votes left", comment: "Voting") + case votePollNotAvailable: + return closed + case voterNotFound, incorrectVotingAddress, incorrectVoterIdentityId: + return NSLocalizedString( + "The vote was not cast. This voting key does not belong to an active masternode.", + comment: "Voting") + default: + return generic + } + } + + private static var connection: String { + NSLocalizedString("The vote was not cast. Check your connection and try again.", comment: "Voting") + } + + private static var closed: String { + NSLocalizedString("The vote was not cast. Voting on this name has closed.", comment: "Voting") + } + + private static var generic: String { + NSLocalizedString("The vote was not cast. Please try again.", comment: "Voting") + } +} diff --git a/DashWallet/Sources/UI/DashPay/Voting/Store/VoteLimit.swift b/DashWallet/Sources/UI/DashPay/Voting/Store/VoteLimit.swift new file mode 100644 index 0000000000..d87fd62a37 --- /dev/null +++ b/DashWallet/Sources/UI/DashPay/Voting/Store/VoteLimit.swift @@ -0,0 +1,105 @@ +// +// VoteLimit.swift +// DashWallet +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import Foundation + +/// One contest's local vote history reduced to what the casting rules read: +/// each masternode's live vote and how many casts it has spent. +/// +/// The five-cast ceiling is applied by this one rule: looking only at the +/// live choice would offer exhausted nodes that Platform then rejects. +/// An unknown history (`nil`) answers `nil` to every query, never "no votes". +struct VoteLimit { + /// `votes_allowed_per_masternode` in the platform version this app talks + /// to; the sixth cast is refused with `MasternodeVotedTooManyTimesError`. + static let maxCastsPerNode = 5 + + private var latest: [Data: CastVoteRecord] = [:] + private var casts: [Data: Int] = [:] + + /// Whether the history was read at all; `[]` is known, with no votes. + let isKnown: Bool + + init(_ records: [CastVoteRecord]?) { + isKnown = records != nil + // One row per node per contest — a change overwrites the row it + // came from — so the ceiling is read from the row's own + // `castCount`, not from how many rows a node has. Counting rows + // could never reach five. + for record in records ?? [] { + casts[record.proTxHash] = max(casts[record.proTxHash] ?? 0, record.castCount) + if let seen = latest[record.proTxHash], seen.castAt >= record.castAt { continue } + latest[record.proTxHash] = record + } + } + + /// This node's live choice, when it has one. + func liveChoice(of node: Data) -> VoteChoice? { + latest[node]?.choice + } + + /// How many more votes Platform would accept from this node here. + func votesLeft(_ node: Data) -> Int? { + guard isKnown else { return nil } + return max(0, Self.maxCastsPerNode - (casts[node] ?? 0)) + } + + /// The smallest `votesLeft` over `nodes`; `nil` when unknown or `nodes` is empty. + func fewestVotesLeft(among nodes: Set) -> Int? { + guard isKnown else { return nil } + return nodes.compactMap { votesLeft($0) }.min() + } + + func nodesWithVotesLeft(among nodes: Set) -> Set? { + guard isKnown else { return nil } + return nodes.filter { (votesLeft($0) ?? 0) > 0 } + } + + /// The nodes of `nodes` whose live vote is `choice`, abstain included. + func nodes(holding choice: VoteChoice, among nodes: Set) -> Set? { + guard isKnown else { return nil } + return nodes.filter { latest[$0]?.choice == choice } + } + + /// The live choices of `nodes` that fill a pill, for marking "my vote" on + /// a list row. Abstain has no pill and is left out. + func filledChoices(of nodes: Set) -> Set? { + guard isKnown else { return nil } + return Set(nodes.compactMap { latest[$0]?.choice }.filter { $0 != .abstain }) + } + + /// Whether `node`'s live vote was cast at `date` or later. + func hasCast(of node: Data, since date: Date) -> Bool { + guard let castAt = latest[node]?.castAt else { return false } + return castAt >= date + } + + /// One more cast by `node`, as the store records it. It becomes the live + /// choice unless the node already holds a later one. + mutating func recordCast(of node: Data, on normalizedLabel: String, choice: VoteChoice, at date: Date) { + casts[node, default: 0] += 1 + if let seen = latest[node], seen.castAt > date { return } + latest[node] = CastVoteRecord( + proTxHash: node, + normalizedLabel: normalizedLabel, + choice: choice, + castAt: date, + castCount: casts[node] ?? 1) + } +} diff --git a/DashWallet/Sources/UI/DashPay/Voting/Store/VotingStore.swift b/DashWallet/Sources/UI/DashPay/Voting/Store/VotingStore.swift new file mode 100644 index 0000000000..379b2485b5 --- /dev/null +++ b/DashWallet/Sources/UI/DashPay/Voting/Store/VotingStore.swift @@ -0,0 +1,685 @@ +// +// VotingStore.swift +// DashWallet +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import Combine +import Foundation +import SwiftDashSDK + +// MARK: - Dependencies + +/// Reads the open contests and one contest's vote state from Platform. +@MainActor +protocol VotingContestReading { + func activeContests() async throws -> [DPNSContest] + func voteState(normalizedLabel: String) async throws -> DPNSContestVoteState? +} + +/// Resolves the masternodes of this wallet that can vote. +@MainActor +protocol VotableMasternodeResolving { + func votableNodes() -> MasternodeVoterRegistry.Resolution + /// The wallet's sync is done (`SyncingActivityMonitor` `.syncDone`), so an + /// empty ``votableNodes()`` means this wallet has no node rather than that + /// the sync has not found it yet. + var isNodeListSynced: Bool { get } +} + +/// Casts a vote with a set of masternodes. +@MainActor +protocol VoteCasting { + func cast(choice: VoteChoice, onNormalizedLabel normalizedLabel: String, with nodes: [VoterNode]) async throws + -> VoteCastReport +} + +/// Remembers which masternodes the user ticked to vote with. +protocol VotingSelectionStoring: AnyObject { + var votingNodeSelection: Set { get set } +} + +extension ContestedNamesService: VotingContestReading {} +extension MasternodeVoterRegistry: VotableMasternodeResolving {} +extension MasternodeVoteCaster: VoteCasting {} +extension VotingPrefs: VotingSelectionStoring {} + +// MARK: - VotingStore + +/// The one owner of the data every voting screen reads: the open contests, +/// the wallet's votable and ticked masternodes, and the vote history of those +/// contests. Screen view models hold presentation state only. +/// +/// Loads — the whole list, every contest's history, one contest's history, one +/// contest's tallies — run one at a time, in the order they were asked for. +@MainActor +final class VotingStore: ObservableObject { + // MARK: Published state + + /// The contests on the list: the open ones, plus any Platform closed + /// early or left out of its last answer, until their voting end + /// (sad §4 choice 6). ``closedLabels`` says which are closed. + @Published private(set) var contests: [DPNSContest] = [] { + didSet { stateDidChange.send() } + } + /// Labels observed to have resolved while the user was looking at them, + /// so an already-open detail screen can say so instead of offering a vote + /// that can no longer be accepted. + @Published private(set) var closedLabels: Set = [] + @Published private(set) var votableNodes: [VoterNode] = [] { + didSet { + let ids = Set(votableNodes.map(\.proTxHash)) + guard ids != votableNodeIDs else { return } + votableNodeIDs = ids + stateDidChange.send() + } + } + /// ``votableNodes`` as a set, kept with it rather than rebuilt per row. + private(set) var votableNodeIDs: Set = [] + /// ``votableNodes`` was read after the wallet's sync was done, so an empty + /// one means this wallet has no node to vote with. + @Published private(set) var nodeListSynced = false + /// The wallet's voting-key pool could only be read at its shallow + /// fallback depth and some active registration went unmatched, so a node + /// you can actually vote with may be missing from ``votableNodes``. + @Published private(set) var nodeListMayBeIncomplete = false { + didSet { if nodeListMayBeIncomplete != oldValue { stateDidChange.send() } } + } + @Published private(set) var isLoading = false + /// A full refresh is queued or running. + @Published private(set) var isRefreshing = false + /// Set when a refresh fails. The list keeps showing the last good data; + /// the error itself goes to the log, never to the screen. + @Published private(set) var loadFailed = false + /// `false` until the first refresh completes, so the empty state is not + /// shown while the first fetch is still in flight. + @Published private(set) var hasLoadedOnce = false + /// This wallet's vote history could not be read, so the list cannot tell + /// which votes are already cast and holds its vote controls back. + @Published private(set) var historyUnavailable = false { + didSet { if historyUnavailable != oldValue { stateDidChange.send() } } + } + + /// Which of our nodes voted, per contest. Keyed by contest so a screen can + /// never be answered with another contest's history — and so an ABSENT + /// entry is distinguishable from "none voted here", which is what makes + /// gating on load possible. + @Published private(set) var votedProTxHashesByContest: [String: Set] = [:] + + /// Per contest, rebuilt for one contest by `loadVotedNodes(for:)` and for + /// every listed contest by `loadAllVoteHistory()`. + @Published private(set) var voteHistoryByContest: [String: VoteLimit] = [:] { + didSet { stateDidChange.send() } + } + + /// proTxHashes of the nodes the next vote will use, shared by the list + /// and the contest screen and persisted so the next contest + /// opens with the same nodes ticked. + /// + /// Persisted rather than re-asked because it is a privacy choice: voting + /// with several nodes at once links those masternodes to each other, and + /// that should stay the user's standing decision, not something re-made + /// under time pressure on every contest. + @Published var selectedNodeIDs: Set { + didSet { + prefs.votingNodeSelection = selectedNodeIDs + stateDidChange.send() + } + } + + /// The one result of the latest vote attempt: a toast, an error message or + /// the per-masternode report of a mixed run. Cleared when the next attempt + /// starts. + @Published private(set) var outcome: VoteAttemptOutcome? + + /// Votes Platform accepted while this store lived whose history write + /// failed, per contest. The store's rows are one cast short for each, so + /// every history rebuild adds them back: the cast is spent (owner decision, + /// 2026-11-05). Kept per screen open: a store is made each time Username Voting + /// opens, and the next one starts without them (owner, 2026-11-06). + private var unrecordedCasts: [String: [CastVoteRecord]] = [:] + + /// Contests with a vote in flight. Their pills show a spinner and take no + /// taps until the votes are applied and the tallies re-read. + @Published private(set) var sendingLabels: Set = [] + + /// Fires after any change a screen derives its rows from, with the new + /// value already in place (``objectWillChange`` fires before). + let stateDidChange = PassthroughSubject() + + // MARK: Dependencies + + private let contestsReader: VotingContestReading + private let nodes: VotableMasternodeResolving + let caster: VoteCasting + private let history: VoteHistoryDAO + private let prefs: VotingSelectionStoring + private let now: () -> Date + + init( + contests: VotingContestReading, + nodes: VotableMasternodeResolving, + caster: VoteCasting, + history: VoteHistoryDAO, + prefs: VotingSelectionStoring, + now: @escaping () -> Date = Date.init + ) { + self.contestsReader = contests + self.nodes = nodes + self.caster = caster + self.history = history + self.prefs = prefs + self.now = now + self.selectedNodeIDs = prefs.votingNodeSelection + } + + // MARK: Derived state + + var canVote: Bool { !votableNodes.isEmpty } + + /// The stored choice that is still votable — a remembered node that has + /// since been revoked or left the masternode list must not silently come + /// back. `nil` while none is chosen yet, which is not the same as an empty + /// choice. + var tickedNodeIDs: Set? { + let live = selectedNodeIDs.intersection(votableNodeIDs) + return live.isEmpty ? nil : live + } + + /// The remembered selection, or a single node when nothing was ever + /// chosen. Never every node by default: see ``VotingPrefs``. + /// + /// Also recovers from a selection that no longer matches any votable node + /// (nodes revoked, or a different wallet), which would otherwise leave the + /// vote button permanently disabled with no way to see why. + var effectiveSelectedNodeIDs: Set { + tickedNodeIDs ?? Set(votableNodes.first.map { [$0.proTxHash] } ?? []) + } + + /// The latest copy of `contest` in the list, so a screen opened from an + /// older snapshot shows today's counts. + func latest(_ contest: DPNSContest) -> DPNSContest { + contests.first { $0.normalizedLabel == contest.normalizedLabel } ?? contest + } + + /// Whether a contest the user is looking at has closed under them. The + /// detail screen reads this to swap its vote controls for a closed notice + /// instead of silently showing a stale snapshot with live-looking buttons. + func isClosed(normalizedLabel: String) -> Bool { + closedLabels.contains(normalizedLabel) + } + + // MARK: Loading + + /// True once a contest fetch has actually succeeded. Distinct from + /// ``hasLoadedOnce``, which only records that a load was attempted. + private var didLoadContests = false + + /// Each load reads the store or Platform when its turn comes and applies + /// what it read before the next one starts, so a load that read earlier + /// can never land after one that read later and put back what was there + /// before a vote. + private var loadQueueTail: Task? + + /// A queued load must call only `perform…` functions, never the public + /// wrappers: those wait for the queue's tail, which would be itself. + private func serially(_ load: @escaping @MainActor () async -> Void) async { + let previous = loadQueueTail + let next = Task { @MainActor in + await previous?.value + await load() + } + loadQueueTail = next + await next.value + } + + func refresh() async { + queuedRefreshes += 1 + defer { queuedRefreshes -= 1 } + await serially { [weak self] in await self?.performRefresh() } + } + + /// Try again: a refresh, unless one is already queued or running. + func retry() async { + guard !isRefreshing else { return } + await refresh() + } + + private var queuedRefreshes = 0 { + didSet { isRefreshing = queuedRefreshes > 0 } + } + + private func performRefresh() async { + isLoading = true + defer { + isLoading = false + hasLoadedOnce = true + } + + refreshVotableNodes() + + do { + let open = try await contestsReader.activeContests() + let listed = Set(open.map(\.normalizedLabel)) + // A contest the answer leaves out (closed early, or cut from the + // list) stays with its last known votes until its voting end. + let current = now() + let kept = contests.filter { contest in + guard !listed.contains(contest.normalizedLabel), let end = contest.endTime else { return false } + return end > current + } + contests = open + kept + // A contest Platform lists as open again is not closed. + closedLabels.subtract(listed) + loadFailed = false + didLoadContests = true + } catch { + loadFailed = true + DWLogger.log("Voting: contest list load failed (\(type(of: error)))") + } + + // After the contests, so every listed contest gets a known history — + // an empty one included — and its vote controls are not held back + // waiting for a per-contest load. + await performLoadAllVoteHistory() + } + + /// The screen's initial load, which does nothing once contests are in hand. + /// + /// `.task` re-runs when the list reappears — including on the way back from + /// a contest — and `refresh()` re-queries every active contest over the + /// network, which takes long enough to read as the screen hanging. Nothing + /// about returning from a contest invalidates the list: casting already + /// refreshes the one contest it touched via ``refreshContest(normalizedLabel:)``, + /// and pull-to-refresh still forces a real reload. + /// + /// Keyed on contests actually having loaded rather than on an attempt, so a + /// first load that failed still retries instead of stranding the user on an + /// empty list. + func refreshIfNeeded() async { + // Once contests have loaded this loads nothing, so it must not hide + // Try again while the queue is busy with something else. + guard !didLoadContests else { return } + // Counted like a refresh, so Try again shows progress and queues + // nothing while this one waits or runs. + queuedRefreshes += 1 + defer { queuedRefreshes -= 1 } + // Checked when its turn comes: a list that reappears while the first + // load is still queued must not queue a second full refresh. + await serially { [weak self] in + guard let self, !self.didLoadContests else { return } + await self.performRefresh() + } + } + + /// This wallet's vote history for every contest, in one query, so the list + /// can mark the user's own vote on every row without a query per row. + /// + /// Fills the same per-contest maps ``loadVotedNodes(for:)`` fills for one + /// contest. A listed contest with no records gets an empty history: after a + /// full load "no records" means "nobody voted", not "not loaded yet". + private func loadAllVoteHistory() async { + await serially { [weak self] in await self?.performLoadAllVoteHistory() } + } + + private func performLoadAllVoteHistory() async { + let labels = Set(contests.map(\.normalizedLabel)) + // A failed read leaves every history unknown — not "nobody voted", + // which would offer nodes for votes they already hold — and says so. + guard let records = await history.votes( + forContests: labels, network: MasternodeVoteCaster.networkKey) + else { + historyUnavailable = true + return + } + historyUnavailable = false + let byLabel = Dictionary(grouping: records, by: \.normalizedLabel) + // Merged in: a contest not in the list (one open on its own screen + // after it closed) keeps the history it has. + var voted = votedProTxHashesByContest + var histories = voteHistoryByContest + for label in labels { + (voted[label], histories[label]) = rebuiltHistory(of: label, from: byLabel[label] ?? []) + } + votedProTxHashesByContest = voted + voteHistoryByContest = histories + } + + /// Re-resolve which nodes this wallet can vote with, and nothing else. + /// + /// The voting-key screens call this after adding or removing a key. A full + /// ``refresh()`` would also re-query every open contest over the network, + /// which a key change does not affect. + func refreshVotableNodes() { + let resolution = nodes.votableNodes() + nodeListSynced = nodes.isNodeListSynced + votableNodes = resolution.nodes + nodeListMayBeIncomplete = resolution.mayBeIncomplete + + // Settle the remembered selection against the nodes that actually + // exist now, so the picker and the "voting with" row agree with what a + // tap would really do. + // + // Only when the node list actually resolved. `votableNodes()` returns + // empty while the SDK is starting or the masternode phase has not + // synced, and settling against that would compute an empty selection + // and PERSIST it — destroying a multi-node choice the user made, with + // the next vote silently falling back to one node. + if !votableNodes.isEmpty { + let settled = effectiveSelectedNodeIDs + if settled != selectedNodeIDs { + selectedNodeIDs = settled + } + } + } + + /// Re-read one contest's tallies after voting on it, so the row reflects + /// the vote without a full refresh. + /// + /// A contest that has since resolved is recorded in ``closedLabels``, so no + /// vote can start on it, and keeps its row until its voting end. A refresh + /// that fails or finds no contenders keeps the row until its voting end has + /// passed. + func refreshContest(normalizedLabel: String) async { + await serially { [weak self] in await self?.performRefreshContest(normalizedLabel: normalizedLabel) } + } + + private func performRefreshContest(normalizedLabel: String) async { + let state: DPNSContestVoteState? + do { + state = try await contestsReader.voteState(normalizedLabel: normalizedLabel) + } catch { + // The query failed, so we learned nothing about this contest. + // Leave the cached row exactly as it was rather than treating a + // network blip as a resolution. + return + } + + // No contenders: the row keeps its last known votes until its voting + // end, then the refresh drops it. + guard let state else { + if let end = contests.first(where: { $0.normalizedLabel == normalizedLabel })?.endTime, + end <= now() { + close(normalizedLabel: normalizedLabel) + } + return + } + + guard !state.isResolved else { + if let end = contests.first(where: { $0.normalizedLabel == normalizedLabel })?.endTime, end > now() { + closedLabels.insert(normalizedLabel) + } else { + close(normalizedLabel: normalizedLabel) + } + return + } + + guard let index = contests.firstIndex(where: { $0.normalizedLabel == normalizedLabel }) + else { return } + + let existing = contests[index] + contests[index] = DPNSContest( + normalizedLabel: existing.normalizedLabel, + endTime: existing.endTime, + hasWinner: false, + abstainVotes: state.abstainVotes, + lockVotes: state.lockVotes, + contenders: state.contenders, + // The vote state carries no requested spellings; without these the + // row would fall back to the normalized label ("p1zza") after a vote. + requestedLabels: existing.requestedLabels) + } + + private func close(normalizedLabel: String) { + contests.removeAll { $0.normalizedLabel == normalizedLabel } + closedLabels.insert(normalizedLabel) + } + + // MARK: Sending + + func isSending(normalizedLabel: String) -> Bool { + sendingLabels.contains(normalizedLabel) + } + + /// Clears the previous attempt's outcome. + func beginAttempt() { + outcome = nil + } + + /// Casts `choice` on `contest` with `nodes` and sets ``outcome``. + /// + /// Returns once the caster has finished, the contest's history is rebuilt + /// from the store's rows plus the unrecorded casts this store keeps, and its + /// tallies are re-read. Both go through the load queue, so a load that read + /// before the cast cannot land after it. A second send on a contest already + /// in flight returns without casting. + func send(choice: VoteChoice, on contest: DPNSContest, from nodes: [VoterNode]) async { + let label = contest.normalizedLabel + guard sendingLabels.insert(label).inserted else { return } + beginAttempt() + defer { sendingLabels.remove(label) } + + let report: VoteCastReport + let startedAt = now() + do { + report = try await caster.cast(choice: choice, onNormalizedLabel: label, with: nodes) + } catch { + // Platform's answer for a contest a full refresh left out: it is + // closed, so no vote starts on it again. The row stays until its + // voting end. Through the load queue, so a full refresh asked for + // before this answer cannot list the contest open again. + if case MasternodeVoteCaster.CastError.contestClosed = error { + await serially { [weak self] in _ = self?.closedLabels.insert(label) } + } + outcome = .failure(VoteErrorMessage.plain(for: error)) + return + } + + let castAt = now() + let unrecorded = report.succeeded.filter { !$0.historyRecorded }.map { + CastVoteRecord(proTxHash: $0.node.proTxHash, normalizedLabel: label, choice: report.choice, castAt: castAt) + } + unrecordedCasts[label, default: []].append(contentsOf: unrecorded) + await serially { [weak self] in + guard let self else { return } + // Without a readable store, patch what is known instead. + if await !self.performLoadVotedNodes(for: label) { + self.applyRecordedVotes(of: report, on: label, at: castAt, startedAt: startedAt) + } + } + await refreshContest(normalizedLabel: label) + + if report.isCompleteSuccess { + outcome = .success(.voted(username: contest.displayTitle)) + } else if report.succeeded.isEmpty { + outcome = .failure(report.failed.first?.failure + ?? NSLocalizedString("The vote was not cast. Please try again.", comment: "Voting")) + } else { + outcome = .mixed(report) + } + } + + // MARK: Vote history + + /// Whether this contest's vote history is known yet. Callers disable the + /// vote control until it is, rather than acting on an unknown. + func hasLoadedVoteHistory(for normalizedLabel: String) -> Bool { + votedProTxHashesByContest[normalizedLabel] != nil + } + + /// Load which of our nodes already voted on one contest. Called when its + /// detail screen opens, so the vote button knows what is left. + func loadVotedNodes(for normalizedLabel: String) async { + await serially { [weak self] in await self?.performLoadVotedNodes(for: normalizedLabel) } + } + + /// `false` when the store could not be read. + @discardableResult + private func performLoadVotedNodes(for normalizedLabel: String) async -> Bool { + // A failed read leaves what was known: an empty history would offer + // nodes for votes they already hold. + guard let records = await history.votes( + forContest: normalizedLabel, + network: MasternodeVoteCaster.networkKey) + else { return false } + (votedProTxHashesByContest[normalizedLabel], voteHistoryByContest[normalizedLabel]) = + rebuiltHistory(of: normalizedLabel, from: records) + return true + } + + /// One contest's history from the store's rows plus the casts this store keeps + /// that landed without a row. + private func rebuiltHistory(of normalizedLabel: String, from records: [CastVoteRecord]) -> (Set, VoteLimit) { + let unrecorded = unrecordedCasts[normalizedLabel] ?? [] + var limit = VoteLimit(records) + for cast in unrecorded { + limit.recordCast(of: cast.proTxHash, on: normalizedLabel, choice: cast.choice, at: cast.castAt) + } + return (Set(records.map(\.proTxHash)).union(unrecorded.map(\.proTxHash)), limit) + } + + /// Adds the votes `report` says landed to the contest's known history. + /// Nothing when the history is not known yet: it stays unknown until the + /// next history load, which adds the unrecorded ones back. A node whose + /// history already holds a cast from `startedAt` on was counted by a load + /// that ran while the vote was in flight, so it is not counted again. + private func applyRecordedVotes( + of report: VoteCastReport, on normalizedLabel: String, at castAt: Date, startedAt: Date + ) { + guard var contestHistory = voteHistoryByContest[normalizedLabel] else { return } + let uncounted = report.succeeded.filter { !contestHistory.hasCast(of: $0.node.proTxHash, since: startedAt) } + for outcome in uncounted { + contestHistory.recordCast( + of: outcome.node.proTxHash, on: normalizedLabel, choice: report.choice, at: castAt) + } + voteHistoryByContest[normalizedLabel] = contestHistory + votedProTxHashesByContest[normalizedLabel, default: []] + .formUnion(report.succeeded.map(\.node.proTxHash)) + } + + /// Nodes that have not yet voted on this contest, in registration order. + /// + /// Empty until this contest's history has loaded. The screen evaluates this + /// before its `.task` completes, and treating "not loaded" as "nobody + /// voted" would offer nodes that already voted — a duplicate Platform + /// rejects, spending one of the masternode's per-contest votes. + func nodesYetToVote(on normalizedLabel: String) -> [VoterNode] { + guard let voted = votedProTxHashesByContest[normalizedLabel] else { return [] } + return votableNodes.filter { !voted.contains($0.proTxHash) } + } + + /// How many of this wallet's nodes have a live vote here — nodes, not + /// records. A node that changed its mind has two records and is still one + /// node, which is what "%d of %d nodes voted" is counting. + func votedNodeCount(on normalizedLabel: String) -> Int { + votedProTxHashesByContest[normalizedLabel]?.count ?? 0 + } + + /// This node's live choice on this contest, when it has one. + func liveChoice(of node: VoterNode, on normalizedLabel: String) -> VoteChoice? { + voteHistoryByContest[normalizedLabel]?.liveChoice(of: node.proTxHash) + } + + /// The nodes a tap on `choice` should cast with: the remembered selection, + /// minus nodes already holding that exact choice (Platform rejects a + /// duplicate) and minus nodes that have spent the five casts it allows per + /// contest. A node holding a *different* choice belongs here — replacing + /// its vote is one state transition, and it is the whole point of being + /// able to change your mind from this screen. + func nodesForVote(_ choice: VoteChoice, on normalizedLabel: String) -> [VoterNode] { + guard hasLoadedVoteHistory(for: normalizedLabel) else { return [] } + let chosen = effectiveSelectedNodeIDs + let history = voteHistoryByContest[normalizedLabel] ?? VoteLimit([]) + return votableNodes.filter { node in + guard chosen.contains(node.proTxHash) else { return false } + guard (history.votesLeft(node.proTxHash) ?? 0) > 0 else { return false } + return history.liveChoice(of: node.proTxHash) != choice + } + } + + /// The nodes cancelling `held` should abstain with: the remembered + /// selection's nodes whose live choice is `held` and that have a vote left. + /// A node holding anything else is not touched (AC-17). + func nodesToCancel(_ held: VoteChoice, on normalizedLabel: String) -> [VoterNode] { + nodesForVote(.abstain, on: normalizedLabel).filter { liveChoice(of: $0, on: normalizedLabel) == held } + } + + /// What the cast sheet offers for a vote, and why ticked nodes are missing. + struct CastCandidates { + /// The nodes the vote can be cast with. + let nodes: [VoterNode] + /// Ticked nodes left out because they already hold this choice. + let holdingThisChoice: Int + /// Ticked nodes left out because they have no casts left here. + let outOfCasts: Int + } + + /// The cast sheet's nodes for `choice`: ``nodesForVote(_:on:)``, or + /// ``nodesToCancel(_:on:)`` when the vote takes `cancelling` back. The + /// counts cover the ticked nodes only — when cancelling, only the ticked + /// holders of `cancelling` — so a node the user never ticked is not + /// reported as out of votes. + func castCandidates(for choice: VoteChoice, cancelling: VoteChoice?, on normalizedLabel: String) -> CastCandidates { + let offered = cancelling.map { nodesToCancel($0, on: normalizedLabel) } + ?? nodesForVote(choice, on: normalizedLabel) + let ticked = effectiveSelectedNodeIDs + let considered = votableNodes.filter { node in + guard ticked.contains(node.proTxHash) else { return false } + guard let cancelling else { return true } + return liveChoice(of: node, on: normalizedLabel) == cancelling + } + let holding = considered.filter { liveChoice(of: $0, on: normalizedLabel) == choice }.count + return CastCandidates( + nodes: offered, + holdingThisChoice: holding, + outOfCasts: max(0, considered.count - offered.count - holding)) + } + + /// Whether a tap on `choice` may start a vote on this contest: the key flow + /// when the wallet has no node, otherwise only once the contest's history + /// is known and some selected node can still cast that choice — not one + /// already holding it, not one out of casts. One rule for the list and the + /// contest screen. + func canStartVote(_ choice: VoteChoice, on normalizedLabel: String) -> Bool { + guard !isClosed(normalizedLabel: normalizedLabel) else { return false } + guard canVote else { return true } + return !nodesForVote(choice, on: normalizedLabel).isEmpty + } + + /// The choices the ticked nodes currently hold on a contest, from local + /// history. Empty when none of them voted, when no node is ticked, or + /// before the history loaded (or when it could not be read). + func myChoices(on normalizedLabel: String) -> Set { + guard let ticked = tickedNodeIDs, let history = voteHistoryByContest[normalizedLabel] else { return [] } + var choices = history.filledChoices(of: ticked) ?? [] + if let abstainers = history.nodes(holding: .abstain, among: ticked), !abstainers.isEmpty { + choices.insert(.abstain) + } + return choices + } +} + +// MARK: - VoteAttemptOutcome + +/// How a vote attempt ended. +enum VoteAttemptOutcome { + /// Every masternode's vote landed. + case success(VotingToast) + /// Nothing landed; the reason in plain words. + case failure(String) + /// Some votes landed and some did not; the report lists each masternode. + case mixed(VoteCastReport) +} diff --git a/DashWallet/Sources/UI/DashPay/Voting/UsernameVotingScreen.swift b/DashWallet/Sources/UI/DashPay/Voting/UsernameVotingScreen.swift index c77a8c8495..0750976e0e 100644 --- a/DashWallet/Sources/UI/DashPay/Voting/UsernameVotingScreen.swift +++ b/DashWallet/Sources/UI/DashPay/Voting/UsernameVotingScreen.swift @@ -35,15 +35,23 @@ struct UsernameVotingScreen: View { /// explicitly — SwiftUI cannot see the UIKit stack underneath it. let onClose: () -> Void - @StateObject private var viewModel = VotingViewModel() + @StateObject private var viewModel: VotingViewModel @State private var showingNodePicker = false @State private var showingFilters = false /// Where the voting-key flow opens, while it is shown. @State private var keyFlowStart: VotingKeysFlow.Start? /// A vote started from a pill, handed to ``View/voteFlow(_:viewModel:)``. @State private var voteRequest: VoteFlowRequest? - /// The contest opened from a row. + /// The contest opened from a row's context menu. @State private var openedContest: OpenedContest? + /// The request opened from a row. + @State private var openedRequest: OpenedRequest? + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + private struct OpenedRequest: Hashable { + let normalizedLabel: String + let identityId: String + } /// A contest pushed from the list, identified by its label so the /// destination keeps its snapshot while it pops. @@ -53,6 +61,14 @@ struct UsernameVotingScreen: View { func hash(into hasher: inout Hasher) { hasher.combine(contest.normalizedLabel) } } + init(onClose: @escaping () -> Void, viewModel: VotingViewModel? = nil) { + self.onClose = onClose + _viewModel = StateObject(wrappedValue: viewModel ?? VotingViewModel()) + } + + private var store: VotingStore { viewModel.store } + private var list: VotingListViewModel { viewModel.list } + private var screenTitle: String { NSLocalizedString("Username Voting", comment: "Voting") } var body: some View { @@ -73,7 +89,7 @@ struct UsernameVotingScreen: View { .padding(.top, 20) DashUIKit.SearchBar( - text: $viewModel.searchQuery, + text: Binding(get: { list.searchQuery }, set: { list.searchQuery = $0 }), placeholder: NSLocalizedString("Search by username", comment: "Voting")) .padding(.top, 20) @@ -111,19 +127,23 @@ struct UsernameVotingScreen: View { } .safeAreaInset(edge: .bottom, spacing: 0) { DashUIKit.FilterBar( - value: viewModel.filter.sort.title, + value: list.filter.sort.title, title: NSLocalizedString("Filtered by", comment: "Voting"), filterAccessibilityLabel: NSLocalizedString("Filter", comment: "Voting"), - replacement: viewModel.toast.map(\.view)) { + replacement: list.toast.map(\.view)) { showingFilters = true } } .sheet(isPresented: $showingFilters) { - VotingFiltersSheet(filter: viewModel.filter) { viewModel.filter = $0 } + VotingFiltersSheet(filter: list.filter) { list.filter = $0 } } .navigationDestination(item: $openedContest) { opened in ContestDetailScreen(contest: opened.contest, viewModel: viewModel) } + .navigationDestination(item: $openedRequest) { opened in + RequestDetailsScreen( + voting: viewModel, normalizedLabel: opened.normalizedLabel, identityId: opened.identityId) + } .voteFlow($voteRequest, viewModel: viewModel) .sheet(isPresented: $showingNodePicker) { VotingNodeSelectionSheet( @@ -138,17 +158,17 @@ struct UsernameVotingScreen: View { viewModel: viewModel, onFinish: { _ in keyFlowStart = nil }) } - .task { await viewModel.refreshIfNeeded() } - .refreshable { await viewModel.refresh() } + .task { await store.refreshIfNeeded() } + .refreshable { await store.refresh() } // "Voting ends today / in N days" is relative to today. // Midnight and time-zone changes, delivered on return if they happened // while the app was suspended. .onReceive(NotificationCenter.default.publisher(for: UIApplication.significantTimeChangeNotification)) { _ in - viewModel.recomputeVisible() + list.recomputeVisible() } // The toast appears where VoiceOver is not looking; say it. - .onChange(of: viewModel.toast?.id) { - if let message = viewModel.toast?.message { + .onChange(of: list.toast?.id) { + if let message = list.toast?.message { AccessibilityNotification.Announcement(message).post() } } @@ -161,15 +181,15 @@ struct UsernameVotingScreen: View { VStack(alignment: .leading, spacing: 1) { // The filter's type and how many open contests it keeps, // whatever the search narrows the list to. - Text(viewModel.filter.title) + Text(list.filter.title) .dashFont(.headline) .foregroundStyle(Color.dash.primaryText) // No count while the type reads this wallet's votes and they // are not known for every contest: it would not be a count. - if !viewModel.filter.type.readsMyVotes || viewModel.myVotesKnownForList { + if !list.filter.type.readsMyVotes || list.myVotesKnownForList { Text(String.localizedStringWithFormat( NSLocalizedString("%d usernames", comment: "Voting"), - viewModel.filterMatchCount)) + list.filterMatchCount)) .dashFont(.footnote) .foregroundStyle(Color.dash.tertiaryText) } @@ -214,12 +234,12 @@ struct UsernameVotingScreen: View { /// No node to vote with, and the node list is complete — while it may be /// incomplete, its own banner says so instead of "no voting keys". private var showsBrowseOnly: Bool { - viewModel.hasLoadedOnce && !viewModel.canVote && !viewModel.nodeListMayBeIncomplete + store.hasLoadedOnce && !viewModel.canVote && !store.nodeListMayBeIncomplete } private var hasBanners: Bool { - showsBrowseOnly || viewModel.nodeListMayBeIncomplete || viewModel.loadError != nil - || viewModel.historyUnavailable + showsBrowseOnly || store.nodeListMayBeIncomplete || list.loadState == .contests(refreshFailed: true) + || store.historyUnavailable } private var banners: some View { @@ -236,7 +256,7 @@ struct UsernameVotingScreen: View { action: (NSLocalizedString("Add masternode voting key", comment: "Voting"), { keyFlowStart = .addKey }), isRounded: true) } - if viewModel.nodeListMayBeIncomplete { + if store.nodeListMayBeIncomplete { VotingBanner( text: NSLocalizedString( "Some of your masternodes may be missing from this list — the wallet could not read your full voting-key pool. Finish syncing and reopen this screen.", @@ -244,12 +264,21 @@ struct UsernameVotingScreen: View { tone: .warning, isRounded: true) } - if let loadError = viewModel.loadError { - VotingBanner(text: loadError, tone: .error, isRounded: true) + // Rows are on screen: keep them and offer a retry above them. With + // nothing cached the full-screen message says it instead. + // No Try again while the retry runs; it comes back if that fails too. + if let refreshFailed = list.refreshFailedText { + VotingBanner( + text: refreshFailed, + tone: .error, + action: store.isRefreshing + ? nil + : (NSLocalizedString("Try again", comment: "Voting"), { retryLoad() }), + isRounded: true) } // Without the history the list cannot tell which votes are cast, // so it holds the vote controls back; say why. - if viewModel.historyUnavailable { + if store.historyUnavailable { VotingBanner( text: NSLocalizedString( "Couldn't read your vote history, so voting is paused. Pull down to try again.", @@ -289,69 +318,62 @@ struct UsernameVotingScreen: View { } } + private func retryLoad() { + Task { await store.retry() } + } + @ViewBuilder private var contestList: some View { - if !viewModel.hasLoadedOnce { + switch list.emptyState { + case .loading: SwiftUI.ProgressView() .frame(maxWidth: .infinity) .padding(.vertical, 40) - } else if viewModel.visibleContests.isEmpty && viewModel.loadError != nil && viewModel.contests.isEmpty { + case .couldNotLoad: // The load failed and nothing is cached: say so, rather than that // nothing is being contested — that was never checked. VotingEmptyState( icon: "exclamationmark.triangle", title: NSLocalizedString("Couldn't load the contests", comment: "Voting"), - message: NSLocalizedString("Pull down to try again.", comment: "Voting")) + message: NSLocalizedString("Pull down to try again.", comment: "Voting"), + action: ( + title: NSLocalizedString("Try again", comment: "Voting"), + perform: { retryLoad() })) .padding(.vertical, 40) - } else if viewModel.visibleContests.isEmpty && !viewModel.contests.isEmpty - && viewModel.filter.type.readsMyVotes, - let reason = viewModel.myVotesUnavailableReason { - // The type needs this wallet's votes, which cannot be told right - // now. Not the filter's fault. + case .cannotFilterByMyVotes(let reason): VotingEmptyState( icon: "exclamationmark.triangle", title: NSLocalizedString("Can't filter by your votes right now", comment: "Voting"), message: reason, action: ( title: NSLocalizedString("Reset filters", comment: "Voting"), - perform: { viewModel.filter = .default })) + perform: { list.filter = .default })) .padding(.vertical, 40) - } else if viewModel.visibleContests.isEmpty && !viewModel.contests.isEmpty - && viewModel.filter.type.readsMyVotes && !viewModel.myVotesKnownForList { - // This wallet's history is still loading for some contests, so - // neither the filter nor a search can say yet that nothing matches. - SwiftUI.ProgressView() - .frame(maxWidth: .infinity) - .padding(.vertical, 40) - } else if viewModel.visibleContests.isEmpty && !viewModel.contests.isEmpty - && viewModel.filterMatchCount == 0 - && (!viewModel.filter.type.readsMyVotes || viewModel.myVotesKnownForList) { - // Open contests exist and the filter alone hides them all; when it - // is the search, the search's empty state below says so. + case .filterMatchesNothing: VotingEmptyState( icon: "line.3.horizontal.decrease.circle", title: NSLocalizedString("No usernames match this filter", comment: "Voting"), message: NSLocalizedString("Change the filter or reset it to see every open contest.", comment: "Voting"), action: ( title: NSLocalizedString("Reset filters", comment: "Voting"), - perform: { viewModel.filter = .default })) + perform: { list.filter = .default })) + .padding(.vertical, 40) + case .noContests: + VotingEmptyState( + icon: "checkmark.seal", + title: NSLocalizedString("No open contests", comment: "Voting"), + message: NSLocalizedString( + "No usernames are being contested right now. Contests open when two or more people request the same name.", + comment: "Voting")) .padding(.vertical, 40) - } else if viewModel.visibleContests.isEmpty { + case .searchMatchesNothing: VotingEmptyState( icon: "checkmark.seal", - title: viewModel.searchQuery.isEmpty - ? NSLocalizedString("No open contests", comment: "Voting") - : NSLocalizedString("No matching contests", comment: "Voting"), - message: viewModel.searchQuery.isEmpty - ? NSLocalizedString( - "No usernames are being contested right now. Contests open when two or more people request the same name.", - comment: "Voting") - : NSLocalizedString( - "No open contest matches that search.", - comment: "Voting")) + title: NSLocalizedString("No matching contests", comment: "Voting"), + message: NSLocalizedString("No open contest matches that search.", comment: "Voting")) .padding(.vertical, 40) - } else { - ForEach(viewModel.sections) { section in + case nil: + ForEach(list.sections) { section in Text(section.title) .dashFont(.footnote) .foregroundStyle(Color.dash.tertiaryText) @@ -372,11 +394,31 @@ struct UsernameVotingScreen: View { let label = contest.normalizedLabel return VotingContestCard( contest: contest, - myChoices: viewModel.myChoices(on: label), - isCasting: viewModel.castingLabels.contains(label), - canStartVote: { viewModel.canStartVote($0, on: label) }, - onVote: { choice in voteRequest = VoteFlowRequest(contest: contest, choice: choice) }, - onOpen: { openedContest = OpenedContest(contest: contest) }) + myChoices: store.myChoices(on: label), + isCasting: store.isSending(normalizedLabel: label), + canTapPill: { list.canTapPill($0, on: label) }, + onVote: { voteRequest = list.voteRequest(for: $0, on: contest) }, + onOpenRequest: { openedRequest = OpenedRequest(normalizedLabel: label, identityId: $0) }, + onOpenOutcomes: { openedContest = OpenedContest(contest: contest) }, + headerHint: list.headerAccessibilityHint(for: contest), + expansion: list.isExpandable(contest) ? expansion(for: contest) : nil) + } + + private func expansion(for contest: DPNSContest) -> VotingContestCard.Expansion { + let label = contest.normalizedLabel + let isExpanded = list.isExpanded(label) + return VotingContestCard.Expansion( + isExpanded: isExpanded, + countText: list.requestCountText(for: contest), + pillLabel: list.expandAccessibilityLabel(for: contest, isExpanded: isExpanded), + pillValue: list.expandAccessibilityValue(for: contest), + requests: list.requestRows(for: contest), + // The card grows or shrinks while the requests fade, in one + // transaction with the chevron and «You voted»; under Reduce + // Motion the row opens and closes at once. + onToggle: { + withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.25)) { list.toggleExpanded(label) } + }) } } @@ -494,3 +536,149 @@ struct VotingBanner: View { } } } + +// MARK: - Previews + +#if DEBUG +// Shared by the voting screens' previews (CastVoteSheet too). +struct PreviewContests: VotingContestReading { + let contests: [DPNSContest] + var failure: Error? + /// Answers the first load, then fails every later one. + var failAfterFirstLoad = false + private let loaded = PreviewLoadCounter() + + init(contests: [DPNSContest], failure: Error? = nil, failAfterFirstLoad: Bool = false) { + self.contests = contests + self.failure = failure + self.failAfterFirstLoad = failAfterFirstLoad + } + + func activeContests() async throws -> [DPNSContest] { + if let failure { throw failure } + if failAfterFirstLoad, loaded.next() > 1 { throw VotingPreviewError.unavailable } + return contests + } + + func voteState(normalizedLabel: String) async throws -> DPNSContestVoteState? { nil } +} + +private final class PreviewLoadCounter { + private var count = 0 + func next() -> Int { count += 1; return count } +} + +struct PreviewNodes: VotableMasternodeResolving { + var nodes: [VoterNode] = [] + var mayBeIncomplete = false + var isNodeListSynced = true + + func votableNodes() -> MasternodeVoterRegistry.Resolution { + .init(nodes: nodes, mayBeIncomplete: mayBeIncomplete) + } +} + +struct PreviewCaster: VoteCasting { + func cast(choice: VoteChoice, onNormalizedLabel normalizedLabel: String, with nodes: [VoterNode]) async throws + -> VoteCastReport { + throw VotingPreviewError.unavailable + } +} + +final class PreviewHistory: VoteHistoryDAO { + private let records: [CastVoteRecord] + + init(records: [CastVoteRecord] = []) { + self.records = records + } + + func record(_ record: CastVoteRecord, network: String) async throws {} + func votes(forContest normalizedLabel: String, network: String) async -> [CastVoteRecord]? { + records.filter { $0.normalizedLabel == normalizedLabel } + } + func votes(forContests normalizedLabels: Set, network: String) async -> [CastVoteRecord]? { + records.filter { normalizedLabels.contains($0.normalizedLabel) } + } + func deleteAll() {} +} + +final class PreviewPrefs: VotingSelectionStoring { + var votingNodeSelection: Set + + init(selection: Set = []) { + votingNodeSelection = selection + } +} + +private enum VotingPreviewError: LocalizedError { + case unavailable + + var errorDescription: String? { "Dash Platform is not connected yet." } +} + +@MainActor +private func previewScreen( + contests: [DPNSContest], + nodes: [VoterNode] = [], + mayBeIncomplete: Bool = false, + failure: Error? = nil, + failAfterFirstLoad: Bool = false, + filterType: VotingTypeFilter = .all +) -> some View { + let store = VotingStore( + contests: PreviewContests(contests: contests, failure: failure, failAfterFirstLoad: failAfterFirstLoad), + nodes: PreviewNodes(nodes: nodes, mayBeIncomplete: mayBeIncomplete), + caster: PreviewCaster(), + history: PreviewHistory(), + prefs: PreviewPrefs()) + let viewModel = VotingViewModel(store: store) + viewModel.list.filter.type = filterType + return NavigationStack { + UsernameVotingScreen(onClose: {}, viewModel: viewModel) + } + // A second load, queued behind the screen's own first one, which fails. + .task { if failAfterFirstLoad { await store.refresh() } } +} + +private let previewEnd = Date(timeIntervalSince1970: 1_800_000_000) + +private let previewContests: [DPNSContest] = [ + DPNSContest(normalizedLabel: "johndoe", endTime: previewEnd, hasWinner: false, + abstainVotes: 0, lockVotes: 2, contenders: []), + DPNSContest(normalizedLabel: "a11ce", endTime: previewEnd.addingTimeInterval(3 * 86_400), hasWinner: false, + abstainVotes: 1, lockVotes: 0, contenders: []), + DPNSContest(normalizedLabel: "somelongusernamethatkeepsgoingandgoing", endTime: nil, hasWinner: false, + abstainVotes: 0, lockVotes: 0, contenders: []), +] + +private let previewNode = VoterNode( + proTxHash: Data([1]), isEvonode: false, typeIndex: 1, serviceAddress: nil, keySource: .walletIndex(0)) + +#Preview("Loaded") { + previewScreen(contests: previewContests, nodes: [previewNode]) +} + +#Preview("No open contests") { + previewScreen(contests: [], nodes: [previewNode]) +} + +#Preview("Node list may be incomplete") { + previewScreen(contests: previewContests, mayBeIncomplete: true) +} + +#Preview("Load failed") { + previewScreen(contests: [], failure: VotingPreviewError.unavailable) +} + +#Preview("Refresh failed with rows") { + previewScreen(contests: previewContests, nodes: [previewNode], failAfterFirstLoad: true) +} + +#Preview("Filter matches nothing") { + previewScreen(contests: previewContests, nodes: [previewNode], filterType: .approved) +} + +#Preview("Can't filter by your votes") { + previewScreen(contests: previewContests, filterType: .notVoted) +} +#endif diff --git a/DashWallet/Sources/UI/DashPay/Voting/VoteFlow.swift b/DashWallet/Sources/UI/DashPay/Voting/VoteFlow.swift index 3a48a520b2..d9aaeb1746 100644 --- a/DashWallet/Sources/UI/DashPay/Voting/VoteFlow.swift +++ b/DashWallet/Sources/UI/DashPay/Voting/VoteFlow.swift @@ -24,10 +24,13 @@ import SwiftUI /// A vote the user asked for from a screen: which contest and which choice. /// `choice` is `nil` when the user only asked to add a voting key. +/// `cancelling` is the choice an abstain takes back: only the nodes holding it +/// cast (AC-17). struct VoteFlowRequest: Identifiable { let id = UUID() let contest: DPNSContest let choice: VoteChoice? + var cancelling: VoteChoice? } extension View { @@ -68,6 +71,7 @@ private struct VoteFlowModifier: ViewModifier { CastVoteSheet( contest: viewModel.latest(request.contest), choice: choice, + cancelling: request.cancelling, viewModel: viewModel) } } diff --git a/DashWallet/Sources/UI/DashPay/Voting/VotingContestCard.swift b/DashWallet/Sources/UI/DashPay/Voting/VotingContestCard.swift index bed65b3fc5..56632881ef 100644 --- a/DashWallet/Sources/UI/DashPay/Voting/VotingContestCard.swift +++ b/DashWallet/Sources/UI/DashPay/Voting/VotingContestCard.swift @@ -27,23 +27,53 @@ import SwiftUI /// /// A name with one request shows its block (lock) and approve counts as vote /// pills. A name with several requests shows how many, its block count and a -/// chevron that opens the contest, where each request is listed. The pill that -/// carries this wallet's vote is filled. +/// chevron that opens the row in place, listing each request with its own +/// approve pill. The pill that carries this wallet's vote is filled. struct VotingContestCard: View { let contest: DPNSContest /// The choices this wallet's nodes hold on the contest. let myChoices: Set /// A vote on this contest is being sent. let isCasting: Bool - /// Whether a tap on this choice may start a vote (it may lead to the key flow). - let canStartVote: (VoteChoice) -> Bool + /// Whether a tap on this choice's pill can start anything: a vote (it may + /// lead to the key flow) or, on a filled pill, taking that vote back. + let canTapPill: (VoteChoice) -> Bool let onVote: (VoteChoice) -> Void - let onOpen: () -> Void + /// Opens one request's details, by its identity. + let onOpenRequest: (_ identityId: String) -> Void + /// Opens the contest screen with every outcome (the row's context menu). + let onOpenOutcomes: () -> Void + /// What a tap on the name does, for VoiceOver. + let headerHint: String + /// The open-in-place state of a several-request name; `nil` for one request. + var expansion: Expansion? + + /// What a several-request row shows and speaks, computed by the list's view model. + struct Expansion { + let isExpanded: Bool + let countText: String + let pillLabel: String + let pillValue: String + let requests: [VotingRequestRow] + let onToggle: () -> Void + } - /// A vote of this wallet's that no pill on the row carries. private var hasVoteWithoutPill: Bool { - var carried: Set = [.lock] - if let sole { carried.insert(.towards(identityId: sole.identityId)) } + Self.hasVoteWithoutPill(myChoices, contenders: contest.contenders, isExpanded: expansion?.isExpanded ?? false) + } + + /// A vote of this wallet's that no pill on the row carries. An abstain is + /// not one: it takes a vote back, and the name is listed under + /// "I have not voted" (AC-07). + static func hasVoteWithoutPill( + _ myChoices: Set, + contenders: [DPNSContender], + isExpanded: Bool + ) -> Bool { + var carried: Set = [.lock, .abstain] + if contenders.count == 1 || isExpanded { + carried.formUnion(contenders.map { .towards(identityId: $0.identityId) }) + } return !myChoices.subtracting(carried).isEmpty } @@ -52,8 +82,33 @@ struct VotingContestCard: View { } var body: some View { + VStack(spacing: 0) { + header + if let expansion, expansion.isExpanded { + ForEach(expansion.requests, id: \.identityId) { request in + requestRow(request) + } + .transition(.opacity) + } + } + .padding(.vertical, 8) + .modifier(MenuViewModifier(shadowRadius: 20)) + } + + /// One request opens its details; several open in place. + private func openHeader() { + if let sole { + onOpenRequest(sole.identityId) + } else if let expansion { + expansion.onToggle() + } else { + onOpenOutcomes() + } + } + + private var header: some View { HStack(spacing: 20) { - Button(action: onOpen) { + Button(action: openHeader) { VStack(alignment: .leading, spacing: 0) { Text(contest.displayTitle) .dashFont(.subheadMedium) @@ -71,20 +126,19 @@ struct VotingContestCard: View { .lineLimit(1) .truncationMode(.middle) } - if contest.contenders.count > 1 { - Text(String.localizedStringWithFormat( - NSLocalizedString("%d requests", comment: "Voting"), - contest.contenders.count)) + if let expansion { + Text(expansion.countText) .dashFont(.footnote) .foregroundStyle(Color.dash.tertiaryText) } // A vote no pill on this row carries (an approve on a - // several-request name, an abstain anywhere): say it, so - // the name does not read as still to vote on. + // collapsed several-request name): say it, so the name + // does not read as still to vote on. if hasVoteWithoutPill { Text(NSLocalizedString("You voted", comment: "Voting")) .dashFont(.footnoteMedium) .foregroundStyle(Color.dash.blueText) + .transition(.opacity) } } .padding(.leading, 4) @@ -92,25 +146,70 @@ struct VotingContestCard: View { .contentShape(Rectangle()) } .buttonStyle(.plain) - .accessibilityHint(NSLocalizedString("Opens the requests for this name", comment: "Voting")) + .accessibilityHint(headerHint) + .contextMenu { + Button(NSLocalizedString("All outcomes", comment: "Voting"), action: onOpenOutcomes) + } HStack(spacing: 10) { pill(.block, count: contest.lockVotes, choice: .lock) if let sole { pill(.approve, count: sole.voteTally, choice: .towards(identityId: sole.identityId)) - } else if contest.contenders.count > 1 { + } else if let expansion { VotePill( - kind: .expand(isExpanded: false), - accessibilityLabel: String( - format: NSLocalizedString("Show requests for %@", comment: "Voting"), - contest.displayTitle), - action: onOpen) + kind: .expand(isExpanded: expansion.isExpanded), + accessibilityLabel: expansion.pillLabel, + accessibilityValue: expansion.pillValue, + action: expansion.onToggle) } } } .padding(.leading, 10) - .padding(.vertical, 8) - .modifier(MenuViewModifier(shadowRadius: 20)) + } + + /// One request of an open several-request name: its identity (the request + /// details open on tap) and its own approve pill. + private func requestRow(_ request: VotingRequestRow) -> some View { + let choice = VoteChoice.towards(identityId: request.identityId) + let status: VotePill.Status = isCasting ? .busy : (canTapPill(choice) ? .enabled : .disabled) + return HStack(spacing: 20) { + Button(action: { onOpenRequest(request.identityId) }) { + Text(request.identityId) + .dashFont(.footnote) + .monospaced() + .foregroundStyle(Color.dash.secondaryText) + .lineLimit(1) + .truncationMode(.middle) + .padding(.leading, 4) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(Text(request.spokenIdentity)) + .accessibilityHint(NSLocalizedString("Opens the request details", comment: "Voting")) + + VotePill( + kind: .approve, + count: request.votes, + isSelected: request.isMine, + status: status, + accessibilityLabel: request.accessibilityLabel, + accessibilityValue: isCasting + ? request.accessibilityValue + ", " + NSLocalizedString("Sending", comment: "Voting") + : request.accessibilityValue, + action: { onVote(choice) }) + .accessibilityHint(Self.pillAccessibilityHint(isSelected: request.isMine, status: status) ?? "") + } + .padding(.leading, 10) + .padding(.top, 8) + } + + /// VoiceOver's hint for a block or approve pill: a filled pill that can be + /// tapped takes my vote back (AC-17), which its label and selected trait do + /// not say. + static func pillAccessibilityHint(isSelected: Bool, status: VotePill.Status) -> String? { + guard isSelected, status == .enabled else { return nil } + return NSLocalizedString("Takes your vote back", comment: "Voting") } /// The pill's spoken vote count, by the locale's plural rules: «1 vote», «3 votes». @@ -123,16 +222,19 @@ struct VotingContestCard: View { ? String(format: NSLocalizedString("Block %@", comment: "Voting"), contest.displayTitle) : String(format: NSLocalizedString("Approve %@", comment: "Voting"), contest.displayTitle) let votes = Self.votesValue(count: count) + let isSelected = myChoices.contains(choice) + let status: VotePill.Status = isCasting ? .busy : (canTapPill(choice) ? .enabled : .disabled) return VotePill( kind: kind, count: Int(count), - isSelected: myChoices.contains(choice), - status: isCasting ? .busy : (canStartVote(choice) ? .enabled : .disabled), + isSelected: isSelected, + status: status, accessibilityLabel: label, accessibilityValue: isCasting ? votes + ", " + NSLocalizedString("Sending", comment: "Voting") : votes, action: { onVote(choice) }) + .accessibilityHint(Self.pillAccessibilityHint(isSelected: isSelected, status: status) ?? "") } } @@ -145,3 +247,51 @@ extension VotingToast { .id(id) } } + +// MARK: - Previews + +#if DEBUG +private enum CardPreview { + static func contest(requests: Int, label: String = "johndoe") -> DPNSContest { + DPNSContest( + normalizedLabel: label, endTime: nil, hasWinner: false, abstainVotes: 0, lockVotes: 3, + contenders: (1...requests).map { + DPNSContender(identityId: "identity\($0)Xk3vQ9mT2pLw8RzYb5NcHf7Ud4Ea", voteTally: UInt32($0 * 2)) + }) + } + + static func card( + _ contest: DPNSContest, expanded: Bool = false, mine: Int? = nil + ) -> some View { + let rows = contest.contenders.enumerated().map { index, contender in + VotingRequestRow(identityId: contender.identityId, votes: Int(contender.voteTally), isMine: index == mine) + } + let myChoices: Set = mine.map { [.towards(identityId: contest.contenders[$0].identityId)] } ?? [] + return VotingContestCard( + contest: contest, myChoices: myChoices, isCasting: false, + canTapPill: { _ in true }, onVote: { _ in }, onOpenRequest: { _ in }, onOpenOutcomes: {}, + headerHint: contest.contenders.count > 1 ? "Opens the requests for this name" : "Opens the request details", + expansion: contest.contenders.count > 1 + ? .init( + isExpanded: expanded, countText: "\(contest.contenders.count) requests", + pillLabel: (expanded ? "Hide" : "Show") + " requests for \(contest.displayTitle)", + pillValue: "\(contest.contenders.count) requests", requests: rows, onToggle: {}) + : nil) + .padding(16) + } +} + +#Preview("One request") { CardPreview.card(CardPreview.contest(requests: 1)) } +#Preview("Several collapsed") { CardPreview.card(CardPreview.contest(requests: 3)) } +#Preview("Several expanded") { CardPreview.card(CardPreview.contest(requests: 3), expanded: true) } +#Preview("My vote on request 2 of 3") { + CardPreview.card(CardPreview.contest(requests: 3), expanded: true, mine: 1) +} +#Preview("Long identity") { + CardPreview.card(CardPreview.contest(requests: 2, label: "averyveryveryverylongusernamethatwraps"), expanded: true) +} +#Preview("Dark") { + CardPreview.card(CardPreview.contest(requests: 3), expanded: true, mine: 0) + .preferredColorScheme(.dark) +} +#endif diff --git a/DashWallet/Sources/UI/DashPay/Voting/VotingFilter.swift b/DashWallet/Sources/UI/DashPay/Voting/VotingFilter.swift index f3aaad5c7b..2fdc924527 100644 --- a/DashWallet/Sources/UI/DashPay/Voting/VotingFilter.swift +++ b/DashWallet/Sources/UI/DashPay/Voting/VotingFilter.swift @@ -87,7 +87,8 @@ enum VotingTypeFilter: String, CaseIterable, Identifiable { return false } ?? false case .notVoted: - return myChoices?.isEmpty ?? false + // No record, or abstain only: neither blocks nor approves. + return myChoices?.allSatisfy { $0 == .abstain } ?? false case .hasBlockedVotes: return contest.lockVotes > 0 } diff --git a/DashWallet/Sources/UI/DashPay/Voting/VotingViewModel.swift b/DashWallet/Sources/UI/DashPay/Voting/VotingViewModel.swift index efcd16b127..d8d20b833d 100644 --- a/DashWallet/Sources/UI/DashPay/Voting/VotingViewModel.swift +++ b/DashWallet/Sources/UI/DashPay/Voting/VotingViewModel.swift @@ -24,147 +24,27 @@ import SwiftUI // MARK: - VotingViewModel -/// Backing model for the username-voting section. -/// -/// Owns the live contest list, the wallet's votable nodes, and the casting -/// flow. Everything it publishes comes from Platform or from the wallet's -/// on-chain masternode registrations — there is no local vote arithmetic and -/// no seeded data. +/// Backing model for the username-voting section's casting and voting-key +/// flows. The data every screen reads lives on ``store`` and the list's +/// presentation state on ``list``; this type composes them for the existing +/// screens and forwards their reads. @MainActor final class VotingViewModel: ObservableObject { + // MARK: Composition - // MARK: Published state + let store: VotingStore + let list: VotingListViewModel + private var changes = Set() - /// The *open* contests. A contest that resolves leaves this list. - @Published private(set) var contests: [DPNSContest] = [] { - didSet { recomputeVisible() } - } - /// Labels observed to have resolved while the user was looking at them, - /// so an already-open detail screen can say so instead of offering a vote - /// that can no longer be accepted. - @Published private(set) var closedLabels: Set = [] - @Published private(set) var votableNodes: [VoterNode] = [] { - didSet { - let ids = Set(votableNodes.map(\.proTxHash)) - guard ids != votableNodeIDs else { return } - votableNodeIDs = ids - // "I have approved / not voted" count only these nodes' votes. - recomputeIfFilteringByMyVotes() - } - } - /// ``votableNodes`` as a set, kept with it rather than rebuilt per row. - private(set) var votableNodeIDs: Set = [] - /// The wallet's voting-key pool could only be read at its shallow - /// fallback depth and some active registration went unmatched, so a node - /// you can actually vote with may be missing from ``votableNodes``. - @Published private(set) var nodeListMayBeIncomplete = false { - didSet { if nodeListMayBeIncomplete != oldValue { recomputeIfFilteringByMyVotes() } } - } - @Published private(set) var isLoading = false - /// Set when a refresh fails. The list keeps showing the last good data. - @Published private(set) var loadError: String? - /// `false` until the first refresh completes, so the empty state is not - /// shown while the first fetch is still in flight. - @Published private(set) var hasLoadedOnce = false - - @Published var searchQuery: String = "" { - didSet { - normalizedNeedle = contestsService.normalizedLabel( - for: searchQuery.trimmingCharacters(in: .whitespacesAndNewlines)) - recomputeVisible() - } - } - /// The search query, homograph-normalized once per edit rather than on - /// every recompute of the list. - private var normalizedNeedle: String? - @Published var filter: VotingFilter = .default { - didSet { - guard filter != oldValue else { return } - recomputeVisible() - } - } - - /// Contests matching the search box and the filter, in the filter's order. - /// Recomputed when the contests, the search, the filter or this wallet's - /// votes change — not on every render, since matching a search normalizes - /// it through the SDK. - @Published private(set) var visibleContests: [DPNSContest] = [] - /// How many open contests the filter keeps, whatever the search narrows - /// the list to: the count next to the filter's name in the header. - @Published private(set) var filterMatchCount = 0 - /// Whether the types that read this wallet's votes can classify every - /// listed contest: the votes can be told, and each contest's history has - /// loaded. Until then their count and an empty list say nothing. - @Published private(set) var myVotesKnownForList = false - /// ``visibleContests`` grouped by the day voting ends. - @Published private(set) var sections: [VotingListSection] = [] - - /// Also called when the day changes, so "Voting ends today / in N days" - /// stays true on a screen left open past midnight. - func recomputeVisible() { - // Search matching keeps order and does not depend on the filter, so - // filtering first gives both the header count and the rows. - myVotesKnownForList = canFilterByMyVotes - && contests.allSatisfy { hasLoadedVoteHistory(for: $0.normalizedLabel) } - // A filter by my vote shows nothing until every contest can be told: - // after a refresh the new contests' history is still loading, and - // showing only the contests already known would be a partial list. - let kept = filter.type.readsMyVotes && !myVotesKnownForList ? [] : filtered(contests) - filterMatchCount = kept.count - let visible = searchMatches(in: kept) - // Days always go soonest first; the sort orders names inside a day. - // The flat list takes the same order as the grouped one. - sections = VotingListSection.group(visible, now: Date(), calendar: .current) - visibleContests = sections.flatMap(\.contests) - } - - /// The latest copy of `contest` in the list, so a screen opened from an - /// older snapshot shows today's counts. - func latest(_ contest: DPNSContest) -> DPNSContest { - contests.first { $0.normalizedLabel == contest.normalizedLabel } ?? contest - } - - /// True once a contest fetch has actually succeeded. Distinct from - /// ``hasLoadedOnce``, which only records that a load was attempted. - private var didLoadContests = false - - /// Which of our nodes voted, per contest. Keyed by contest so a screen can - /// never be answered with another contest's history — and so an ABSENT - /// entry is distinguishable from "none voted here", which is what makes - /// gating on load possible. - @Published private(set) var votedProTxHashesByContest: [String: Set] = [:] - - /// proTxHashes of the nodes the next vote will use, shared by the list - /// and the contest screen and persisted so the next contest - /// opens with the same nodes ticked. - /// - /// Persisted rather than re-asked because it is a privacy choice: voting - /// with several nodes at once links those masternodes to each other, and - /// that should stay the user's standing decision, not something re-made - /// under time pressure on every contest. - @Published var selectedNodeIDs: Set = VotingPrefs.shared.votingNodeSelection { - didSet { VotingPrefs.shared.votingNodeSelection = selectedNodeIDs } - } - - /// The selected nodes, in registration order, restricted to ones that are - /// still votable — a remembered node that has since been revoked or left - /// the masternode list must not silently come back. - var selectedNodes: [VoterNode] { - votableNodes.filter { selectedNodeIDs.contains($0.proTxHash) } - } + // MARK: Casting state /// Result banner for the most recent casting run. @Published var lastCastReport: VoteCastReport? /// Error from a casting run that never got as far as broadcasting. @Published var castError: String? - @Published private(set) var isCasting = false // MARK: Dependencies - private let contestsService: ContestedNamesService - private let registry: MasternodeVoterRegistry - private let caster: MasternodeVoteCaster - private let history: VoteHistoryDAO = VoteHistoryDAOImpl.shared private let vault: TrackedMasternodeKeyVaulting /// Read when needed, not once: the SDK manager comes and goes with the wallet. private let tracker: @MainActor () -> VotingKeyMasternodeTracking? @@ -176,21 +56,62 @@ final class VotingViewModel: ObservableObject { contestsService: ContestedNamesService? = nil, registry: MasternodeVoterRegistry? = nil, vault: TrackedMasternodeKeyVaulting? = nil, - tracker: (@MainActor () -> VotingKeyMasternodeTracking?)? = nil + tracker: (@MainActor () -> VotingKeyMasternodeTracking?)? = nil, + store: VotingStore? = nil ) { let contestsService = contestsService ?? ContestedNamesService() let registry = registry ?? MasternodeVoterRegistry() - self.contestsService = contestsService - self.registry = registry self.vault = vault ?? TrackedMasternodeKeyVault() self.tracker = tracker ?? { SwiftDashSDKHost.shared.manager } - self.caster = MasternodeVoteCaster(registry: registry, contests: contestsService) + let store = store ?? VotingStore( + contests: contestsService, + nodes: registry, + caster: MasternodeVoteCaster( + registry: registry, contests: contestsService, history: VoteHistoryDAOImpl.shared), + history: VoteHistoryDAOImpl.shared, + prefs: VotingPrefs.shared) + let list = VotingListViewModel( + store: store, normalizedLabel: { contestsService.normalizedLabel(for: $0) }) + self.store = store + self.list = list + // Screens observe this model; tell them when either part changes. + store.objectWillChange.sink { [weak self] in self?.objectWillChange.send() }.store(in: &changes) + list.objectWillChange.sink { [weak self] in self?.objectWillChange.send() }.store(in: &changes) + } + + // MARK: Reads forwarded from the store + + var canVote: Bool { store.canVote } + var votableNodes: [VoterNode] { store.votableNodes } + var effectiveSelectedNodeIDs: Set { store.effectiveSelectedNodeIDs } + var selectedNodeIDs: Set { + get { store.selectedNodeIDs } + set { store.selectedNodeIDs = newValue } + } + var toast: VotingToast? { list.toast } + + func latest(_ contest: DPNSContest) -> DPNSContest { store.latest(contest) } + func isClosed(normalizedLabel: String) -> Bool { store.isClosed(normalizedLabel: normalizedLabel) } + func hasLoadedVoteHistory(for normalizedLabel: String) -> Bool { + store.hasLoadedVoteHistory(for: normalizedLabel) } - - // MARK: Derived state - - - var canVote: Bool { !votableNodes.isEmpty } + func nodesYetToVote(on normalizedLabel: String) -> [VoterNode] { store.nodesYetToVote(on: normalizedLabel) } + func votedNodeCount(on normalizedLabel: String) -> Int { store.votedNodeCount(on: normalizedLabel) } + func nodesForVote(_ choice: VoteChoice, on normalizedLabel: String) -> [VoterNode] { + store.nodesForVote(choice, on: normalizedLabel) + } + func canStartVote(_ choice: VoteChoice, on normalizedLabel: String) -> Bool { + store.canStartVote(choice, on: normalizedLabel) + } + func castCandidates( + for choice: VoteChoice, cancelling: VoteChoice?, on normalizedLabel: String + ) -> VotingStore.CastCandidates { + store.castCandidates(for: choice, cancelling: cancelling, on: normalizedLabel) + } + func loadVotedNodes(for normalizedLabel: String) async { await store.loadVotedNodes(for: normalizedLabel) } + func refreshContest(normalizedLabel: String) async { await store.refreshContest(normalizedLabel: normalizedLabel) } + func refreshVotableNodes() { store.refreshVotableNodes() } + func isSending(normalizedLabel: String) -> Bool { store.isSending(normalizedLabel: normalizedLabel) } /// Names the nodes a vote will use, so the privacy consequence of the /// current selection is legible without opening the picker. Describes the @@ -206,416 +127,6 @@ final class VotingViewModel: ObservableObject { return chosen.map(\.displayName).joined(separator: ", ") } - /// The contests in `input` matching the search box, in their order. - /// - /// The query is homograph-normalized before matching because Platform - /// stores normalized labels — someone typing "alice" is looking for - /// "a11ce", and a raw substring match would find nothing. - private func searchMatches(in input: [DPNSContest]) -> [DPNSContest] { - let trimmed = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return input } - - // Normalization needs the SDK, and so does `contests` — a non-empty - // list means the handle is up, so this only returns nil when there is - // nothing to filter anyway. Leaving the list unfiltered beats - // matching against a locally-guessed spelling of the label. - // Normalized when the query was typed; again here only if the SDK was - // not up yet then. - if normalizedNeedle == nil { - normalizedNeedle = contestsService.normalizedLabel(for: trimmed) - } - guard let needle = normalizedNeedle else { - return input - } - // Match the normalized form *and* the spellings people actually typed, - // so searching "pizza" finds the contest whether the row is showing - // "pizza" or the normalized "p1zza". - let raw = trimmed.lowercased() - return input.filter { contest in - contest.normalizedLabel.contains(needle) - || contest.requestedLabels.contains { $0.lowercased().contains(raw) } - } - } - - private func filtered(_ input: [DPNSContest]) -> [DPNSContest] { - filter.apply(to: input, myChoices: knownChoices(on:)) - } - - /// This wallet's choices on a contest, or `nil` while they are not known - /// (history not loaded or unreadable, node list maybe incomplete): the - /// filters by my vote then leave the contest out rather than guess. - private func knownChoices(on normalizedLabel: String) -> Set? { - guard canFilterByMyVotes, hasLoadedVoteHistory(for: normalizedLabel) else { return nil } - return myChoices(on: normalizedLabel) - } - - // MARK: Loading - - /// The loads below — the whole list, every contest's history, one - /// contest's history, one contest's tallies — run one at a time, in the - /// order they were asked for. Each reads the store or Platform when its - /// turn comes and applies what it read before the next one starts, so a - /// load that read earlier can never land after one that read later and - /// put back what was there before a vote. - private var loadQueueTail: Task? - - /// A queued load must call only `perform…` functions, never the public - /// wrappers: those wait for the queue's tail, which would be itself. - private func serially(_ load: @escaping @MainActor () async -> Void) async { - let previous = loadQueueTail - let next = Task { @MainActor in - await previous?.value - await load() - } - loadQueueTail = next - await next.value - } - - func refresh() async { - await serially { [weak self] in await self?.performRefresh() } - } - - private func performRefresh() async { - isLoading = true - defer { - isLoading = false - hasLoadedOnce = true - } - - refreshVotableNodes() - - do { - contests = try await contestsService.activeContests() - // A contest Platform lists as open again is not closed. - closedLabels.subtract(contests.map(\.normalizedLabel)) - loadError = nil - didLoadContests = true - } catch { - loadError = (error as? LocalizedError)?.errorDescription ?? String(describing: error) - } - - // After the contests, so every listed contest gets a known history — - // an empty one included — and its vote controls are not held back - // waiting for a per-contest load. - await performLoadAllVoteHistory() - } - - /// This wallet's vote history for every contest, in one query, so the list - /// can mark the user's own vote on every row without a query per row. - /// - /// Fills the same per-contest maps ``loadVotedNodes(for:)`` fills for one - /// contest. A listed contest with no records gets an empty history: after a - /// full load "no records" means "nobody voted", not "not loaded yet". - private func loadAllVoteHistory() async { - await serially { [weak self] in await self?.performLoadAllVoteHistory() } - } - - private func performLoadAllVoteHistory() async { - let labels = Set(contests.map(\.normalizedLabel)) - // A failed read leaves every history unknown — not "nobody voted", - // which would offer nodes for votes they already hold — and says so. - guard let records = await history.votes( - forContests: labels, network: MasternodeVoteCaster.networkKey) - else { - historyUnavailable = true - return - } - historyUnavailable = false - let byLabel = Dictionary(grouping: records, by: \.normalizedLabel) - // Merged in: a contest not in the list (one open on its own screen - // after it closed) keeps the history it has. - var voted = votedProTxHashesByContest - var histories = voteHistoryByContest - for label in labels { - let contestRecords = byLabel[label] ?? [] - voted[label] = Set(contestRecords.map(\.proTxHash)) - histories[label] = NodeVoteHistory(contestRecords) - } - votedProTxHashesByContest = voted - voteHistoryByContest = histories - } - - /// This wallet's vote history could not be read, so the list cannot tell - /// which votes are already cast and holds its vote controls back. - @Published private(set) var historyUnavailable = false { - didSet { if historyUnavailable != oldValue { recomputeIfFilteringByMyVotes() } } - } - - /// Re-resolve which nodes this wallet can vote with, and nothing else. - /// - /// The voting-key screens call this after adding or removing a key. A full - /// ``refresh()`` would also re-query every open contest over the network, - /// which a key change does not affect. - func refreshVotableNodes() { - let resolution = registry.votableNodes() - votableNodes = resolution.nodes - nodeListMayBeIncomplete = resolution.mayBeIncomplete - - // Settle the remembered selection against the nodes that actually - // exist now, so the picker and the "voting with" row agree with what a - // tap would really do. - // - // Only when the node list actually resolved. `votableNodes()` returns - // empty while the SDK is starting or the masternode phase has not - // synced, and settling against that would compute an empty selection - // and PERSIST it — destroying a multi-node choice the user made, with - // the next vote silently falling back to one node. - if !votableNodes.isEmpty { - let settled = effectiveSelectedNodeIDs - if settled != selectedNodeIDs { - selectedNodeIDs = settled - } - } - } - - /// The screen's initial load, which does nothing once contests are in hand. - /// - /// `.task` re-runs when the list reappears — including on the way back from - /// a contest — and `refresh()` re-queries every active contest over the - /// network, which takes long enough to read as the screen hanging. Nothing - /// about returning from a contest invalidates the list: casting already - /// refreshes the one contest it touched via ``refreshContest(normalizedLabel:)``, - /// and pull-to-refresh still forces a real reload. - /// - /// Keyed on contests actually having loaded rather than on an attempt, so a - /// first load that failed still retries instead of stranding the user on an - /// empty list. - func refreshIfNeeded() async { - // Checked when its turn comes: a list that reappears while the first - // load is still queued must not queue a second full refresh. - await serially { [weak self] in - guard let self, !self.didLoadContests else { return } - await self.performRefresh() - } - } - - /// Re-read one contest's tallies after voting on it, so the row reflects - /// the vote without a full refresh. - /// - /// A contest that has since resolved — or that Platform no longer holds - /// contenders for — leaves `contests` and is recorded in ``closedLabels``. - /// `contests` is the *open* contest list: leaving a settled contest in it - /// would offer a Vote button whose only possible outcome is the caster's - /// closed-poll rejection. - func refreshContest(normalizedLabel: String) async { - await serially { [weak self] in await self?.performRefreshContest(normalizedLabel: normalizedLabel) } - } - - private func performRefreshContest(normalizedLabel: String) async { - let state: DPNSContestVoteState? - do { - state = try await contestsService.voteState(normalizedLabel: normalizedLabel) - } catch { - // The query failed, so we learned nothing about this contest. - // Leave the cached row exactly as it was rather than treating a - // network blip as a resolution. - return - } - - // A successful query returning no contenders means Platform holds no - // poll for the label. For a row that was in the active list moments - // ago, that is a contest which resolved and was pruned. - guard let state, !state.isResolved else { - close(normalizedLabel: normalizedLabel) - return - } - - guard let index = contests.firstIndex(where: { $0.normalizedLabel == normalizedLabel }) - else { return } - - let existing = contests[index] - contests[index] = DPNSContest( - normalizedLabel: existing.normalizedLabel, - endTime: existing.endTime, - hasWinner: false, - abstainVotes: state.abstainVotes, - lockVotes: state.lockVotes, - contenders: state.contenders, - // The vote state carries no requested spellings; without these the - // row would fall back to the normalized label ("p1zza") after a vote. - requestedLabels: existing.requestedLabels) - } - - private func close(normalizedLabel: String) { - contests.removeAll { $0.normalizedLabel == normalizedLabel } - closedLabels.insert(normalizedLabel) - } - - /// Whether a contest the user is looking at has closed under them. The - /// detail screen reads this to swap its vote controls for a closed notice - /// instead of silently showing a stale snapshot with live-looking buttons. - func isClosed(normalizedLabel: String) -> Bool { - closedLabels.contains(normalizedLabel) - } - - // MARK: Vote history - - /// One contest's history reduced to what the casting rules read: each - /// node's live vote and how many casts it has spent. - /// - /// The five-cast ceiling is applied by this one rule: looking only at the - /// live choice would offer exhausted nodes that Platform then rejects. - struct NodeVoteHistory { - private(set) var latest: [Data: CastVoteRecord] = [:] - private(set) var casts: [Data: Int] = [:] - - init(_ records: [CastVoteRecord]) { - // One row per node per contest — a change overwrites the row it - // came from — so the ceiling is read from the row's own - // `castCount`, not from how many rows a node has. Counting rows - // could never reach five. - for record in records { - casts[record.proTxHash] = max(casts[record.proTxHash] ?? 0, record.castCount) - if let seen = latest[record.proTxHash], seen.castAt >= record.castAt { continue } - latest[record.proTxHash] = record - } - } - - func liveChoice(of proTxHash: Data) -> VoteChoice? { - latest[proTxHash]?.choice - } - - /// The live choices of `nodes`, for marking "my vote" on a list row. - func liveChoices(of nodes: Set) -> Set { - Set(latest.filter { nodes.contains($0.key) }.values.map(\.choice)) - } - - /// One more cast by `node`, now holding `choice`, as the store records it. - mutating func recordCast(of node: Data, on normalizedLabel: String, choice: VoteChoice, at date: Date) { - casts[node, default: 0] += 1 - latest[node] = CastVoteRecord( - proTxHash: node, - normalizedLabel: normalizedLabel, - choice: choice, - castAt: date, - castCount: casts[node] ?? 1) - } - - /// Whether Platform would still accept another vote from this node here. - func hasCastsLeft(_ proTxHash: Data) -> Bool { - (casts[proTxHash] ?? 0) < VotingViewModel.maxCastsPerNodePerContest - } - } - - /// Per contest, rebuilt for one contest by `loadVotedNodes(for:)` and for - /// every listed contest by `loadAllVoteHistory()`. - private var voteHistoryByContest: [String: NodeVoteHistory] = [:] { - didSet { recomputeIfFilteringByMyVotes() } - } - - /// The type filter reads this wallet's votes, so a change to them changes - /// what it keeps; the other filters do not depend on them. - private func recomputeIfFilteringByMyVotes() { - guard filter.type.readsMyVotes else { return } - recomputeVisible() - } - - /// Whether this wallet's own votes can be told for the types that read - /// them: not when the history could not be read, nor while a voting node - /// may be missing from ``votableNodes`` (its votes would not count). - var canFilterByMyVotes: Bool { - !historyUnavailable && !nodeListMayBeIncomplete && canVote - } - - /// Why this wallet's own votes cannot be told, as the next step for the - /// user; `nil` when they can. Without a voting node the wallet holds no - /// vote to tell, so the types that read them have nothing to go on. - var myVotesUnavailableReason: String? { - if historyUnavailable { - return NSLocalizedString("Pull down to try again.", comment: "Voting") - } - if nodeListMayBeIncomplete { - return NSLocalizedString( - "Some of your masternodes may be missing from this list — the wallet could not read your full voting-key pool. Finish syncing and reopen this screen.", - comment: "Voting") - } - if !canVote { - return NSLocalizedString( - "This wallet's masternode voting keys aren't available right now, so it has no votes to filter by.", - comment: "Voting") - } - return nil - } - - /// Nodes that have not yet voted on this contest, in registration order. - /// - /// Empty until this contest's history has loaded. The screen evaluates this - /// before its `.task` completes, and treating "not loaded" as "nobody - /// voted" would offer nodes that already voted — a duplicate Platform - /// rejects, spending one of the masternode's per-contest votes. - func nodesYetToVote(on normalizedLabel: String) -> [VoterNode] { - guard let voted = votedProTxHashesByContest[normalizedLabel] else { return [] } - return votableNodes.filter { !voted.contains($0.proTxHash) } - } - - /// Whether this contest's vote history is known yet. Callers disable the - /// vote control until it is, rather than acting on an unknown. - func hasLoadedVoteHistory(for normalizedLabel: String) -> Bool { - votedProTxHashesByContest[normalizedLabel] != nil - } - - /// Load which of our nodes already voted on one contest. Called when its - /// detail screen opens, so the vote button knows what is left. - func loadVotedNodes(for normalizedLabel: String) async { - await serially { [weak self] in await self?.performLoadVotedNodes(for: normalizedLabel) } - } - - private func performLoadVotedNodes(for normalizedLabel: String) async { - // A failed read leaves what was known: an empty history would offer - // nodes for votes they already hold. - guard let records = await history.votes( - forContest: normalizedLabel, - network: MasternodeVoteCaster.networkKey) - else { return } - votedProTxHashesByContest[normalizedLabel] = Set(records.map(\.proTxHash)) - voteHistoryByContest[normalizedLabel] = NodeVoteHistory(records) - } - - /// How many of this wallet's nodes have a live vote here — nodes, not - /// records. A node that changed its mind has two records and is still one - /// node, which is what "%d of %d nodes voted" is counting. - func votedNodeCount(on normalizedLabel: String) -> Int { - votedProTxHashesByContest[normalizedLabel]?.count ?? 0 - } - - /// This node's live choice on this contest, when it has one. - func liveChoice(of node: VoterNode, on normalizedLabel: String) -> VoteChoice? { - voteHistoryByContest[normalizedLabel]?.liveChoice(of: node.proTxHash) - } - - /// The nodes a tap on `choice` should cast with: the remembered selection, - /// minus nodes already holding that exact choice (Platform rejects a - /// duplicate) and minus nodes that have spent the five casts it allows per - /// contest. A node holding a *different* choice belongs here — replacing - /// its vote is one state transition, and it is the whole point of being - /// able to change your mind from this screen. - func nodesForVote(_ choice: VoteChoice, on normalizedLabel: String) -> [VoterNode] { - guard hasLoadedVoteHistory(for: normalizedLabel) else { return [] } - let chosen = effectiveSelectedNodeIDs - let history = voteHistoryByContest[normalizedLabel] ?? NodeVoteHistory([]) - return votableNodes.filter { node in - guard chosen.contains(node.proTxHash) else { return false } - guard history.hasCastsLeft(node.proTxHash) else { return false } - return history.liveChoice(of: node.proTxHash) != choice - } - } - - /// `votes_allowed_per_masternode` in the platform version this app talks - /// to; the sixth cast is refused with `MasternodeVotedTooManyTimesError`. - static let maxCastsPerNodePerContest = 5 - - /// The remembered selection, or a single node when nothing was ever - /// chosen. Never every node by default: see ``VotingPrefs``. - /// - /// Also recovers from a selection that no longer matches any votable node - /// (nodes revoked, or a different wallet), which would otherwise leave the - /// vote button permanently disabled with no way to see why. - var effectiveSelectedNodeIDs: Set { - let live = selectedNodeIDs.intersection(votableNodeIDs) - if !live.isEmpty { return live } - return Set(votableNodes.first.map { [$0.proTxHash] } ?? []) - } - // MARK: Voting keys /// Remove a voting key the user added, so that node stops voting from this @@ -656,174 +167,35 @@ final class VotingViewModel: ObservableObject { // MARK: Casting - /// Cast `choice` on `contest` with `nodes`, then refresh that contest. - /// Returns `true` when every node's vote landed. That outcome is told by a - /// toast, so the caller can close its sheet right away; anything less is - /// left in ``lastCastReport`` / ``castError`` for the sheet to show. - /// - /// The toast is shown as soon as the votes are recorded, and the contest's - /// tallies are re-read from Platform afterwards — waiting for that network - /// query first could let the toast expire under the still-open sheet. + /// Cast `choice` on `contest` with `nodes` through the store, which also + /// re-reads that contest. Returns `true` when every node's vote landed. + /// That outcome is told by a toast, so the caller can close its sheet + /// right away; anything less is left in ``lastCastReport`` / + /// ``castError`` for the sheet to show. @discardableResult func cast(choice: VoteChoice, on contest: DPNSContest, with nodes: [VoterNode]) async -> Bool { - let label = contest.normalizedLabel - isCasting = true castError = nil - castingLabels.insert(label) // A new vote clears the last outcome, so a toast from the previous // vote never sits next to this one. - toast = nil - defer { isCasting = false } - - do { - let report = try await caster.cast( - choice: choice, - onNormalizedLabel: label, - with: nodes) - // What was just recorded is known here: apply it now rather than - // wait for the store read, which may queue behind a slow refresh. - applyRecordedVotes(of: report, on: label) - // Then confirm from the store and Platform. The contest's pills stay - // busy until that lands, so a queued earlier read cannot offer a - // node for the vote it now holds in between. - Task { [weak self] in - await self?.loadVotedNodes(for: label) - await self?.refreshContest(normalizedLabel: label) - self?.castingLabels.remove(label) - } - if report.isCompleteSuccess { - showToast(.voted(username: contest.displayTitle)) - return true - } + list.clearToast() + await store.send(choice: choice, on: contest, from: nodes) + + switch store.outcome { + case .success(let toast): + list.showToast(toast) + return true + case .mixed(let report): lastCastReport = report - return false - } catch { - castingLabels.remove(label) - castError = (error as? LocalizedError)?.errorDescription ?? String(describing: error) - return false - } - } - - /// Adds the votes `report` says landed to the contest's known history, as - /// the caster recorded them. Nothing when the history is not known yet: - /// the store reload that follows fills it. - private func applyRecordedVotes(of report: VoteCastReport, on normalizedLabel: String) { - guard var contestHistory = voteHistoryByContest[normalizedLabel] else { return } - let now = Date() - for outcome in report.succeeded { - contestHistory.recordCast( - of: outcome.node.proTxHash, on: normalizedLabel, choice: report.choice, at: now) - } - voteHistoryByContest[normalizedLabel] = contestHistory - votedProTxHashesByContest[normalizedLabel, default: []] - .formUnion(report.succeeded.map(\.node.proTxHash)) - } - - /// Whether a tap on `choice` may start a vote on this contest: the key flow - /// when the wallet has no node, otherwise only once the contest's history - /// is known and some selected node can still cast that choice — not one - /// already holding it, not one out of casts. One rule for the list and the - /// contest screen. - func canStartVote(_ choice: VoteChoice, on normalizedLabel: String) -> Bool { - guard !isClosed(normalizedLabel: normalizedLabel) else { return false } - guard canVote else { return true } - return !nodesForVote(choice, on: normalizedLabel).isEmpty - } - - // MARK: List state - - /// Contests with a vote in flight. Their pills show a spinner and take no - /// taps while it is sent. - @Published private(set) var castingLabels: Set = [] - - /// The outcome of the last vote, shown in the list's bottom bar and over - /// the contest screen. - @Published private(set) var toast: VotingToast? - - /// How long a toast stays before it clears itself. - static let toastDuration: Duration = .seconds(3) - - private func showToast(_ toast: VotingToast) { - self.toast = toast - Task { [weak self, id = toast.id] in - try? await Task.sleep(for: Self.toastDuration) - // Only the toast this task was started for: a newer one has its own timer. - if self?.toast?.id == id { self?.toast = nil } + case .failure(let message): + castError = message + case nil: + break } + return false } - /// The choices this wallet's nodes currently hold on a contest, from local - /// history. Empty when none of them voted, or before the history loaded. - func myChoices(on normalizedLabel: String) -> Set { - guard let history = voteHistoryByContest[normalizedLabel] else { return [] } - // Only nodes this wallet votes with: the history table is per device, - // and a node whose key was removed is no longer this wallet's vote. - return history.liveChoices(of: votableNodeIDs) - } - - func dismissCastResult() { lastCastReport = nil castError = nil } } - -// MARK: - VotingListSection - -/// The voting list's groups: contests whose voting ends on the same calendar -/// day, soonest first. Rows inside a group keep the order they came in, which -/// is the list's chosen sort. -struct VotingListSection: Identifiable, Equatable { - /// Days from today to the day voting ends; `nil` when the end is unknown. - let daysLeft: Int? - let contests: [DPNSContest] - - var id: Int { daysLeft ?? Int.max } - - var title: String { - switch daysLeft { - case nil: - return NSLocalizedString("Voting end unknown", comment: "Voting") - case 0: - return NSLocalizedString("Voting ends today", comment: "Voting") - case let days?: - return String.localizedStringWithFormat( - NSLocalizedString("Voting ends in %d days", comment: "Voting"), days) - } - } - - /// Group `contests` by end day relative to `now` in `calendar`. A contest - /// whose end has already passed today is still "today" (it is closing); an - /// end on an earlier day also counts as today rather than a negative count. - static func group(_ contests: [DPNSContest], now: Date, calendar: Calendar) -> [VotingListSection] { - let today = calendar.startOfDay(for: now) - var order: [Int?] = [] - var buckets: [Int?: [DPNSContest]] = [:] - for contest in contests { - let key: Int? = contest.endTime.map { end in - let days = calendar.dateComponents([.day], from: today, to: calendar.startOfDay(for: end)).day ?? 0 - return max(days, 0) - } - if buckets[key] == nil { order.append(key) } - buckets[key, default: []].append(contest) - } - return order - .sorted { ($0 ?? Int.max) < ($1 ?? Int.max) } - .map { VotingListSection(daysLeft: $0, contests: buckets[$0] ?? []) } - } -} - -// MARK: - VotingToast - -/// A vote that landed on every node, told briefly in the list's bottom bar or -/// over the contest screen. A -/// partial or failed vote is not a toast: the cast sheet stays open and lists -/// each node's outcome. -struct VotingToast: Identifiable, Equatable { - let id = UUID() - let message: String - - static func voted(username: String) -> VotingToast { - VotingToast(message: String(format: NSLocalizedString("Voted %@ username", comment: "Voting"), username)) - } -} diff --git a/DashWallet/ar.lproj/Localizable.strings b/DashWallet/ar.lproj/Localizable.strings index 6db611cf3e..93f3dd82eb 100644 --- a/DashWallet/ar.lproj/Localizable.strings +++ b/DashWallet/ar.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "المتنافس %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "استمر"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "ما القادم؟"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/bg.lproj/Localizable.strings b/DashWallet/bg.lproj/Localizable.strings index 458ed39fd2..df5d4457d2 100644 --- a/DashWallet/bg.lproj/Localizable.strings +++ b/DashWallet/bg.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Кандидат %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Продължи"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Какво следва?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/ca.lproj/Localizable.strings b/DashWallet/ca.lproj/Localizable.strings index 9ed3b88f6d..d63d52cc4e 100644 --- a/DashWallet/ca.lproj/Localizable.strings +++ b/DashWallet/ca.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Aspirant %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Què vindrà després?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/cs.lproj/Localizable.strings b/DashWallet/cs.lproj/Localizable.strings index 4f28898f88..90c29e08b2 100644 --- a/DashWallet/cs.lproj/Localizable.strings +++ b/DashWallet/cs.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Uchazeč %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Pokračovat"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Co přijde dál?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/da.lproj/Localizable.strings b/DashWallet/da.lproj/Localizable.strings index 45c6bf92f2..2c04f1285e 100644 --- a/DashWallet/da.lproj/Localizable.strings +++ b/DashWallet/da.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Ansøger %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Hvad kommer der herefter?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/de.lproj/Localizable.strings b/DashWallet/de.lproj/Localizable.strings index 5b4aaec49d..392f19c786 100644 --- a/DashWallet/de.lproj/Localizable.strings +++ b/DashWallet/de.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Bewerber %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Fortfahren"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Was ist das Abstimmen über Nutzernamen?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Was kommt als Nächstes?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Stimmen: Aufsteigend"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Kein Vote übrig"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/el.lproj/Localizable.strings b/DashWallet/el.lproj/Localizable.strings index f9e7221425..275e2515bb 100644 --- a/DashWallet/el.lproj/Localizable.strings +++ b/DashWallet/el.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Διεκδικητής %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Συνέχεια"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Τι είναι η ψηφοφορία ονόματος χρήστη;"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Τι έρχεται στη συνέχεια;"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Ψήφοι: Χαμηλές προς υψηλές"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Δεν έχουν απομείνει ψήφοι"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index c290cd10e3..8a1a2d51c3 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -1328,7 +1328,6 @@ "Contender %@" = "Contender %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6822,7 +6821,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "What's coming next?"; @@ -7512,3 +7510,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/eo.lproj/Localizable.strings b/DashWallet/eo.lproj/Localizable.strings index 9420ed9511..5c81dbc256 100644 --- a/DashWallet/eo.lproj/Localizable.strings +++ b/DashWallet/eo.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Kandidato %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Kio venos poste?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/es.lproj/Localizable.strings b/DashWallet/es.lproj/Localizable.strings index 926f161d16..f32187f5d2 100644 --- a/DashWallet/es.lproj/Localizable.strings +++ b/DashWallet/es.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Aspirante %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continuar"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "¿Qué es la votación por nombre de usuario?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "¿Qué viene a continuación?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votos: Bajo a alto"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No quedan votos"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/et.lproj/Localizable.strings b/DashWallet/et.lproj/Localizable.strings index 9e55ee4c2d..cca05feb4c 100644 --- a/DashWallet/et.lproj/Localizable.strings +++ b/DashWallet/et.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Taotleja %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Mis tuleb järgmisena?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/fa.lproj/Localizable.strings b/DashWallet/fa.lproj/Localizable.strings index d34592f797..ff6de3af05 100644 --- a/DashWallet/fa.lproj/Localizable.strings +++ b/DashWallet/fa.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "داوطلب %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "ادامه"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "رای‌گیری نام کاربری چیست؟"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "بعد از این چه می‌آید؟"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "هیچ رایی باقی نمانده است. "; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/fi.lproj/Localizable.strings b/DashWallet/fi.lproj/Localizable.strings index e35ad5aed3..da9915644a 100644 --- a/DashWallet/fi.lproj/Localizable.strings +++ b/DashWallet/fi.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Hakija %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Mitä on tulossa seuraavaksi?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/fil.lproj/Localizable.strings b/DashWallet/fil.lproj/Localizable.strings index 0a74691c48..ab0f2b82a1 100644 --- a/DashWallet/fil.lproj/Localizable.strings +++ b/DashWallet/fil.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Kalahok %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Ipagpatuloy"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Ano ang pagboto ng username?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Ano ang susunod?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Mga Boto: Mababa hanggang mataas"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Walang natitirang boto"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/fr.lproj/Localizable.strings b/DashWallet/fr.lproj/Localizable.strings index 10c2b1da12..cef6ae9a7c 100644 --- a/DashWallet/fr.lproj/Localizable.strings +++ b/DashWallet/fr.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Candidat %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continuer"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Qu'est-ce que le vote des noms d'utilisateur ?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Quelle est la suite ?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes : de bas à haut"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Plus de vote possible"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/hr.lproj/Localizable.strings b/DashWallet/hr.lproj/Localizable.strings index f16835a91d..81dc3030d4 100644 --- a/DashWallet/hr.lproj/Localizable.strings +++ b/DashWallet/hr.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Kandidat %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Što slijedi?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/hu.lproj/Localizable.strings b/DashWallet/hu.lproj/Localizable.strings index 314c7179dc..fa2cfbe104 100644 --- a/DashWallet/hu.lproj/Localizable.strings +++ b/DashWallet/hu.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Pályázó: %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Mi jön ezután?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/id.lproj/Localizable.strings b/DashWallet/id.lproj/Localizable.strings index 246f90d3d5..36ef2f442f 100644 --- a/DashWallet/id.lproj/Localizable.strings +++ b/DashWallet/id.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Penawar %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Teruskan"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Apa itu voting nama pengguna?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Apa yang akan datang berikutnya?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Rendah ke tinggi"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Tidak ada suara tersisa"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/it.lproj/Localizable.strings b/DashWallet/it.lproj/Localizable.strings index af233aca1b..5e3ee61156 100644 --- a/DashWallet/it.lproj/Localizable.strings +++ b/DashWallet/it.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Candidato %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continua"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Cos'è la votazione del nome utente?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Cosa arriverà dopo?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Voti: da basso a alto"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Nessun voto rimasto"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/ja.lproj/Localizable.strings b/DashWallet/ja.lproj/Localizable.strings index 259d33301f..80f35b2f23 100644 --- a/DashWallet/ja.lproj/Localizable.strings +++ b/DashWallet/ja.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "候補者 %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "続ける"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "ユーザー名投票とは?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "次に来る機能は?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "投票数:低から高"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "あと0票"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/ko.lproj/Localizable.strings b/DashWallet/ko.lproj/Localizable.strings index 3be10b952e..fe87a1c7de 100644 --- a/DashWallet/ko.lproj/Localizable.strings +++ b/DashWallet/ko.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "후보 %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "계속"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "사용자이름 투표란 무엇인가요?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "다음에는 무엇이 오나요?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "투표: 낮음부터 높음"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "남은 투표 없음"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/mk.lproj/Localizable.strings b/DashWallet/mk.lproj/Localizable.strings index 393b0f6b36..0e515c3a96 100644 --- a/DashWallet/mk.lproj/Localizable.strings +++ b/DashWallet/mk.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Кандидат %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Што следува?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/ms.lproj/Localizable.strings b/DashWallet/ms.lproj/Localizable.strings index 6583fa7fb9..8e9e855e4c 100644 --- a/DashWallet/ms.lproj/Localizable.strings +++ b/DashWallet/ms.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Pemohon %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Apa yang akan datang seterusnya?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/nb.lproj/Localizable.strings b/DashWallet/nb.lproj/Localizable.strings index 6c7f40f1e5..ed6940a4cc 100644 --- a/DashWallet/nb.lproj/Localizable.strings +++ b/DashWallet/nb.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Søker %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Hva kommer nå?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/nl.lproj/Localizable.strings b/DashWallet/nl.lproj/Localizable.strings index 1d24270264..fde68b00fc 100644 --- a/DashWallet/nl.lproj/Localizable.strings +++ b/DashWallet/nl.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Kandidaat %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Ga door"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Wat is stemmen met gebruikersnaam?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Wat komt er hierna?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Stemmen: van laag naar hoog"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Geen stemmen over"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/pl.lproj/Localizable.strings b/DashWallet/pl.lproj/Localizable.strings index 19c4955719..d4d4eb21a3 100644 --- a/DashWallet/pl.lproj/Localizable.strings +++ b/DashWallet/pl.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Kandydat %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Dalej"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Na czym polega głosowanie nad nazwą użytkownika?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Co dalej?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Głosy: od najmniej do najwięcej"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Nie możesz oddać więcej głosów"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/pt.lproj/Localizable.strings b/DashWallet/pt.lproj/Localizable.strings index 247fd28d26..a4c0277b2b 100644 --- a/DashWallet/pt.lproj/Localizable.strings +++ b/DashWallet/pt.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Candidato %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continuar"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "O que é a votação de nomes de usuário?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "O que vem a seguir?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votos: Do mais baixo para o mais alto"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Sem votos restantes"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/ro.lproj/Localizable.strings b/DashWallet/ro.lproj/Localizable.strings index 2911f5e5f7..9a4bed7746 100644 --- a/DashWallet/ro.lproj/Localizable.strings +++ b/DashWallet/ro.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Candidatul %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Ce urmează?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/ru.lproj/Localizable.strings b/DashWallet/ru.lproj/Localizable.strings index 7fb53c61a1..ddcaa4f8e7 100644 --- a/DashWallet/ru.lproj/Localizable.strings +++ b/DashWallet/ru.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Претендент %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Продолжить"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Что такое голосование за имя пользователя?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Что дальше?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Голоса: По возрастанию"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Голосов больше нет"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/sk.lproj/Localizable.strings b/DashWallet/sk.lproj/Localizable.strings index 98f634a6ce..04c880208b 100644 --- a/DashWallet/sk.lproj/Localizable.strings +++ b/DashWallet/sk.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Uchádzač %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Pokračovať"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Čo je to hlasovanie o používateľské mená?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Čo príde ďalej?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Hlasy: od najmenších"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Nezostávajú žiadne hlasy"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/sl.lproj/Localizable.strings b/DashWallet/sl.lproj/Localizable.strings index 0c0b438be9..31cf2977af 100644 --- a/DashWallet/sl.lproj/Localizable.strings +++ b/DashWallet/sl.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Kandidat %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Kaj prihaja naslednje?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/sl_SI.lproj/Localizable.strings b/DashWallet/sl_SI.lproj/Localizable.strings index 2fe8d9731e..f542f9f10e 100644 --- a/DashWallet/sl_SI.lproj/Localizable.strings +++ b/DashWallet/sl_SI.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Kandidat %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Kaj prihaja naslednje?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/sq.lproj/Localizable.strings b/DashWallet/sq.lproj/Localizable.strings index 50cd18f912..8356ea475d 100644 --- a/DashWallet/sq.lproj/Localizable.strings +++ b/DashWallet/sq.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Kandidati %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Çfarë vjen më pas?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/sr.lproj/Localizable.strings b/DashWallet/sr.lproj/Localizable.strings index fd4b637c5d..354e8f708e 100644 --- a/DashWallet/sr.lproj/Localizable.strings +++ b/DashWallet/sr.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Kandidat %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Šta sledi?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/sv.lproj/Localizable.strings b/DashWallet/sv.lproj/Localizable.strings index 35d7695468..4dce1175a8 100644 --- a/DashWallet/sv.lproj/Localizable.strings +++ b/DashWallet/sv.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Sökande %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Fortsätt"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Vad kommer härnäst?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/th.lproj/Localizable.strings b/DashWallet/th.lproj/Localizable.strings index 0d2759eeac..80a32b0f06 100644 --- a/DashWallet/th.lproj/Localizable.strings +++ b/DashWallet/th.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "ผู้ขอ %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "ดำเนินการต่อ"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "การโหวตชื่อผู้ใช้คืออะไร?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "อะไรจะมาต่อไป"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "โหวต: ต่ำไปสูง"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/tr.lproj/Localizable.strings b/DashWallet/tr.lproj/Localizable.strings index f8dca1da39..f602683fa4 100644 --- a/DashWallet/tr.lproj/Localizable.strings +++ b/DashWallet/tr.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Aday %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Devam"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Kullanıcı adı oylaması nedir?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Sırada ne var?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Oylar: Düşükten yükseğe"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/uk.lproj/Localizable.strings b/DashWallet/uk.lproj/Localizable.strings index 15337a3c3c..d1abcf9555 100644 --- a/DashWallet/uk.lproj/Localizable.strings +++ b/DashWallet/uk.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Претендент %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Продовжити"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "Що таке голосування за імʼя користувача?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Що буде далі?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Голоси: від низького до високого"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "Голосів немає"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/vi.lproj/Localizable.strings b/DashWallet/vi.lproj/Localizable.strings index d2ef4303ae..0008e93bc0 100644 --- a/DashWallet/vi.lproj/Localizable.strings +++ b/DashWallet/vi.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "Người xin %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Tiếp tục"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "Sắp tới có gì?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/zh-Hans.lproj/Localizable.strings b/DashWallet/zh-Hans.lproj/Localizable.strings index 91fe183373..a981fba367 100644 --- a/DashWallet/zh-Hans.lproj/Localizable.strings +++ b/DashWallet/zh-Hans.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "申请者 %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "接下来会有什么?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/zh-Hant-TW.lproj/Localizable.strings b/DashWallet/zh-Hant-TW.lproj/Localizable.strings index e863a2db4b..8774eee49a 100644 --- a/DashWallet/zh-Hant-TW.lproj/Localizable.strings +++ b/DashWallet/zh-Hant-TW.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "申請者 %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "Continue"; @@ -6821,7 +6820,6 @@ "What is username voting?" = "What is username voting?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "接下來會有什麼?"; @@ -7511,3 +7509,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "Votes: Low to high"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "No votes left"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/zh.lproj/Localizable.strings b/DashWallet/zh.lproj/Localizable.strings index b83ab2a8d4..274e552f68 100644 --- a/DashWallet/zh.lproj/Localizable.strings +++ b/DashWallet/zh.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "申请者 %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "继续"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "什么是用户名投票?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "接下来会有什么?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "投票: 从低到高"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "没有剩余投票"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWallet/zh_TW.lproj/Localizable.strings b/DashWallet/zh_TW.lproj/Localizable.strings index 5d5812a282..ec43462a25 100644 --- a/DashWallet/zh_TW.lproj/Localizable.strings +++ b/DashWallet/zh_TW.lproj/Localizable.strings @@ -1329,7 +1329,6 @@ "Contender %@" = "申請者 %@"; /* Voting */ -"Contender details" = "Contender details"; /* No comment provided by engineer. */ "Continue" = "繼續"; @@ -6819,7 +6818,6 @@ "What is username voting?" = "什麼是用戶名投票?"; /* Voting */ -"What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on." = "What this person published to show the name is theirs. None of it is verified by the network — it is what you are voting on."; /* DashPay FAQ */ "What's coming next?" = "接下來會有什麼?"; @@ -7509,3 +7507,32 @@ /* No comment provided by engineer. */ "Votes: Low to high" = "得票數:從低到高"; + +"Could not check how many votes this node has left." = "Could not check how many votes this node has left."; + +/* No comment provided by engineer. */ +"No votes left" = "沒有剩餘選票"; + +"The vote was not cast. Check your connection and try again." = "The vote was not cast. Check your connection and try again."; + +"The vote was not cast. Voting on this name has closed." = "The vote was not cast. Voting on this name has closed."; + +"The vote was not cast. This voting key does not belong to an active masternode." = "The vote was not cast. This voting key does not belong to an active masternode."; + +"The vote was not cast. Please try again." = "The vote was not cast. Please try again."; +"Hide requests for %@" = "Hide requests for %@"; +"Not provided" = "Not provided"; +"Not provided – %@" = "Not provided – %@"; +"Couldn't check for a link" = "Couldn't check for a link"; +"Vote to approve" = "Vote to approve"; +"Cancel approval" = "Cancel approval"; +"Voting period" = "Voting period"; +"All outcomes" = "All outcomes"; +"Opens the request details" = "Opens the request details"; +"Couldn't refresh." = "Couldn't refresh."; + +"Hides the requests for this name" = "Hides the requests for this name"; +"Takes your vote back" = "Takes your vote back"; + +/* Voting */ +"Review the posting below to verify the ownership of this username" = "Review the posting below to verify the ownership of this username"; diff --git a/DashWalletTests/MasternodeVoteCasterTests.swift b/DashWalletTests/MasternodeVoteCasterTests.swift new file mode 100644 index 0000000000..7441f9df84 --- /dev/null +++ b/DashWalletTests/MasternodeVoteCasterTests.swift @@ -0,0 +1,243 @@ +// +// MasternodeVoteCasterTests.swift +// DashWalletTests +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +@testable import dashpay +import SwiftDashSDK +import XCTest + +/// The caster's own vote-limit guard (AC-15) and its handling of a failed +/// history write, through an injected `VoteHistoryDAO`. +/// +/// Seams the production code must offer (the SDK call and the key derivation +/// cannot run in a unit test): +/// - `MasternodeVoteCaster.init(registry:contests:history:votingKey:send:)` +/// with `votingKey`/`send` defaulting to the registry and the SDK; +/// - `typealias VoteSender = (VoterNode, Data, VoteChoice, String) async throws -> Void` +/// (node, voting key, choice, normalizedLabel); +/// - the per-node loop reachable as an internal +/// `castAuthenticated(choice:onNormalizedLabel:with:) async -> VoteCastReport`. +@MainActor +final class MasternodeVoteCasterTests: XCTestCase { + + private let label = "johndoe" + private let choice = VoteChoice.towards(identityId: "contender-1") + + private func node(_ byte: UInt8) -> VoterNode { + VoterNode(proTxHash: Data([byte]), isEvonode: false, typeIndex: UInt32(byte), + serviceAddress: nil, keySource: .walletIndex(0)) + } + + private func record(_ node: VoterNode, casts: Int) -> CastVoteRecord { + CastVoteRecord(proTxHash: node.proTxHash, normalizedLabel: label, choice: choice, + castAt: Date(timeIntervalSince1970: 1_700_000_000), castCount: casts) + } + + private final class SendLog { + var sentTo: [Data] = [] + var failFor: Set = [] + } + + private func makeCaster(history: FakeVoteHistory, log: SendLog) -> MasternodeVoteCaster { + MasternodeVoteCaster( + registry: MasternodeVoterRegistry(), + contests: ContestedNamesService(), + history: history, + votingKey: { _ in Data(repeating: 1, count: 32) }, + send: { node, _, _, _ in + if log.failFor.contains(node.proTxHash) { throw FakeSendError.refused } + log.sentTo.append(node.proTxHash) + }) + } + + private func run(_ caster: MasternodeVoteCaster, nodes: [VoterNode]) async -> VoteCastReport { + await caster.castAuthenticated(choice: choice, onNormalizedLabel: label, with: nodes) + } + + func testNodeAtTheLimitIsNeverCast() async { + let a = node(0xA1) + let history = FakeVoteHistory(records: [record(a, casts: VoteLimit.maxCastsPerNode)]) + let log = SendLog() + + let report = await run(makeCaster(history: history, log: log), nodes: [a]) + + XCTAssertTrue(log.sentTo.isEmpty, "a node with no votes left must not be sent") + XCTAssertEqual(report.outcomes.count, 1) + XCTAssertFalse(report.outcomes[0].succeeded) + XCTAssertTrue(report.outcomes[0].failure?.lowercased().contains("no votes left") ?? false, + "reason was \(report.outcomes[0].failure ?? "nil")") + } + + func testNodeAtTheLimitIsSkippedWhileOthersCast() async { + let a = node(0xA1), b = node(0xB2) + let history = FakeVoteHistory(records: [ + record(a, casts: 5), record(b, casts: 4), + ]) + let log = SendLog() + + let report = await run(makeCaster(history: history, log: log), nodes: [a, b]) + + XCTAssertEqual(log.sentTo, [b.proTxHash]) + XCTAssertFalse(report.outcomes[0].succeeded) + XCTAssertTrue(report.outcomes[1].succeeded) + XCTAssertTrue(report.outcomes[1].historyRecorded) + } + + /// The count is re-read before each node's cast; the node whose read + /// fails is stopped, the others continue. + func testUnreadableHistoryStopsTheNodeWithoutCasting() async { + let a = node(0xA1), b = node(0xB2), c = node(0xC3) + let history = FakeVoteHistory(records: [], failingReads: [1]) // b's read + let log = SendLog() + + let report = await run(makeCaster(history: history, log: log), nodes: [a, b, c]) + + XCTAssertEqual(history.reads, 3, "one read per node") + XCTAssertFalse(log.sentTo.contains(b.proTxHash), "never cast on an unknown count") + XCTAssertFalse(report.outcomes[1].succeeded) + XCTAssertNotNil(report.outcomes[1].failure) + XCTAssertEqual(log.sentTo, [a.proTxHash, c.proTxHash], "the other nodes continue") + } + + /// A node's second cast reads the count its first one wrote. + func testASecondCastReadsTheCountTheFirstWrote() async { + let a = node(0xA1) + let history = FakeVoteHistory(records: [record(a, casts: VoteLimit.maxCastsPerNode - 1)]) + let log = SendLog() + let caster = makeCaster(history: history, log: log) + + _ = await run(caster, nodes: [a]) + let second = await run(caster, nodes: [a]) + + XCTAssertEqual(log.sentTo, [a.proTxHash], "the fifth cast went out, the sixth did not") + XCTAssertFalse(second.outcomes[0].succeeded) + XCTAssertEqual(history.records.first?.castCount, VoteLimit.maxCastsPerNode) + XCTAssertEqual(history.records.count, 1, "one row per node and contest") + } + + func testFailedHistoryWriteKeepsTheVoteLanded() async { + let a = node(0xA1) + let history = FakeVoteHistory(records: [], recordThrows: true) + let log = SendLog() + + let report = await run(makeCaster(history: history, log: log), nodes: [a]) + + XCTAssertEqual(log.sentTo, [a.proTxHash]) + XCTAssertTrue(report.outcomes[0].succeeded, "Platform accepted the vote") + XCTAssertFalse(report.outcomes[0].historyRecorded) + } + + func testRecordedVoteIsFlaggedRecordedAndWritten() async { + let a = node(0xA1) + let history = FakeVoteHistory(records: []) + let log = SendLog() + + let report = await run(makeCaster(history: history, log: log), nodes: [a]) + + XCTAssertTrue(report.outcomes[0].succeeded) + XCTAssertTrue(report.outcomes[0].historyRecorded) + XCTAssertEqual(history.recorded.map(\.proTxHash), [a.proTxHash]) + } + + func testFailedCastIsNotRecordedAndOtherNodesStillCast() async { + let a = node(0xA1), b = node(0xB2) + let history = FakeVoteHistory(records: []) + let log = SendLog() + log.failFor = [a.proTxHash] + + let report = await run(makeCaster(history: history, log: log), nodes: [a, b]) + + XCTAssertFalse(report.outcomes[0].succeeded) + XCTAssertTrue(report.outcomes[1].succeeded) + XCTAssertEqual(history.recorded.map(\.proTxHash), [b.proTxHash]) + } + + // MARK: Failure reasons are plain words, never Platform's text + + private func castFailing(with error: Error) async -> VoteOutcome { + let a = node(0xA1) + let caster = MasternodeVoteCaster( + registry: MasternodeVoterRegistry(), + contests: ContestedNamesService(), + history: FakeVoteHistory(records: []), + votingKey: { _ in Data(repeating: 1, count: 32) }, + send: { _, _, _, _ in throw error }) + return await run(caster, nodes: [a]).outcomes[0] + } + + func testPlatformTooManyVotesRefusalIsStoredAsNoVotesLeft() async { + let refusal = SDKError.consensusRejection(PlatformConsensusError(code: 40303, kind: .state), "RAW-PLATFORM-TEXT") + + let outcome = await castFailing(with: refusal) + + XCTAssertFalse(outcome.succeeded) + XCTAssertEqual(outcome.failure, "No votes left") + } + + func testGenericSendErrorNeverStoresRawText() async { + struct Odd: LocalizedError { var errorDescription: String? { "RAW-PLATFORM-TEXT odd" } } + + for error in [Odd() as Error, SDKError.internalError("RAW-PLATFORM-TEXT")] { + let outcome = await castFailing(with: error) + + XCTAssertFalse(outcome.succeeded) + XCTAssertEqual(outcome.failure, "The vote was not cast. Please try again.") + XCTAssertFalse(outcome.failure?.contains("RAW-PLATFORM-TEXT") ?? true) + } + } +} + +private enum FakeSendError: Error { case refused } +private enum FakeRecordError: Error { case disk } + +private final class FakeVoteHistory: VoteHistoryDAO, @unchecked Sendable { + var records: [CastVoteRecord] + /// Which reads (0-based, in call order) answer `nil`. The read is per + /// contest and carries no node, so the fake scripts calls, not nodes. + let failingReads: Set + private(set) var reads = 0 + let recordThrows: Bool + private(set) var recorded: [CastVoteRecord] = [] + + init(records: [CastVoteRecord], failingReads: Set = [], recordThrows: Bool = false) { + self.records = records + self.failingReads = failingReads + self.recordThrows = recordThrows + } + + func record(_ record: CastVoteRecord, network: String) async throws { + if recordThrows { throw FakeRecordError.disk } + recorded.append(record) + // As the DAO: one row per node and contest, its count raised. + let sameRow = { (row: CastVoteRecord) in + row.proTxHash == record.proTxHash && row.normalizedLabel == record.normalizedLabel + } + let previous = records.first(where: sameRow) + records.removeAll(where: sameRow) + var row = record + row.castCount = (previous?.castCount ?? 0) + 1 + records.append(row) + } + + func votes(forContest normalizedLabel: String, network: String) async -> [CastVoteRecord]? { + defer { reads += 1 } + return failingReads.contains(reads) ? nil : records + } + + func votes(forContests normalizedLabels: Set, network: String) async -> [CastVoteRecord]? { records } + func deleteAll() {} +} diff --git a/DashWalletTests/RequestDetailsViewModelTests.swift b/DashWalletTests/RequestDetailsViewModelTests.swift new file mode 100644 index 0000000000..42bbc79a81 --- /dev/null +++ b/DashWalletTests/RequestDetailsViewModelTests.swift @@ -0,0 +1,400 @@ +// +// RequestDetailsViewModelTests.swift +// DashWalletTests +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +@testable import dashpay +import SwiftDashSDK +import XCTest + +// MARK: - Fakes + +private final class FakeContests: VotingContestReading { + var result: Result<[DPNSContest], Error> = .success([]) + var state: DPNSContestVoteState? + func activeContests() async throws -> [DPNSContest] { try result.get() } + func voteState(normalizedLabel: String) async throws -> DPNSContestVoteState? { state } +} + +private final class FakeNodes: VotableMasternodeResolving { + var resolution = MasternodeVoterRegistry.Resolution(nodes: [], mayBeIncomplete: false) + var isNodeListSynced = true + func votableNodes() -> MasternodeVoterRegistry.Resolution { resolution } +} + +private struct FakeCaster: VoteCasting { + struct Unused: Error {} + func cast(choice: VoteChoice, onNormalizedLabel normalizedLabel: String, with nodes: [VoterNode]) async throws + -> VoteCastReport { + throw Unused() + } +} + +private final class FakeHistory: VoteHistoryDAO { + var records: [CastVoteRecord]? = [] + func record(_ record: CastVoteRecord, network: String) async throws {} + func votes(forContest normalizedLabel: String, network: String) async -> [CastVoteRecord]? { + records?.filter { $0.normalizedLabel == normalizedLabel } + } + func votes(forContests normalizedLabels: Set, network: String) async -> [CastVoteRecord]? { + records?.filter { normalizedLabels.contains($0.normalizedLabel) } + } + func deleteAll() {} +} + +private final class FakePrefs: VotingSelectionStoring { + var votingNodeSelection: Set = [] +} + +private struct LookupFailure: Error {} + +// MARK: - Tests + +/// Request details: what the screen shows for one request, the link states, +/// and whether the action approves or cancels an approval. +@MainActor +final class RequestDetailsViewModelTests: XCTestCase { + + private let epoch = Date(timeIntervalSince1970: 1_700_000_000) + private let label = "johndoe" + private let identityId = "johndoe-id2" + private var contests: FakeContests! + private var nodes: FakeNodes! + private var history: FakeHistory! + private var prefs: FakePrefs! + + override func setUp() { + super.setUp() + contests = FakeContests() + nodes = FakeNodes() + history = FakeHistory() + prefs = FakePrefs() + } + + private var votingEnd: Date { + var components = DateComponents() + components.year = 2026 + components.month = 10 + components.day = 25 + components.hour = 12 + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC")! + return calendar.date(from: components)! + } + + /// en_US + UTC, medium date: «Oct 25, 2026». + private var formatter: DateFormatter { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US") + formatter.timeZone = TimeZone(identifier: "UTC") + formatter.dateStyle = .medium + formatter.timeStyle = .none + return formatter + } + + private func node(_ byte: UInt8) -> VoterNode { + VoterNode(proTxHash: Data([byte]), isEvonode: false, typeIndex: UInt32(byte), + serviceAddress: nil, keySource: .walletIndex(0)) + } + + private func contest(endTime: Date? = nil) -> DPNSContest { + let contenders = [ + DPNSContender(identityId: "johndoe-id1", voteTally: 2, displayLabel: "JohnDoe"), + DPNSContender(identityId: identityId, voteTally: 4, displayLabel: "johndoe") + ] + return DPNSContest(normalizedLabel: label, endTime: endTime, hasWinner: false, + abstainVotes: 0, lockVotes: 0, contenders: contenders) + } + + private func vote(_ node: VoterNode, _ choice: VoteChoice) -> CastVoteRecord { + CastVoteRecord(proTxHash: node.proTxHash, normalizedLabel: label, choice: choice, castAt: epoch) + } + + private func makeStore() async -> VotingStore { + let store = VotingStore(contests: contests, nodes: nodes, caster: FakeCaster(), history: history, + prefs: prefs) + await store.refresh() + return store + } + + /// Links handed to the system to open. + private var opened: [URL] = [] + + private func makeVM( + _ store: VotingStore, + link: @escaping (String, String) async throws -> URL? = { _, _ in nil } + ) -> RequestDetailsViewModel { + RequestDetailsViewModel(store: store, normalizedLabel: label, identityId: identityId, + linkLookup: link, dateFormatter: formatter, + openLink: { [weak self] in self?.opened.append($0) }) + } + + // MARK: Fields (AC-11) + + func testShowsUsernameIdentityAndVotingEndFromTheStore() async { + contests.result = .success([contest(endTime: votingEnd)]) + let vm = makeVM(await makeStore()) + + XCTAssertEqual(vm.username, "johndoe") + XCTAssertEqual(vm.identityId, "johndoe-id2") + XCTAssertEqual(vm.votingEnd, votingEnd) + } + + func testRequestDateIsUnknownBeforeStage5bSoThePeriodReadsNotProvidedThenTheVotingEnd() async { + contests.result = .success([contest(endTime: votingEnd)]) + let vm = makeVM(await makeStore()) + + XCTAssertNil(vm.requestDate) + XCTAssertEqual(vm.votingPeriodText, "Not provided – Oct 25, 2026") + } + + // MARK: Link states + + func testLinkStartsInReadingStateBeforeTheLookupRuns() async { + contests.result = .success([contest()]) + let vm = makeVM(await makeStore()) + + XCTAssertEqual(vm.linkState, .reading) + XCTAssertNil(vm.linkText, "no text while the check is in flight") + } + + func testNoPublishedLinkReadsNotProvided() async { + contests.result = .success([contest()]) + let vm = makeVM(await makeStore(), link: { _, _ in nil }) + + await vm.loadLink() + + XCTAssertEqual(vm.linkState, .none) + XCTAssertEqual(vm.linkText, "Not provided") + } + + func testFailedLookupReadsCouldntCheckAndNeverNotProvided() async { + contests.result = .success([contest()]) + let vm = makeVM(await makeStore(), link: { _, _ in throw LookupFailure() }) + + await vm.loadLink() + + XCTAssertEqual(vm.linkState, .failed) + XCTAssertEqual(vm.linkText, "Couldn't check for a link") + XCTAssertNotEqual(vm.linkText, "Not provided", "the check never ran (guardrail 3)") + } + + func testPublishedLinkShowsTheFullURL() async { + contests.result = .success([contest()]) + let url = URL(string: "https://example.com/proof/johndoe")! + let vm = makeVM(await makeStore(), link: { _, _ in url }) + + await vm.loadLink() + + XCTAssertEqual(vm.linkState, .published(url)) + XCTAssertEqual(vm.linkText, "https://example.com/proof/johndoe") + } + + func testLookupIsAskedForThisRequestsLabelAndIdentity() async { + contests.result = .success([contest()]) + var asked: (String, String)? + let vm = makeVM(await makeStore(), link: { label, identity in + asked = (label, identity) + return nil + }) + + await vm.loadLink() + + XCTAssertEqual(asked?.0, "johndoe") + XCTAssertEqual(asked?.1, "johndoe-id2") + } + + func testStateIsReadingWhileALaterLookupIsInFlight() async { + contests.result = .success([contest()]) + var release: CheckedContinuation? + var started = false + var first = true + let vm = makeVM(await makeStore(), link: { _, _ in + if first { first = false; return nil } + started = true + return try await withCheckedThrowingContinuation { release = $0 } + }) + await vm.loadLink() + XCTAssertEqual(vm.linkState, .none) + + let retry = Task { await vm.loadLink() } + while !started { await Task.yield() } + + XCTAssertEqual(vm.linkState, .reading) + release?.resume(returning: nil) + await retry.value + XCTAssertEqual(vm.linkState, .none) + } + + // MARK: My approve (AC-17) + + func testActionIsCancelApprovalWhenATickedNodesLiveChoiceApprovesThisRequest() async { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + contests.result = .success([contest()]) + history.records = [vote(a, .towards(identityId: identityId))] + let vm = makeVM(await makeStore()) + + XCTAssertEqual(vm.approveAction, .cancelApproval) + XCTAssertEqual(vm.approveTitle, "Cancel approval") + } + + func testActionIsVoteToApproveWhenNobodyVoted() async { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + contests.result = .success([contest()]) + let vm = makeVM(await makeStore()) + + XCTAssertEqual(vm.approveAction, .voteToApprove) + XCTAssertEqual(vm.approveTitle, "Vote to approve") + } + + func testActionIsVoteToApproveWhenTheLiveChoiceIsAnotherRequest() async { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + contests.result = .success([contest()]) + history.records = [vote(a, .towards(identityId: "johndoe-id1"))] + let vm = makeVM(await makeStore()) + + XCTAssertEqual(vm.approveAction, .voteToApprove) + } + + func testActionIsVoteToApproveWhenTheLiveChoiceIsBlockOrAbstain() async { + let a = node(1), b = node(2) + nodes.resolution = .init(nodes: [a, b], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash, b.proTxHash] + contests.result = .success([contest()]) + history.records = [vote(a, .lock), vote(b, .abstain)] + let vm = makeVM(await makeStore()) + + XCTAssertEqual(vm.approveAction, .voteToApprove) + } + + func testOnlyTickedNodesCountForCancelApproval() async { + let a = node(1), b = node(2) + nodes.resolution = .init(nodes: [a, b], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + contests.result = .success([contest()]) + history.records = [vote(b, .towards(identityId: identityId))] + let vm = makeVM(await makeStore()) + + XCTAssertEqual(vm.approveAction, .voteToApprove, "the approving node is not ticked") + } + + // MARK: Cancel approval sends only from the nodes holding it (AC-17) + + func testCancelApprovalAbstainsOnlyFromTheTickedNodesHoldingThisApprove() async throws { + let a = node(1), b = node(2) + nodes.resolution = .init(nodes: [a, b], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash, b.proTxHash] + contests.result = .success([contest()]) + history.records = [vote(a, .towards(identityId: identityId)), vote(b, .lock)] + let store = await makeStore() + let vm = makeVM(store) + + let request = try XCTUnwrap(vm.voteRequest()) + + XCTAssertEqual(request.choice, .abstain) + XCTAssertEqual(request.cancelling, .towards(identityId: identityId)) + XCTAssertEqual(store.nodesToCancel(.towards(identityId: identityId), on: label).map(\.proTxHash), + [a.proTxHash], "b's block on the name is not touched") + } + + func testVoteToApproveAsksForThisRequestsApprove() async throws { + contests.result = .success([contest()]) + let vm = makeVM(await makeStore()) + + let request = try XCTUnwrap(vm.voteRequest()) + + XCTAssertEqual(request.choice, .towards(identityId: identityId)) + XCTAssertNil(request.cancelling) + } + + // MARK: No dead button (AC-03, AC-11) + + func testApproveIsEnabledWithoutVotingKeysSoTheKeyFlowCanOpen() async { + contests.result = .success([contest(endTime: Date().addingTimeInterval(86_400))]) + let vm = makeVM(await makeStore()) + XCTAssertTrue(vm.canApprove) + } + + func testApproveIsDisabledOnceTheContestClosed() async { + contests.result = .success([contest(endTime: Date().addingTimeInterval(86_400))]) + let store = await makeStore() + let vm = makeVM(store) + + contests.state = DPNSContestVoteState(normalizedLabel: label, contenders: [], abstainVotes: 0, lockVotes: 0, + outcome: .locked, resolvedAt: epoch) + await store.refreshContest(normalizedLabel: label) + + XCTAssertFalse(vm.canApprove) + } + + func testApproveIsDisabledWhenNoTickedNodeHasAVoteLeft() async { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + contests.result = .success([contest()]) + history.records = [CastVoteRecord(proTxHash: a.proTxHash, normalizedLabel: label, choice: .lock, + castAt: epoch, castCount: VoteLimit.maxCastsPerNode)] + let vm = makeVM(await makeStore()) + + XCTAssertFalse(vm.canApprove) + } + + /// The contest left the list while the screen was open: the fields keep + /// what they showed, and the button no longer pretends it can vote. + func testFieldsKeepTheLastKnownContestAfterItLeftTheList() async { + let renamed = DPNSContest( + normalizedLabel: label, endTime: nil, hasWinner: false, abstainVotes: 0, lockVotes: 0, + contenders: [DPNSContender(identityId: identityId, voteTally: 4, displayLabel: "JohnDOE")]) + contests.result = .success([renamed]) + let store = await makeStore() + let vm = makeVM(store) + XCTAssertEqual(vm.username, "JohnDOE") + + contests.result = .success([]) + await store.refresh() + + XCTAssertEqual(vm.username, "JohnDOE") + XCTAssertFalse(vm.canApprove) + } + + // MARK: The link opens outside the app (AC-11) + + func testTappingAWebLinkHandsTheFullLinkToTheSystem() async throws { + contests.result = .success([contest()]) + let vm = makeVM(await makeStore()) + let url = try XCTUnwrap(URL(string: "https://x.com/johndoe/status/1?ref=dash")) + + vm.open(url) + + XCTAssertEqual(opened, [url]) + } + + func testACustomSchemeLinkIsNeverOpened() async throws { + contests.result = .success([contest()]) + let vm = makeVM(await makeStore()) + + vm.open(try XCTUnwrap(URL(string: "dash:XyZ?amount=10"))) + + XCTAssertEqual(opened, []) + } +} diff --git a/DashWalletTests/VoteHistoryDAOTests.swift b/DashWalletTests/VoteHistoryDAOTests.swift new file mode 100644 index 0000000000..3214399816 --- /dev/null +++ b/DashWalletTests/VoteHistoryDAOTests.swift @@ -0,0 +1,126 @@ +// +// VoteHistoryDAOTests.swift +// DashWalletTests +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import SQLite +import XCTest +@testable import dashpay + +/// `VoteHistoryDAOImpl` against an in-memory database: the upsert raises +/// `castCount`, and a failed write throws instead of being logged away. +final class VoteHistoryDAOTests: XCTestCase { + + private let network = "testnet" + private let label = "johndoe" + private let node = Data([0xA1, 0xB2]) + private let epoch = Date(timeIntervalSince1970: 1_700_000_000) + + /// The two vote-history migrations, applied in version order from the host + /// app's own `Migrations.bundle`, so the schema cannot drift from the app's. + private static let migrationFiles = [ + "20260808030000_add_masternode_vote_history", + "20260922120000_vote_history_cast_count", + ] + + private func makeConnection(createTable: Bool = true) throws -> Connection { + let connection = try Connection(.inMemory) + guard createTable else { return connection } + let bundle = DatabaseConnection.migrationsBundle() + for name in Self.migrationFiles { + let url = try XCTUnwrap(bundle.url(forResource: name, withExtension: "sql"), name) + try connection.execute(String(contentsOf: url, encoding: .utf8)) + } + return connection + } + + private func vote(_ choice: VoteChoice, at offset: TimeInterval = 0) -> CastVoteRecord { + CastVoteRecord(proTxHash: node, normalizedLabel: label, choice: choice, + castAt: epoch.addingTimeInterval(offset)) + } + + func testRepeatedRecordRaisesCastCountAndKeepsOneRow() async throws { + let dao = VoteHistoryDAOImpl(connection: try makeConnection()) + + try await dao.record(vote(.towards(identityId: "c1")), network: network) + try await dao.record(vote(.lock, at: 10), network: network) + try await dao.record(vote(.abstain, at: 20), network: network) + + let rows = await dao.votes(forContest: label, network: network) + XCTAssertEqual(rows?.count, 1) + XCTAssertEqual(rows?.first?.castCount, 3) + XCTAssertEqual(rows?.first?.choice, .abstain) + } + + /// A vote recorded before `castCount` existed counts as one cast after + /// the upgrade, and later votes on the same contest add to it. + func testUpgradeCountsAnExistingVoteOnceAndReplacementsAccumulate() async throws { + let connection = try makeConnection(createTable: false) + let bundle = DatabaseConnection.migrationsBundle() + let sql = { (name: String) throws -> String in + let url = try XCTUnwrap(bundle.url(forResource: name, withExtension: "sql"), name) + return try String(contentsOf: url, encoding: .utf8) + } + try connection.execute(sql(Self.migrationFiles[0])) + try connection.run( + """ + INSERT INTO masternode_vote_history + (proTxHash, normalizedLabel, network, choice, contenderIdentityId, castAt) + VALUES (?, ?, ?, 'abstain', NULL, 1) + """, + [Blob(bytes: [UInt8](node)), label, network] as [Binding?]) + try connection.execute(sql(Self.migrationFiles[1])) + + let dao = VoteHistoryDAOImpl(connection: connection) + let upgraded = await dao.votes(forContest: label, network: network) + XCTAssertEqual(upgraded?.map(\.castCount), [1], "an existing row is one cast") + + let choices: [VoteChoice] = [.lock, .abstain, .towards(identityId: "c1"), .lock] + for (index, choice) in choices.enumerated() { + try await dao.record(vote(choice, at: TimeInterval(10 + index)), network: network) + } + + let rows = await dao.votes(forContest: label, network: network) + XCTAssertEqual(rows?.count, 1) + XCTAssertEqual(rows?.first?.castCount, 5) + XCTAssertEqual(rows?.first?.choice, .lock, "the row holds the latest vote") + } + + /// On a fresh store a node's first vote is one cast, and the whole-list + /// read the voting screen uses returns it. + func testAFreshStoreStartsEachNodeAtOneCast() async throws { + let dao = VoteHistoryDAOImpl(connection: try makeConnection()) + + try await dao.record(vote(.abstain), network: network) + + let rows = await dao.votes(forContest: label, network: network) + XCTAssertEqual(rows?.map(\.castCount), [1]) + let listed = await dao.votes(forContests: [label, "other"], network: network) + XCTAssertEqual(listed?.map(\.normalizedLabel), [label]) + XCTAssertEqual(listed?.map(\.castCount), [1]) + } + + func testRecordThrowsWhenTheWriteFails() async throws { + let dao = VoteHistoryDAOImpl(connection: try makeConnection(createTable: false)) + + do { + try await dao.record(vote(.lock), network: network) + XCTFail("record must throw when the write fails") + } catch { + // expected + } + } +} diff --git a/DashWalletTests/VoteHistoryPersistenceTests.swift b/DashWalletTests/VoteHistoryPersistenceTests.swift deleted file mode 100644 index 4e97e0bead..0000000000 --- a/DashWalletTests/VoteHistoryPersistenceTests.swift +++ /dev/null @@ -1,97 +0,0 @@ -// -// VoteHistoryPersistenceTests.swift -// DashWalletTests -// -// Copyright © 2026 Dash Core Group. All rights reserved. -// -// Licensed under the MIT License (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://opensource.org/licenses/MIT -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -@testable import dashpay -import SQLite -import XCTest - -/// The five-cast ceiling counts casts, and the table keeps one row per node -/// and contest: the count lives in `castCount`, added by its own migration and -/// incremented by the upsert. Run against a private in-memory database built -/// from the app's own migration files. -final class VoteHistoryPersistenceTests: XCTestCase { - private let label = "a11ce" - private let network = "testnet" - private let node = Data(repeating: 7, count: 32) - - private func migrationSQL(_ name: String) throws -> String { - let url = try XCTUnwrap( - DatabaseConnection.migrationsBundle().url(forResource: name, withExtension: "sql"), - "missing migration \(name)") - return try String(contentsOf: url, encoding: .utf8) - } - - private func castCounts(_ db: Connection) throws -> [Int64] { - try db.prepare("SELECT castCount FROM masternode_vote_history").compactMap { $0[0] as? Int64 } - } - - func testUpgradeCountsAnExistingVoteOnceAndReplacementsAccumulate() async throws { - let db = try Connection(.inMemory) - try db.execute(migrationSQL("20260808030000_add_masternode_vote_history")) - - // A vote recorded before the column existed. - try db.run( - """ - INSERT INTO masternode_vote_history - (proTxHash, normalizedLabel, network, choice, contenderIdentityId, castAt) - VALUES (?, ?, ?, 'abstain', NULL, 1) - """, - [Blob(bytes: [UInt8](node)), label, network] as [Binding?]) - - try db.execute(migrationSQL("20260922120000_vote_history_cast_count")) - XCTAssertEqual(try castCounts(db), [1], "an existing row is at least one cast") - - // Four changes of mind through the persistence boundary. - let dao = VoteHistoryDAOImpl(connection: db) - let choices: [VoteChoice] = [.lock, .abstain, .towards(identityId: "contender"), .lock] - for (index, choice) in choices.enumerated() { - await dao.record( - CastVoteRecord( - proTxHash: node, normalizedLabel: label, choice: choice, - castAt: Date(timeIntervalSince1970: Double(10 + index))), - network: network) - } - - XCTAssertEqual(try castCounts(db), [5], "one row, five casts") - let stored = await dao.votes(forContest: label, network: network) - XCTAssertEqual(stored?.count, 1) - XCTAssertEqual(stored?.first?.castCount, 5) - XCTAssertEqual(stored?.first?.choice, .lock, "the row holds the latest vote") - } - - func testAFreshStoreStartsEachNodeAtOneCast() async throws { - let db = try Connection(.inMemory) - try db.execute(migrationSQL("20260808030000_add_masternode_vote_history")) - try db.execute(migrationSQL("20260922120000_vote_history_cast_count")) - - let dao = VoteHistoryDAOImpl(connection: db) - await dao.record( - CastVoteRecord(proTxHash: node, normalizedLabel: label, choice: .abstain, castAt: Date()), - network: network) - - let stored = await dao.votes(forContest: label, network: network) - XCTAssertEqual(stored?.map(\.castCount), [1]) - // The list reads every contest's history in one query; it sees the same row. - let listed = await dao.votes(forContests: [label, "other"], network: network) - XCTAssertEqual(listed?.map(\.normalizedLabel), [label]) - XCTAssertEqual(listed?.map(\.castCount), [1]) - let unlisted = await dao.votes(forContests: ["other"], network: network) - XCTAssertEqual(unlisted?.isEmpty, true) - } -} diff --git a/DashWalletTests/VoteLimitTests.swift b/DashWalletTests/VoteLimitTests.swift new file mode 100644 index 0000000000..e4d980efee --- /dev/null +++ b/DashWalletTests/VoteLimitTests.swift @@ -0,0 +1,126 @@ +// +// VoteLimitTests.swift +// DashWalletTests +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +@testable import dashpay +import XCTest + +/// The per-masternode vote history and the five-vote limit, as pure values. +final class VoteLimitTests: XCTestCase { + + private let nodeA = Data([0xA1]) + private let nodeB = Data([0xB2]) + private let nodeC = Data([0xC3]) + private let approve = VoteChoice.towards(identityId: "contender-1") + private let epoch = Date(timeIntervalSince1970: 1_700_000_000) + + private func record(_ node: Data, _ choice: VoteChoice, casts: Int, at offset: TimeInterval = 0) -> CastVoteRecord { + CastVoteRecord( + proTxHash: node, normalizedLabel: "johndoe", choice: choice, + castAt: epoch.addingTimeInterval(offset), castCount: casts) + } + + func testCeilingIsFive() { + XCTAssertEqual(VoteLimit.maxCastsPerNode, 5) + } + + func testVotesLeftByCastCount() { + let table: [(casts: Int, left: Int)] = [(1, 4), (3, 2), (4, 1), (5, 0)] + for row in table { + let limit = VoteLimit([record(nodeA, .lock, casts: row.casts)]) + XCTAssertEqual(limit.votesLeft(nodeA), row.left, "casts \(row.casts)") + XCTAssertEqual(limit.fewestVotesLeft(among: [nodeA]), row.left, "casts \(row.casts)") + } + } + + func testAbstainCountsTowardsTheLimit() { + let limit = VoteLimit([record(nodeA, .abstain, casts: 5)]) + XCTAssertEqual(limit.votesLeft(nodeA), 0) + } + + func testNodeWithoutRowHasFiveLeftAndNoChoice() { + let limit = VoteLimit([record(nodeA, .lock, casts: 2)]) + XCTAssertEqual(limit.votesLeft(nodeB), 5) + XCTAssertEqual(limit.filledChoices(of: [nodeB]), []) + XCTAssertEqual(limit.nodes(holding: .lock, among: [nodeB]), []) + } + + func testFewestLeftFollowsTheMostSpentNode() { + let limit = VoteLimit([record(nodeA, .lock, casts: 4), record(nodeB, .lock, casts: 1)]) + XCTAssertEqual(limit.fewestVotesLeft(among: [nodeA, nodeB]), 1) + XCTAssertEqual(limit.fewestVotesLeft(among: [nodeB]), 4) + XCTAssertEqual(limit.fewestVotesLeft(among: [nodeB, nodeC]), 4) + } + + func testNoVotesLeftOnlyWhenEveryNodeIsSpent() { + let limit = VoteLimit([record(nodeA, .lock, casts: 5), record(nodeB, .lock, casts: 2)]) + XCTAssertEqual(limit.nodesWithVotesLeft(among: [nodeA, nodeB]), [nodeB]) + XCTAssertEqual(limit.nodesWithVotesLeft(among: [nodeA]), []) + } + + func testTwoNodesWithDifferentChoicesAreBothReported() { + let limit = VoteLimit([record(nodeA, .lock, casts: 1), record(nodeB, approve, casts: 1)]) + XCTAssertEqual(limit.filledChoices(of: [nodeA, nodeB]), [.lock, approve]) + XCTAssertEqual(limit.filledChoices(of: [nodeB]), [approve]) + XCTAssertEqual(limit.nodes(holding: approve, among: [nodeA, nodeB]), [nodeB]) + XCTAssertEqual(limit.nodes(holding: .lock, among: [nodeA, nodeB]), [nodeA]) + } + + func testAbstainOnlyIsNotAFilledPillButStillHeld() { + let limit = VoteLimit([record(nodeA, .abstain, casts: 2)]) + XCTAssertEqual(limit.filledChoices(of: [nodeA]), []) + XCTAssertEqual(limit.nodes(holding: .abstain, among: [nodeA]), [nodeA]) + } + + func testLatestRecordOfANodeWins() { + let limit = VoteLimit([record(nodeA, .lock, casts: 2, at: 0), record(nodeA, approve, casts: 3, at: 10)]) + XCTAssertEqual(limit.filledChoices(of: [nodeA]), [approve]) + XCTAssertEqual(limit.votesLeft(nodeA), 2) + } + + func testRecordCastSpendsOneAndChangesTheChoice() { + var limit = VoteLimit([record(nodeA, approve, casts: 3)]) + limit.recordCast(of: nodeA, on: "johndoe", choice: .abstain, at: epoch) + XCTAssertEqual(limit.votesLeft(nodeA), 1) + XCTAssertEqual(limit.filledChoices(of: [nodeA]), []) + } + + /// An older cast merged onto a newer row spends one but keeps the newer choice. + func testRecordCastOlderThanTheLiveChoiceSpendsOneButKeepsTheChoice() { + var limit = VoteLimit([record(nodeA, approve, casts: 2, at: 10)]) + limit.recordCast(of: nodeA, on: "johndoe", choice: .lock, at: epoch) + XCTAssertEqual(limit.votesLeft(nodeA), 2) + XCTAssertEqual(limit.liveChoice(of: nodeA), approve) + } + + func testUnknownHistoryIsUnknownNotNoVotes() { + let limit = VoteLimit(nil) + XCTAssertFalse(limit.isKnown) + XCTAssertNil(limit.votesLeft(nodeA)) + XCTAssertNil(limit.fewestVotesLeft(among: [nodeA])) + XCTAssertNil(limit.filledChoices(of: [nodeA])) + XCTAssertNil(limit.nodes(holding: approve, among: [nodeA])) + XCTAssertNil(limit.nodesWithVotesLeft(among: [nodeA])) + } + + func testEmptyKnownHistoryIsKnown() { + let limit = VoteLimit([]) + XCTAssertTrue(limit.isKnown) + XCTAssertEqual(limit.votesLeft(nodeA), 5) + } +} diff --git a/DashWalletTests/VotingFilterTests.swift b/DashWalletTests/VotingFilterTests.swift index 4cb3a3fb1a..2a70e8c6ed 100644 --- a/DashWalletTests/VotingFilterTests.swift +++ b/DashWalletTests/VotingFilterTests.swift @@ -82,11 +82,25 @@ final class VotingFilterTests: XCTestCase { XCTAssertEqual(labels(filter), ["approved"]) } - /// Any recorded vote counts, block and abstain included. - func testIHaveNotVotedKeepsOnlyNamesWithoutAVote() { + /// AC-07: a block or an approve counts as voted; no record, or abstain + /// only, does not. + func testIHaveNotVotedKeepsNamesWithNoVoteOrOnlyAnAbstain() { var filter = VotingFilter.default filter.type = .notVoted - XCTAssertEqual(labels(filter), ["untouched"]) + XCTAssertEqual(labels(filter), ["abstained", "untouched"]) + } + + /// An abstain next to a block or an approve is still a vote. + func testIHaveNotVotedDropsANameWithAbstainAndAnotherVote() { + let mixed: [String: Set] = [ + "approved": [.abstain, .towards(identityId: "approved-0")], + "blocked": [.abstain, .lock], + ] + var filter = VotingFilter.default + filter.type = .notVoted + XCTAssertEqual( + filter.apply(to: contests) { mixed[$0] ?? [] }.map(\.normalizedLabel), + ["abstained", "untouched"]) } func testHasBlockedVotesReadsTheTallyNotThisWalletsVote() { @@ -101,7 +115,7 @@ final class VotingFilterTests: XCTestCase { XCTAssertEqual(labels(filter), ["abstained", "untouched"]) filter.type = .notVoted - XCTAssertEqual(labels(filter), ["untouched"]) + XCTAssertEqual(labels(filter), ["abstained", "untouched"]) } /// Days stay soonest first whatever the sort; the sort orders names inside a day. diff --git a/DashWalletTests/VotingListSectionTests.swift b/DashWalletTests/VotingListSectionTests.swift index e933a343d0..7997624feb 100644 --- a/DashWalletTests/VotingListSectionTests.swift +++ b/DashWalletTests/VotingListSectionTests.swift @@ -54,6 +54,20 @@ final class VotingListSectionTests: XCTestCase { XCTAssertEqual(sections[1].contests.map(\.normalizedLabel), ["early-tomorrow"]) } + /// AC-01: the day follows the device's time zone. 23:30 UTC on 2 Nov is + /// still 2 Nov in UTC but already 3 Nov in Kyiv. + func testATimeZoneChangeMovesAContestAcrossADay() throws { + var utc = Calendar(identifier: .gregorian) + utc.timeZone = try XCTUnwrap(TimeZone(identifier: "UTC")) + let morning = try XCTUnwrap(utc.date(from: DateComponents(year: 2026, month: 11, day: 2, hour: 8))) + let end = try XCTUnwrap(utc.date(from: DateComponents(year: 2026, month: 11, day: 2, hour: 23, minute: 30))) + let late = DPNSContest(normalizedLabel: "late", endTime: end, hasWinner: false, + abstainVotes: 0, lockVotes: 0, contenders: []) + + XCTAssertEqual(VotingListSection.group([late], now: morning, calendar: utc).map(\.daysLeft), [0]) + XCTAssertEqual(VotingListSection.group([late], now: morning, calendar: calendar).map(\.daysLeft), [1]) + } + /// A contest whose end has already passed is closing, so it reads as /// "today", never as a negative number of days. func testPastEndCountsAsToday() { @@ -89,17 +103,17 @@ final class VotingListSectionTests: XCTestCase { /// more of its casts. func testRecordedCastUpdatesTheLiveVoteAndTheCastCount() { let node = Data([1, 2, 3]) - var history = VotingViewModel.NodeVoteHistory([ + var history = VoteLimit([ CastVoteRecord(proTxHash: node, normalizedLabel: "pizza", choice: .lock, castAt: now, castCount: 4), ]) - XCTAssertTrue(history.hasCastsLeft(node)) + XCTAssertEqual(history.votesLeft(node), 1) history.recordCast(of: node, on: "pizza", choice: .abstain, at: now.addingTimeInterval(60)) XCTAssertEqual(history.liveChoice(of: node), .abstain) - XCTAssertEqual(history.liveChoices(of: [node]), [.abstain]) - XCTAssertFalse(history.hasCastsLeft(node), "the fifth cast spends the last one") + XCTAssertEqual(history.nodes(holding: .abstain, among: [node]), [node]) + XCTAssertEqual(history.votesLeft(node), 0, "the fifth cast spends the last one") } func testVotedToastNamesTheUsername() { diff --git a/DashWalletTests/VotingListViewModelTests.swift b/DashWalletTests/VotingListViewModelTests.swift new file mode 100644 index 0000000000..f9fb7e427e --- /dev/null +++ b/DashWalletTests/VotingListViewModelTests.swift @@ -0,0 +1,628 @@ +// +// VotingListViewModelTests.swift +// DashWalletTests +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +@testable import dashpay +import SwiftDashSDK +import XCTest + +// MARK: - Fakes + +private final class FakeContests: VotingContestReading { + var result: Result<[DPNSContest], Error> = .success([]) + var state: DPNSContestVoteState? + func activeContests() async throws -> [DPNSContest] { try result.get() } + func voteState(normalizedLabel: String) async throws -> DPNSContestVoteState? { state } +} + +private final class FakeNodes: VotableMasternodeResolving { + var resolution = MasternodeVoterRegistry.Resolution(nodes: [], mayBeIncomplete: false) + var isNodeListSynced = true + func votableNodes() -> MasternodeVoterRegistry.Resolution { resolution } +} + +private struct FakeCaster: VoteCasting { + struct Unused: Error {} + func cast(choice: VoteChoice, onNormalizedLabel normalizedLabel: String, with nodes: [VoterNode]) async throws + -> VoteCastReport { + throw Unused() + } +} + +private final class FakeHistory: VoteHistoryDAO { + var records: [CastVoteRecord]? = [] + func record(_ record: CastVoteRecord, network: String) async throws {} + func votes(forContest normalizedLabel: String, network: String) async -> [CastVoteRecord]? { + records?.filter { $0.normalizedLabel == normalizedLabel } + } + /// While set, the next contests-wide read waits for ``releaseRead()``. + var holdsNextRead = false + private(set) var isHolding = false + private var held: CheckedContinuation? + func releaseRead() { + held?.resume() + held = nil + } + func votes(forContests normalizedLabels: Set, network: String) async -> [CastVoteRecord]? { + if holdsNextRead { + holdsNextRead = false + isHolding = true + await withCheckedContinuation { held = $0 } + isHolding = false + } + return records?.filter { normalizedLabels.contains($0.normalizedLabel) } + } + func deleteAll() {} +} + +private final class FakePrefs: VotingSelectionStoring { + var votingNodeSelection: Set = [] +} + +// MARK: - Tests + +/// The list view model's several-request rows: expand in place, one approve +/// pill per request filled from the ticked nodes' votes, and the spoken labels. +@MainActor +final class VotingListViewModelTests: XCTestCase { + + private let epoch = Date(timeIntervalSince1970: 1_700_000_000) + private var contests: FakeContests! + private var nodes: FakeNodes! + private var history: FakeHistory! + private var prefs: FakePrefs! + + override func setUp() { + super.setUp() + contests = FakeContests() + nodes = FakeNodes() + history = FakeHistory() + prefs = FakePrefs() + } + + private func makeStore() -> VotingStore { + VotingStore(contests: contests, nodes: nodes, caster: FakeCaster(), history: history, prefs: prefs) + } + + private func makeList(_ store: VotingStore) -> VotingListViewModel { + VotingListViewModel(store: store, normalizedLabel: { $0.lowercased() }) + } + + private func node(_ byte: UInt8) -> VoterNode { + VoterNode(proTxHash: Data([byte]), isEvonode: false, typeIndex: UInt32(byte), + serviceAddress: nil, keySource: .walletIndex(0)) + } + + private func contest(_ label: String, requests: Int) -> DPNSContest { + let contenders = (1...requests).map { + DPNSContender(identityId: "\(label)-id\($0)", voteTally: UInt32($0 * 2)) + } + return DPNSContest(normalizedLabel: label, endTime: nil, hasWinner: false, + abstainVotes: 0, lockVotes: 0, contenders: contenders) + } + + private func vote(_ node: VoterNode, on label: String, _ choice: VoteChoice) -> CastVoteRecord { + CastVoteRecord(proTxHash: node.proTxHash, normalizedLabel: label, choice: choice, castAt: epoch) + } + + // MARK: What the list shows instead of rows (AC-02, AC-08, AC-09) + + private struct RawError: LocalizedError { + var errorDescription: String? { "Network Error: RAW-SDK-TEXT" } + } + + private func single(_ label: String, lock: UInt32 = 0) -> DPNSContest { + DPNSContest(normalizedLabel: label, endTime: nil, hasWinner: false, abstainVotes: 0, lockVotes: lock, + contenders: [DPNSContender(identityId: "\(label)-id1", voteTally: 1)]) + } + + /// One ticked node with a readable, empty history. + private func votingWallet() { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + } + + func testLoadingUntilTheFirstLoadFinishes() { + XCTAssertEqual(makeList(makeStore()).emptyState, .loading) + } + + func testFailedFirstLoadIsCouldNotLoad() async { + contests.result = .failure(RawError()) + let store = makeStore() + let list = makeList(store) + await store.refresh() + XCTAssertEqual(list.emptyState, .couldNotLoad) + } + + /// AC-02: the banner over kept rows says it in plain words, never the + /// error's own text. + func testRefreshFailedBannerIsPlainWords() async { + contests.result = .success([single("kept")]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + XCTAssertNil(list.refreshFailedText) + + contests.result = .failure(RawError()) + await store.refresh() + + XCTAssertEqual(list.refreshFailedText, "Couldn't refresh.") + XCTAssertNil(list.emptyState, "the kept rows show") + } + + func testNoOpenContests() async { + let store = makeStore() + let list = makeList(store) + await store.refresh() + XCTAssertEqual(list.emptyState, .noContests) + } + + /// AC-08: the filter keeps nothing — never the no-contests state. + func testFilterThatKeepsNothingIsNoMatchNotNoContests() async { + contests.result = .success([single("alice")]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + + list.filter.type = .hasBlockedVotes + + XCTAssertEqual(list.emptyState, .filterMatchesNothing) + } + + func testSearchThatFindsNothingIsNoSearchMatch() async { + contests.result = .success([single("alice")]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + + list.searchQuery = "zzz" + + XCTAssertEqual(list.emptyState, .searchMatchesNothing) + } + + func testRowsShowNoEmptyState() async { + contests.result = .success([single("alice")]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + XCTAssertNil(list.emptyState) + } + + /// AC-09, no voting keys: the wallet holds no vote to filter by. + func testMyVotesFilterWithoutVotingKeysCannotFilter() async { + contests.result = .success([single("alice")]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + + list.filter.type = .notVoted + + guard case .cannotFilterByMyVotes(let reason)? = list.emptyState else { + return XCTFail("expected cannot-filter, got \(String(describing: list.emptyState))") + } + XCTAssertTrue(reason.contains("voting keys")) + } + + /// AC-09, history unavailable. + func testMyVotesFilterWithUnreadableHistoryCannotFilter() async { + votingWallet() + history.records = nil + contests.result = .success([single("alice")]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + + list.filter.type = .approved + + guard case .cannotFilterByMyVotes(let reason)? = list.emptyState else { + return XCTFail("expected cannot-filter, got \(String(describing: list.emptyState))") + } + XCTAssertEqual(reason, "Pull down to try again.") + } + + /// AC-09, the masternode list may be incomplete. + func testMyVotesFilterWithAnIncompleteNodeListCannotFilter() async { + votingWallet() + nodes.resolution = .init(nodes: nodes.resolution.nodes, mayBeIncomplete: true) + contests.result = .success([single("alice")]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + + list.filter.type = .notVoted + + guard case .cannotFilterByMyVotes(let reason)? = list.emptyState else { + return XCTFail("expected cannot-filter, got \(String(describing: list.emptyState))") + } + XCTAssertTrue(reason.contains("missing from this list")) + } + + /// Before the wallet's sync is done the nodes read so far may not be all + /// of this wallet's, so its own votes cannot be told yet. + func testMyVotesFilterBeforeTheWalletsSyncIsDoneCannotFilter() async { + votingWallet() + nodes.isNodeListSynced = false + contests.result = .success([single("alice")]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + + list.filter.type = .notVoted + + XCTAssertFalse(list.canFilterByMyVotes) + guard case .cannotFilterByMyVotes(let reason)? = list.emptyState else { + return XCTFail("expected cannot-filter, got \(String(describing: list.emptyState))") + } + XCTAssertEqual(reason, "The masternode list is still syncing. Try again in a moment.") + } + + /// With the votes known, a my-votes filter that keeps nothing is a plain no-match. + func testMyVotesFilterWithKnownVotesThatKeepsNothingIsNoMatch() async { + votingWallet() + contests.result = .success([single("alice")]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + + list.filter.type = .approved + + XCTAssertEqual(list.emptyState, .filterMatchesNothing) + } + + /// AC-09: after a refresh adds a contest whose history is still loading, + /// a filter by my vote shows the loading state, not only the contests + /// already known. + func testMyVotesFilterWaitsForTheHistoryOfNewContests() async { + votingWallet() + contests.result = .success([single("alice")]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + list.filter.type = .notVoted + XCTAssertEqual(list.visibleContests.map(\.normalizedLabel), ["alice"]) + + contests.result = .success([single("alice"), single("bob")]) + history.holdsNextRead = true + let refresh = Task { await store.refresh() } + for _ in 0..<1000 where !history.isHolding { await Task.yield() } + XCTAssertTrue(history.isHolding, "the history read did not start") + + XCTAssertTrue(list.visibleContests.isEmpty) + XCTAssertEqual(list.emptyState, .loading) + + history.releaseRead() + await refresh.value + XCTAssertEqual(Set(list.visibleContests.map(\.normalizedLabel)), ["alice", "bob"]) + } + + // MARK: The row header's VoiceOver hint (AC-10, AC-11) + + func testHeaderHintSaysWhatTheTapDoes() async { + contests.result = .success([contest("solo", requests: 1), contest("many", requests: 3)]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + let solo = contest("solo", requests: 1), many = contest("many", requests: 3) + + XCTAssertEqual(list.headerAccessibilityHint(for: solo), "Opens the request details") + XCTAssertEqual(list.headerAccessibilityHint(for: many), "Opens the requests for this name") + + list.toggleExpanded("many") + + XCTAssertEqual(list.headerAccessibilityHint(for: many), "Hides the requests for this name") + } + + // MARK: Day groups follow the time zone (AC-01) + + /// The zone changes while the list is open: the next recompute (the + /// screen's significant-time-change hook) groups by the new zone. 23:30 + /// UTC on 2 Nov is today in UTC and tomorrow in Kyiv. + func testATimeZoneChangeRegroupsTheLiveList() async throws { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = try XCTUnwrap(TimeZone(identifier: "UTC")) + let now = try XCTUnwrap(calendar.date(from: DateComponents(year: 2026, month: 11, day: 2, hour: 8))) + let end = try XCTUnwrap( + calendar.date(from: DateComponents(year: 2026, month: 11, day: 2, hour: 23, minute: 30))) + contests.result = .success([DPNSContest(normalizedLabel: "late", endTime: end, hasWinner: false, + abstainVotes: 0, lockVotes: 0, contenders: [])]) + let store = makeStore() + let list = VotingListViewModel( + store: store, normalizedLabel: { $0.lowercased() }, now: { now }, calendar: { calendar }) + await store.refresh() + XCTAssertEqual(list.sections.map(\.daysLeft), [0]) + + calendar.timeZone = try XCTUnwrap(TimeZone(identifier: "Europe/Kyiv")) + list.recomputeVisible() + + XCTAssertEqual(list.sections.map(\.daysLeft), [1]) + } + + // MARK: The row's "You voted" line (AC-07, AC-17) + + /// An abstain takes a vote back: a name whose ticked nodes only abstain is + /// listed under "I have not voted", so its row must not say "You voted". + func testAbstainOnlyRowSaysNothingVoted() { + let one = contest("johndoe", requests: 1) + let several = contest("alice", requests: 3) + + XCTAssertFalse(VotingContestCard.hasVoteWithoutPill([.abstain], contenders: one.contenders, isExpanded: false)) + XCTAssertFalse(VotingContestCard.hasVoteWithoutPill( + [.abstain], contenders: several.contenders, isExpanded: false)) + } + + /// An approve on a collapsed several-request name has no pill on the row: + /// the line says it, with or without an abstain next to it. + func testApproveNoPillCarriesSaysYouVoted() { + let several = contest("alice", requests: 3) + let approve = VoteChoice.towards(identityId: "alice-id2") + + XCTAssertTrue(VotingContestCard.hasVoteWithoutPill( + [approve], contenders: several.contenders, isExpanded: false)) + XCTAssertTrue(VotingContestCard.hasVoteWithoutPill( + [approve, .abstain], contenders: several.contenders, isExpanded: false)) + XCTAssertFalse(VotingContestCard.hasVoteWithoutPill( + [approve], contenders: several.contenders, isExpanded: true), "expanded, its pill carries it") + XCTAssertFalse(VotingContestCard.hasVoteWithoutPill([.lock], contenders: several.contenders, isExpanded: false)) + } + + // MARK: Expand and collapse (AC-10) + + func testTogglingExpandsThenTappingAgainCollapses() async { + contests.result = .success([contest("johndoe", requests: 3)]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + XCTAssertFalse(list.isExpanded("johndoe"), "collapsed by default") + + list.toggleExpanded("johndoe") + XCTAssertTrue(list.isExpanded("johndoe")) + + list.toggleExpanded("johndoe") + XCTAssertFalse(list.isExpanded("johndoe")) + } + + func testExpandStateIsPerContest() async { + contests.result = .success([contest("johndoe", requests: 3), contest("janedoe", requests: 2)]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + + list.toggleExpanded("johndoe") + + XCTAssertTrue(list.isExpanded("johndoe")) + XCTAssertFalse(list.isExpanded("janedoe")) + } + + func testRowStaysExpandedAcrossAFilterChangeAndARefreshWhileShown() async { + contests.result = .success([contest("johndoe", requests: 3), contest("solo", requests: 1)]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + list.toggleExpanded("johndoe") + + list.filter.onlyDuplicates = true + XCTAssertEqual(list.visibleContests.map(\.normalizedLabel), ["johndoe"]) + XCTAssertTrue(list.isExpanded("johndoe"), "still shown after a filter change") + + await store.refresh() + XCTAssertTrue(list.isExpanded("johndoe"), "still shown after a refresh") + } + + func testOneRequestContestIsNotExpandable() async { + contests.result = .success([contest("solo", requests: 1), contest("johndoe", requests: 3)]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + + XCTAssertFalse(list.isExpandable(contest("solo", requests: 1))) + XCTAssertTrue(list.isExpandable(contest("johndoe", requests: 3))) + + list.toggleExpanded("solo") + XCTAssertFalse(list.isExpanded("solo"), "no expand pill, so nothing to expand") + } + + // MARK: Per-request fill + + func testOnlyTheRequestCarryingMyVoteIsFilled() async { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + let johndoe = contest("johndoe", requests: 3) + contests.result = .success([johndoe]) + history.records = [vote(a, on: "johndoe", .towards(identityId: "johndoe-id2"))] + let store = makeStore() + let list = makeList(store) + await store.refresh() + + let rows = list.requestRows(for: johndoe) + + XCTAssertEqual(rows.map(\.identityId), ["johndoe-id1", "johndoe-id2", "johndoe-id3"]) + XCTAssertEqual(rows.map(\.isMine), [false, true, false]) + XCTAssertEqual(rows.map(\.votes), [2, 4, 6]) + } + + func testNoRequestIsFilledWhenOnlyAnUntickedNodeVoted() async { + let a = node(1), b = node(2) + nodes.resolution = .init(nodes: [a, b], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + let johndoe = contest("johndoe", requests: 3) + contests.result = .success([johndoe]) + history.records = [vote(b, on: "johndoe", .towards(identityId: "johndoe-id2"))] + let store = makeStore() + let list = makeList(store) + await store.refresh() + + XCTAssertEqual(list.requestRows(for: johndoe).map(\.isMine), [false, false, false]) + } + + // MARK: Pill taps (AC-17) + + /// A filled pill is the way to take my vote back, so it is not shown as + /// disabled although no ticked node can cast that choice again. + func testFilledPillStaysTappableAndTakesTheVoteBack() async throws { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + let johndoe = contest("johndoe", requests: 2) + contests.result = .success([johndoe]) + let mine = VoteChoice.towards(identityId: "johndoe-id2") + history.records = [vote(a, on: "johndoe", mine)] + let store = makeStore() + let list = makeList(store) + await store.refresh() + + XCTAssertFalse(store.canStartVote(mine, on: "johndoe"), "a holds it already") + XCTAssertTrue(list.canTapPill(mine, on: "johndoe")) + let cancel = list.voteRequest(for: mine, on: johndoe) + XCTAssertEqual(cancel.choice, .abstain) + XCTAssertEqual(cancel.cancelling, mine) + } + + func testOutlinedPillAsksForItsOwnChoice() async { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + let johndoe = contest("johndoe", requests: 2) + contests.result = .success([johndoe]) + history.records = [vote(a, on: "johndoe", .towards(identityId: "johndoe-id2"))] + let store = makeStore() + let list = makeList(store) + await store.refresh() + + let other = VoteChoice.towards(identityId: "johndoe-id1") + XCTAssertTrue(list.canTapPill(other, on: "johndoe")) + let request = list.voteRequest(for: other, on: johndoe) + XCTAssertEqual(request.choice, other) + XCTAssertNil(request.cancelling) + } + + /// AC-17: a tap on a filled pill cancels even when another ticked node + /// could still cast that choice, instead of casting it again from that node. + func testFilledPillCancelsAlthoughAnotherTickedNodeCouldCastIt() async { + let a = node(1), b = node(2) + nodes.resolution = .init(nodes: [a, b], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash, b.proTxHash] + let johndoe = contest("johndoe", requests: 2) + contests.result = .success([johndoe]) + let mine = VoteChoice.towards(identityId: "johndoe-id2") + history.records = [vote(a, on: "johndoe", mine)] + let store = makeStore() + let list = makeList(store) + await store.refresh() + + XCTAssertTrue(store.canStartVote(mine, on: "johndoe"), "b holds nothing and could cast it") + XCTAssertTrue(list.canTapPill(mine, on: "johndoe")) + let cancel = list.voteRequest(for: mine, on: johndoe) + XCTAssertEqual(cancel.choice, .abstain) + XCTAssertEqual(cancel.cancelling, mine) + } + + func testFilledPillCannotBeTappedOnceTheContestClosed() async { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + let johndoe = DPNSContest( + normalizedLabel: "johndoe", endTime: Date().addingTimeInterval(86_400), hasWinner: false, + abstainVotes: 0, lockVotes: 0, contenders: [DPNSContender(identityId: "johndoe-id1", voteTally: 2)]) + contests.result = .success([johndoe]) + history.records = [vote(a, on: "johndoe", .lock)] + let store = makeStore() + let list = makeList(store) + await store.refresh() + XCTAssertTrue(list.canTapPill(.lock, on: "johndoe"), "open: the filled pill takes the vote back") + + contests.state = DPNSContestVoteState(normalizedLabel: "johndoe", contenders: [], abstainVotes: 0, + lockVotes: 1, outcome: .locked, resolvedAt: epoch) + await store.refreshContest(normalizedLabel: "johndoe") + + XCTAssertFalse(list.canTapPill(.lock, on: "johndoe")) + } + + func testFilledPillCannotBeTappedWhenItsHolderHasNoVoteLeft() async { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + contests.result = .success([contest("johndoe", requests: 2)]) + history.records = [CastVoteRecord(proTxHash: a.proTxHash, normalizedLabel: "johndoe", choice: .lock, + castAt: epoch, castCount: VoteLimit.maxCastsPerNode)] + let store = makeStore() + let list = makeList(store) + await store.refresh() + + XCTAssertEqual(store.myChoices(on: "johndoe"), [.lock]) + XCTAssertFalse(list.canTapPill(.lock, on: "johndoe")) + } + + // MARK: Subtitle and VoiceOver strings + + /// A filled pill that can be tapped says it takes my vote back; an + /// outlined, disabled or busy pill says nothing more than its label. + func testOnlyATappableFilledPillHasTheTakeBackHint() { + XCTAssertEqual(VotingContestCard.pillAccessibilityHint(isSelected: true, status: .enabled), + "Takes your vote back") + XCTAssertNil(VotingContestCard.pillAccessibilityHint(isSelected: false, status: .enabled)) + XCTAssertNil(VotingContestCard.pillAccessibilityHint(isSelected: true, status: .disabled)) + XCTAssertNil(VotingContestCard.pillAccessibilityHint(isSelected: true, status: .busy)) + } + + func testRequestCountSubtitle() { + let list = makeList(makeStore()) + XCTAssertEqual(list.requestCountText(for: contest("johndoe", requests: 3)), "3 requests") + } + + func testExpandPillSpeaksStateAndRequestCount() { + let list = makeList(makeStore()) + let johndoe = contest("johndoe", requests: 3) + + XCTAssertEqual(list.expandAccessibilityLabel(for: johndoe, isExpanded: false), "Show requests for johndoe") + XCTAssertEqual(list.expandAccessibilityLabel(for: johndoe, isExpanded: true), "Hide requests for johndoe") + XCTAssertEqual(list.expandAccessibilityValue(for: johndoe), "3 requests") + } + + func testRequestApprovePillSpeaksIdentityAndVotes() async { + let johndoe = contest("johndoe", requests: 3) + contests.result = .success([johndoe]) + let store = makeStore() + let list = makeList(store) + await store.refresh() + + let row = list.requestRows(for: johndoe)[1] + + XCTAssertEqual(row.accessibilityLabel, "Approve john … -id2") + XCTAssertEqual(row.accessibilityValue, "4 votes") + } +} + +// MARK: - VotingRequestRow + +final class VotingRequestRowTests: XCTestCase { + /// VoiceOver reads a request by its first and last four characters, not + /// the whole 44-character id. + func testARequestIsSpokenByAShortIdentity() { + let row = VotingRequestRow(identityId: "Hx4kP9mT2pLw8RzYb5NcHf7Ud4EaQ1sV3jK6nB2cD8gF", votes: 3, isMine: false) + + XCTAssertEqual(row.spokenIdentity, "Hx4k … D8gF") + XCTAssertFalse(row.accessibilityLabel.contains(row.identityId)) + XCTAssertTrue(row.accessibilityLabel.contains("Hx4k … D8gF")) + } + + func testAShortIdIsSpokenWhole() { + XCTAssertEqual(VotingRequestRow(identityId: "abc", votes: 0, isMine: false).spokenIdentity, "abc") + } +} diff --git a/DashWalletTests/VotingStoreTests.swift b/DashWalletTests/VotingStoreTests.swift new file mode 100644 index 0000000000..3d6c6b1413 --- /dev/null +++ b/DashWalletTests/VotingStoreTests.swift @@ -0,0 +1,1244 @@ +// +// VotingStoreTests.swift +// DashWalletTests +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +@testable import dashpay +import SwiftDashSDK +import XCTest + +// MARK: - Fakes + +private final class FakeContests: VotingContestReading { + var result: Result<[DPNSContest], Error> = .success([]) + /// When set, `activeContests()` suspends until `release()` is called. + var gate: CheckedContinuation? + var holdNextLoad = false + private(set) var started = false + private(set) var loads = 0 + /// What `voteState(normalizedLabel:)` answers: a state, `nil` (Platform + /// holds no contenders), or a failure. + var voteStateResult: Result = .success(nil) + + func activeContests() async throws -> [DPNSContest] { + started = true + loads += 1 + if holdNextLoad { + await withCheckedContinuation { gate = $0 } + } + return try result.get() + } + + func release() { + gate?.resume() + gate = nil + } + + /// When set, the next `voteState(normalizedLabel:)` suspends until + /// `releaseVoteState()` — a contest refresh that holds the load queue. + var holdNextVoteState = false + private var voteStateGate: CheckedContinuation? + private(set) var voteStateHeld = false + + func voteState(normalizedLabel: String) async throws -> DPNSContestVoteState? { + if holdNextVoteState { + holdNextVoteState = false + voteStateHeld = true + await withCheckedContinuation { voteStateGate = $0 } + } + return try voteStateResult.get() + } + + func releaseVoteState() { + voteStateGate?.resume() + voteStateGate = nil + } +} + +/// A clock the test moves by hand. +private final class TestClock { + var now: Date + init(_ now: Date) { self.now = now } +} + +private final class FakeNodes: VotableMasternodeResolving { + var resolution = MasternodeVoterRegistry.Resolution(nodes: [], mayBeIncomplete: false) + var isNodeListSynced = true + func votableNodes() -> MasternodeVoterRegistry.Resolution { resolution } +} + +private struct FakeCaster: VoteCasting { + struct Unused: Error {} + func cast(choice: VoteChoice, onNormalizedLabel normalizedLabel: String, with nodes: [VoterNode]) async throws + -> VoteCastReport { + throw Unused() + } +} + +/// A caster the test scripts: it answers with a report, throws, or holds the +/// call until `release()`. A landed, recorded outcome is written to the fake +/// history the way the real caster writes it. +private final class ScriptedCaster: VoteCasting { + enum Script { + case outcomes([VoteOutcome]) + case throwing(Error) + } + + var script: Script = .outcomes([]) + var holdNextCall = false + var history: FakeHistory? + private(set) var calls: [(choice: VoteChoice, label: String, nodes: [VoterNode])] = [] + private var gate: CheckedContinuation? + + var started: Bool { !calls.isEmpty } + + func cast(choice: VoteChoice, onNormalizedLabel normalizedLabel: String, with nodes: [VoterNode]) async throws + -> VoteCastReport { + calls.append((choice, normalizedLabel, nodes)) + if holdNextCall { + holdNextCall = false + await withCheckedContinuation { gate = $0 } + } + switch script { + case .throwing(let error): + throw error + case .outcomes(let outcomes): + for outcome in outcomes where outcome.succeeded && outcome.historyRecorded { + let previous = history?.records?.first { + $0.proTxHash == outcome.node.proTxHash && $0.normalizedLabel == normalizedLabel + } + history?.records?.removeAll { + $0.proTxHash == outcome.node.proTxHash && $0.normalizedLabel == normalizedLabel + } + history?.records?.append(CastVoteRecord( + proTxHash: outcome.node.proTxHash, normalizedLabel: normalizedLabel, choice: choice, + castAt: Date(), castCount: (previous?.castCount ?? 0) + 1)) + } + return VoteCastReport(normalizedLabel: normalizedLabel, choice: choice, outcomes: outcomes) + } + } + + func release() { + gate?.resume() + gate = nil + } +} + +private final class FakeHistory: VoteHistoryDAO { + /// `nil` makes the whole-list read fail, as an unreadable store does. + var records: [CastVoteRecord]? = [] + private(set) var listReads = 0 + private(set) var singleReads = 0 + + func record(_ record: CastVoteRecord, network: String) async throws {} + func votes(forContest normalizedLabel: String, network: String) async -> [CastVoteRecord]? { + singleReads += 1 + return records?.filter { $0.normalizedLabel == normalizedLabel } + } + /// When set, the next whole-list read takes its rows, then suspends until + /// `releaseListRead()` — a read that finished before a later write landed. + var holdNextListRead = false + private var listGate: CheckedContinuation? + private(set) var listReadHeld = false + + func votes(forContests normalizedLabels: Set, network: String) async -> [CastVoteRecord]? { + listReads += 1 + let snapshot = records + if holdNextListRead { + holdNextListRead = false + listReadHeld = true + await withCheckedContinuation { listGate = $0 } + } + return snapshot?.filter { normalizedLabels.contains($0.normalizedLabel) } + } + + func releaseListRead() { + listGate?.resume() + listGate = nil + } + func deleteAll() {} +} + +private final class FakePrefs: VotingSelectionStoring { + var votingNodeSelection: Set = [] +} + +// MARK: - Tests + +/// The shared voting store: one history read per list load, the load and +/// banner states, and the pills filled from the ticked masternodes only. +@MainActor +final class VotingStoreTests: XCTestCase { + + private let approve = VoteChoice.towards(identityId: "contender-1") + private let epoch = Date(timeIntervalSince1970: 1_700_000_000) + + private var contests: FakeContests! + private var nodes: FakeNodes! + private var history: FakeHistory! + private var prefs: FakePrefs! + + override func setUp() { + super.setUp() + contests = FakeContests() + nodes = FakeNodes() + history = FakeHistory() + prefs = FakePrefs() + } + + private func makeStore(caster: VoteCasting? = nil) -> VotingStore { + VotingStore(contests: contests, nodes: nodes, caster: caster ?? FakeCaster(), history: history, prefs: prefs) + } + + private func node(_ byte: UInt8) -> VoterNode { + VoterNode(proTxHash: Data([byte]), isEvonode: false, typeIndex: UInt32(byte), + serviceAddress: nil, keySource: .walletIndex(0)) + } + + private func contest(_ label: String, endsAt end: Date? = nil) -> DPNSContest { + DPNSContest(normalizedLabel: label, endTime: end, hasWinner: false, + abstainVotes: 0, lockVotes: 0, contenders: []) + } + + private func vote(_ node: VoterNode, on label: String, _ choice: VoteChoice) -> CastVoteRecord { + CastVoteRecord(proTxHash: node.proTxHash, normalizedLabel: label, choice: choice, castAt: epoch) + } + + // MARK: One history read per load (NFR) + + func testListLoadIssuesExactlyOneHistoryRead() async { + contests.result = .success((1...12).map { contest("name\($0)") }) + let store = makeStore() + + await store.refresh() + + XCTAssertEqual(history.listReads, 1, "one read for the whole list, not one per row") + XCTAssertEqual(history.singleReads, 0) + XCTAssertEqual(store.contests.count, 12) + } + + // MARK: Load states + + func testLoadingThenEmptyWhenNoOpenContests() async { + contests.result = .success([]) + contests.holdNextLoad = true + let store = makeStore() + XCTAssertFalse(store.hasLoadedOnce) + + let load = Task { await store.refresh() } + while !contests.started { await Task.yield() } + XCTAssertTrue(store.isLoading) + XCTAssertFalse(store.hasLoadedOnce, "the empty state must not show while the first fetch is in flight") + + contests.release() + await load.value + + XCTAssertFalse(store.isLoading) + XCTAssertTrue(store.hasLoadedOnce) + XCTAssertTrue(store.contests.isEmpty) + } + + func testNodeListIncompleteFlagFollowsTheRegistry() async { + nodes.resolution = .init(nodes: [node(1)], mayBeIncomplete: true) + let store = makeStore() + + await store.refresh() + + XCTAssertTrue(store.nodeListMayBeIncomplete) + XCTAssertEqual(store.votableNodes.map(\.proTxHash), [Data([1])]) + } + + func testNodeListCompleteByDefault() async { + nodes.resolution = .init(nodes: [node(1)], mayBeIncomplete: false) + let store = makeStore() + await store.refresh() + XCTAssertFalse(store.nodeListMayBeIncomplete) + } + + func testFailedContestLoadKeepsLastGoodListAndSetsError() async { + contests.result = .success([contest("kept")]) + let store = makeStore() + await store.refresh() + + struct Boom: Error {} + contests.result = .failure(Boom()) + await store.refresh() + + XCTAssertEqual(store.contests.map(\.normalizedLabel), ["kept"]) + XCTAssertTrue(store.loadFailed) + } + + // MARK: History unavailable (flow 4) + + func testUnreadableHistorySetsFlagAndFillsNoPill() async { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + contests.result = .success([contest("johndoe")]) + history.records = nil + let store = makeStore() + + await store.refresh() + + XCTAssertTrue(store.historyUnavailable) + XCTAssertEqual(store.myChoices(on: "johndoe"), [], "counts only, none filled") + XCTAssertFalse(store.hasLoadedVoteHistory(for: "johndoe"), "unknown, not 'nobody voted'") + } + + func testReadableHistoryClearsTheFlag() async { + contests.result = .success([contest("johndoe")]) + history.records = nil + let store = makeStore() + await store.refresh() + XCTAssertTrue(store.historyUnavailable) + + history.records = [] + await store.refresh() + + XCTAssertFalse(store.historyUnavailable) + XCTAssertTrue(store.hasLoadedVoteHistory(for: "johndoe")) + } + + // MARK: Pill fill from ticked masternodes only (AC-04) + + func testPillFillsFromTickedMasternodesOnly() async { + let a = node(1), b = node(2) + nodes.resolution = .init(nodes: [a, b], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + contests.result = .success([contest("johndoe")]) + history.records = [vote(a, on: "johndoe", approve), vote(b, on: "johndoe", .lock)] + let store = makeStore() + + await store.refresh() + + XCTAssertEqual(store.myChoices(on: "johndoe"), [approve], "b voted lock but is not ticked") + } + + func testUntickedNodesVoteFillsNothing() async { + let a = node(1), b = node(2) + nodes.resolution = .init(nodes: [a, b], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + contests.result = .success([contest("johndoe")]) + history.records = [vote(b, on: "johndoe", approve)] + let store = makeStore() + + await store.refresh() + + XCTAssertEqual(store.myChoices(on: "johndoe"), []) + } + + // MARK: No masternode chosen yet + + /// Nothing stored and a resolved node list: the first node is settled on + /// and persisted, as before the extraction. + func testEmptySelectionWithResolvedNodesSettlesOnTheFirstNode() async { + let first = node(1) + nodes.resolution = .init(nodes: [first, node(2)], mayBeIncomplete: false) + prefs.votingNodeSelection = [] + let store = makeStore() + + await store.refresh() + + XCTAssertEqual(prefs.votingNodeSelection, [first.proTxHash]) + XCTAssertEqual(store.tickedNodeIDs, [first.proTxHash]) + } + + /// Nothing stored and no nodes yet (SDK not ready): no selection is + /// persisted, and the store says "none chosen yet" rather than an empty set. + func testEmptySelectionWithoutNodesIsNoneChosenYetAndPersistsNothing() async { + nodes.resolution = .init(nodes: [], mayBeIncomplete: false) + prefs.votingNodeSelection = [] + let store = makeStore() + + XCTAssertNil(store.tickedNodeIDs) + await store.refresh() + + XCTAssertNil(store.tickedNodeIDs) + XCTAssertEqual(prefs.votingNodeSelection, []) + } + + func testTickedNodesAreTheStoredChoiceThatIsStillVotable() async { + let a = node(1) + nodes.resolution = .init(nodes: [a, node(2)], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash, Data([9])] + let store = makeStore() + + await store.refresh() + + XCTAssertEqual(store.tickedNodeIDs, [a.proTxHash], "a remembered node that is no longer votable is dropped") + } + + // MARK: Sections on the list view model (AC-01, AC-03b) + + func testListSectionsSoonestFirstAndUnknownEndLast() async { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "Europe/Kyiv")! + let now = calendar.date(from: DateComponents(year: 2026, month: 11, day: 2, hour: 10))! + let day: TimeInterval = 86_400 + contests.result = .success([ + contest("unknown"), + contest("ten", endsAt: now.addingTimeInterval(10 * day)), + contest("today", endsAt: now.addingTimeInterval(3600)), + contest("three", endsAt: now.addingTimeInterval(3 * day)), + ]) + let store = makeStore() + let list = VotingListViewModel(store: store, normalizedLabel: { $0.lowercased() }, now: { now }, + calendar: { calendar }) + + await store.refresh() + + XCTAssertEqual(list.sections.map(\.daysLeft), [0, 3, 10, nil]) + XCTAssertEqual(list.sections.last?.contests.map(\.normalizedLabel), ["unknown"]) + XCTAssertEqual(list.sections.last?.title, "Voting end unknown") + } + + func testSearchNarrowsRowsButNotTheOpenCount() async { + contests.result = .success([contest("alice"), contest("bob")]) + let store = makeStore() + let list = VotingListViewModel(store: store, normalizedLabel: { $0.lowercased() }) + await store.refresh() + + list.searchQuery = "bob" + + XCTAssertEqual(list.visibleContests.map(\.normalizedLabel), ["bob"]) + XCTAssertEqual(list.filterMatchCount, 2, "the header's count ignores the search") + } + + // MARK: Which nodes a tap casts with (AC-14b) + + /// Ticked a, b, d; c is not ticked. a holds the approve, b has spent its + /// five casts, d has not voted. + func testNodesForVoteSkipsHoldersSpentAndUntickedNodes() async { + let a = node(1), b = node(2), c = node(3), d = node(4) + nodes.resolution = .init(nodes: [a, b, c, d], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash, b.proTxHash, d.proTxHash] + contests.result = .success([contest("johndoe")]) + history.records = [ + vote(a, on: "johndoe", approve), + CastVoteRecord(proTxHash: b.proTxHash, normalizedLabel: "johndoe", choice: .lock, castAt: epoch, + castCount: VoteLimit.maxCastsPerNode), + ] + let store = makeStore() + await store.refresh() + + XCTAssertEqual(store.nodesForVote(approve, on: "johndoe").map(\.proTxHash), [d.proTxHash], + "a already holds it, b has no vote left, c is not ticked") + XCTAssertEqual(store.nodesForVote(.lock, on: "johndoe").map(\.proTxHash), [a.proTxHash, d.proTxHash], + "a holding another choice can change it") + } + + // MARK: What the cast sheet offers (AC-14b, AC-17) + + /// A vote: the ticked nodes that can cast it, and how many ticked nodes + /// were left out because they hold it or are out of casts. An unticked + /// node is not counted at all. + func testCastCandidatesForAVoteCountWhatWasLeftOut() async { + let a = node(1), b = node(2), c = node(3), d = node(4) + nodes.resolution = .init(nodes: [a, b, c, d], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash, b.proTxHash, c.proTxHash] + contests.result = .success([contest("johndoe")]) + history.records = [ + vote(a, on: "johndoe", approve), + CastVoteRecord(proTxHash: b.proTxHash, normalizedLabel: "johndoe", choice: .lock, castAt: epoch, + castCount: VoteLimit.maxCastsPerNode), + ] + let store = makeStore() + await store.refresh() + + let candidates = store.castCandidates(for: approve, cancelling: nil, on: "johndoe") + + XCTAssertEqual(candidates.nodes.map(\.proTxHash), [c.proTxHash]) + XCTAssertEqual(candidates.holdingThisChoice, 1, "a") + XCTAssertEqual(candidates.outOfCasts, 1, "b; d is not ticked") + } + + /// Cancel approval: only the ticked holders of the approve, and the counts + /// talk only about them — a ticked node blocking the name is not counted. + func testCastCandidatesForCancelApprovalTalkOnlyAboutItsHolders() async { + let a = node(1), b = node(2), c = node(3) + nodes.resolution = .init(nodes: [a, b, c], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash, b.proTxHash, c.proTxHash] + contests.result = .success([contest("johndoe")]) + history.records = [ + vote(a, on: "johndoe", approve), + vote(b, on: "johndoe", .lock), + CastVoteRecord(proTxHash: c.proTxHash, normalizedLabel: "johndoe", choice: approve, castAt: epoch, + castCount: VoteLimit.maxCastsPerNode), + ] + let store = makeStore() + await store.refresh() + + let candidates = store.castCandidates(for: .abstain, cancelling: approve, on: "johndoe") + + XCTAssertEqual(candidates.nodes.map(\.proTxHash), [a.proTxHash]) + XCTAssertEqual(candidates.holdingThisChoice, 0) + XCTAssertEqual(candidates.outOfCasts, 1, "c; b's block is not counted") + } + + /// Before the contest's history is known, no node is offered. + func testNodesForVoteIsEmptyBeforeTheHistoryLoads() async { + let a = node(1) + nodes.resolution = .init(nodes: [a], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash] + history.records = nil + contests.result = .success([contest("johndoe")]) + let store = makeStore() + await store.refresh() + + XCTAssertFalse(store.hasLoadedVoteHistory(for: "johndoe")) + XCTAssertEqual(store.nodesForVote(approve, on: "johndoe").map(\.proTxHash), []) + } + + // MARK: Keep a contest until its voting end, newer data wins (AC-03, AC-03c) + + private let day: TimeInterval = 86_400 + + /// The store reads its clock from here; the list view model reads the same one. + private func makeClockedStore(_ clock: TestClock) -> VotingStore { + VotingStore(contests: contests, nodes: nodes, caster: FakeCaster(), history: history, prefs: prefs, + now: { clock.now }) + } + + private func contest(_ label: String, endsAt end: Date?, lock: UInt32) -> DPNSContest { + DPNSContest(normalizedLabel: label, endTime: end, hasWinner: false, + abstainVotes: 0, lockVotes: lock, contenders: []) + } + + private func ongoing(_ label: String, lock: UInt32) -> DPNSContestVoteState { + DPNSContestVoteState(normalizedLabel: label, contenders: [], abstainVotes: 0, lockVotes: lock, + outcome: .ongoing, resolvedAt: nil) + } + + /// Loads apply in the order they were asked for: a full refresh asked + /// for before a vote's per-contest refresh cannot land after it and put + /// the pre-vote counts back. + func testLoadsApplyInTheOrderTheyWereAskedFor() async { + let end = epoch.addingTimeInterval(10 * day) + let clock = TestClock(epoch) + contests.result = .success([contest("johndoe", endsAt: end, lock: 1)]) + let store = makeClockedStore(clock) + await store.refresh() + + contests.result = .success([contest("johndoe", endsAt: end, lock: 1)]) // the pre-vote counts + contests.holdNextLoad = true + let full = Task { await store.refresh() } + while contests.loads < 2 { await Task.yield() } + contests.holdNextLoad = false + + contests.voteStateResult = .success(ongoing("johndoe", lock: 5)) // the vote's counts + let single = Task { await store.refreshContest(normalizedLabel: "johndoe") } + await Task.yield() + contests.release() + await full.value + await single.value + + XCTAssertEqual(store.contests.first?.lockVotes, 5, "the later counts must survive the earlier response") + } + + /// A per-contest refresh that finds no contenders, before the voting end, + /// keeps the contest with its last known votes. + func testEmptyContestRefreshKeepsTheContestWithItsLastKnownVotes() async { + let clock = TestClock(epoch) + contests.result = .success([contest("johndoe", endsAt: epoch.addingTimeInterval(3 * day), lock: 3)]) + let store = makeClockedStore(clock) + await store.refresh() + + contests.voteStateResult = .success(nil) + await store.refreshContest(normalizedLabel: "johndoe") + + XCTAssertEqual(store.contests.map(\.normalizedLabel), ["johndoe"]) + XCTAssertEqual(store.contests.first?.lockVotes, 3) + XCTAssertFalse(store.isClosed(normalizedLabel: "johndoe")) + } + + /// Same, without the injected clock: the end is far in the future of the real clock. + func testEmptyContestRefreshKeepsTheContestOnTheRealClock() async { + contests.result = .success([contest("johndoe", endsAt: Date().addingTimeInterval(30 * day), lock: 3)]) + let store = makeStore() + await store.refresh() + + contests.voteStateResult = .success(nil) + await store.refreshContest(normalizedLabel: "johndoe") + + XCTAssertEqual(store.contests.map(\.normalizedLabel), ["johndoe"]) + } + + /// A failed per-contest refresh keeps the row as it was (already the case). + func testFailedContestRefreshKeepsTheContestWithItsLastKnownVotes() async { + struct Boom: Error {} + let clock = TestClock(epoch) + contests.result = .success([contest("johndoe", endsAt: epoch.addingTimeInterval(3 * day), lock: 3)]) + let store = makeClockedStore(clock) + await store.refresh() + + contests.voteStateResult = .failure(Boom()) + await store.refreshContest(normalizedLabel: "johndoe") + + XCTAssertEqual(store.contests.first?.lockVotes, 3) + } + + /// Once the voting end has passed, the next refresh of the contest drops it. + func testEmptyContestRefreshAfterTheVotingEndDropsTheContest() async { + let end = epoch.addingTimeInterval(3 * day) + let clock = TestClock(epoch) + contests.result = .success([contest("johndoe", endsAt: end, lock: 3)]) + let store = makeClockedStore(clock) + await store.refresh() + + clock.now = end.addingTimeInterval(1) + contests.voteStateResult = .success(nil) + await store.refreshContest(normalizedLabel: "johndoe") + + XCTAssertTrue(store.contests.isEmpty) + } + + /// The voting end passing on screen changes nothing by itself (no timer); + /// the next refresh drops the row. + func testRowStaysWhenTheVotingEndPassesUntilTheNextRefresh() async { + let end = epoch.addingTimeInterval(3600) + let clock = TestClock(epoch) + contests.result = .success([contest("johndoe", endsAt: end, lock: 3)]) + let store = makeClockedStore(clock) + let list = VotingListViewModel(store: store, normalizedLabel: { $0.lowercased() }, now: { clock.now }) + await store.refresh() + let before = list.visibleContests + + clock.now = end.addingTimeInterval(60) + await Task.yield() + XCTAssertEqual(list.visibleContests, before, "no timer removes or changes the row") + XCTAssertEqual(store.contests.map(\.normalizedLabel), ["johndoe"]) + + contests.result = .success([]) + await store.refresh() + XCTAssertTrue(list.visibleContests.isEmpty, "the next refresh drops it") + } + + private func resolved(_ label: String, lock: UInt32) -> DPNSContestVoteState { + DPNSContestVoteState(normalizedLabel: label, contenders: [], abstainVotes: 0, lockVotes: lock, + outcome: .locked, resolvedAt: epoch) + } + + /// sad §4 choice 6: a contest Platform closed early stays on the list + /// until its voting end; no vote can start on it. + func testContestClosedEarlyStaysUntilItsVotingEnd() async { + let end = epoch.addingTimeInterval(3 * day) + let clock = TestClock(epoch) + contests.result = .success([contest("johndoe", endsAt: end, lock: 3)]) + let store = makeClockedStore(clock) + await store.refresh() + + contests.voteStateResult = .success(resolved("johndoe", lock: 9)) + await store.refreshContest(normalizedLabel: "johndoe") + + XCTAssertEqual(store.contests.map(\.normalizedLabel), ["johndoe"]) + XCTAssertTrue(store.isClosed(normalizedLabel: "johndoe")) + XCTAssertFalse(store.canStartVote(.lock, on: "johndoe")) + + contests.result = .success([]) + await store.refresh() + XCTAssertEqual(store.contests.map(\.normalizedLabel), ["johndoe"], "still before its voting end") + + clock.now = end.addingTimeInterval(1) + await store.refresh() + XCTAssertTrue(store.contests.isEmpty, "gone once its voting end passed") + } + + /// A resolved contest whose voting end has passed goes at once. + func testContestResolvedAfterItsVotingEndGoes() async { + let end = epoch.addingTimeInterval(3600) + let clock = TestClock(epoch) + contests.result = .success([contest("johndoe", endsAt: end, lock: 3)]) + let store = makeClockedStore(clock) + await store.refresh() + + clock.now = end.addingTimeInterval(1) + contests.voteStateResult = .success(resolved("johndoe", lock: 9)) + await store.refreshContest(normalizedLabel: "johndoe") + + XCTAssertTrue(store.contests.isEmpty) + XCTAssertTrue(store.isClosed(normalizedLabel: "johndoe")) + } + + /// A full refresh that leaves out a contest it listed before (a cut list, + /// a transient omission) keeps it, with its last known votes, until its + /// voting end. + func testFullRefreshKeepsALeftOutContestUntilItsVotingEnd() async { + let end = epoch.addingTimeInterval(3 * day) + let clock = TestClock(epoch) + contests.result = .success([contest("johndoe", endsAt: end, lock: 3), contest("alice", endsAt: end, lock: 0)]) + let store = makeClockedStore(clock) + await store.refresh() + + contests.result = .success([contest("alice", endsAt: end, lock: 1)]) + await store.refresh() + + XCTAssertEqual(Set(store.contests.map(\.normalizedLabel)), ["johndoe", "alice"]) + XCTAssertEqual(store.contests.first { $0.normalizedLabel == "johndoe" }?.lockVotes, 3) + XCTAssertEqual(store.contests.first { $0.normalizedLabel == "alice" }?.lockVotes, 1, "listed ones are fresh") + XCTAssertFalse(store.isClosed(normalizedLabel: "johndoe"), "left out is not known to be closed") + + clock.now = end.addingTimeInterval(1) + await store.refresh() + XCTAssertEqual(store.contests.map(\.normalizedLabel), ["alice"]) + } + + /// Without a known voting end there is no end to keep it until. + func testFullRefreshDropsALeftOutContestWithAnUnknownEnd() async { + let clock = TestClock(epoch) + contests.result = .success([contest("johndoe", endsAt: nil, lock: 3)]) + let store = makeClockedStore(clock) + await store.refresh() + + contests.result = .success([]) + await store.refresh() + + XCTAssertTrue(store.contests.isEmpty) + } + + // MARK: Could not load (AC-02) + + func testLoadingBeforeTheFirstLoadFinishes() { + let list = VotingListViewModel(store: makeStore(), normalizedLabel: { $0.lowercased() }) + XCTAssertEqual(list.loadState, .loading) + } + + /// Nothing cached and the load fails: the full-screen could-not-load state, + /// never "No open contests". + func testFailedFirstLoadIsCouldNotLoadNotNoContests() async { + struct Boom: Error {} + contests.result = .failure(Boom()) + let store = makeStore() + let list = VotingListViewModel(store: store, normalizedLabel: { $0.lowercased() }) + + await store.refresh() + + XCTAssertEqual(list.loadState, .couldNotLoad) + XCTAssertNotEqual(list.loadState, .noContests) + } + + /// Rows on screen and the refresh fails: rows stay, the banner flag is set. + func testFailedRefreshWithRowsKeepsRowsAndFlagsTheBanner() async { + struct Boom: Error {} + contests.result = .success([contest("kept")]) + let store = makeStore() + let list = VotingListViewModel(store: store, normalizedLabel: { $0.lowercased() }) + await store.refresh() + XCTAssertEqual(list.loadState, .contests(refreshFailed: false)) + + contests.result = .failure(Boom()) + await store.refresh() + + XCTAssertEqual(list.loadState, .contests(refreshFailed: true)) + XCTAssertEqual(list.visibleContests.map(\.normalizedLabel), ["kept"]) + } + + /// Try again while a refresh runs shows the loading state and queues no + /// second refresh, however often it is tapped. + func testTryAgainWhileARefreshRunsQueuesNoSecondOne() async { + struct Boom: Error {} + contests.result = .failure(Boom()) + let store = makeStore() + let list = VotingListViewModel(store: store, normalizedLabel: { $0.lowercased() }) + await store.refresh() + XCTAssertEqual(list.emptyState, .couldNotLoad) + + contests.holdNextLoad = true + let first = Task { await store.retry() } + while contests.loads < 2 { await Task.yield() } + XCTAssertTrue(store.isRefreshing) + XCTAssertEqual(list.emptyState, .loading, "the retry shows progress") + let taps = [Task { await store.retry() }, Task { await store.retry() }] + for _ in 0..<20 { await Task.yield() } + contests.holdNextLoad = false + contests.result = .success([contest("back")]) + contests.release() + await first.value + for tap in taps { await tap.value } + + XCTAssertEqual(contests.loads, 2, "one load for the first tap, none for the others") + XCTAssertFalse(store.isRefreshing) + XCTAssertEqual(store.contests.map(\.normalizedLabel), ["back"]) + } + + /// The screen comes back after a failed first load and its own initial + /// load runs: that load shows progress too, and Try again queues nothing. + func testTryAgainWhileTheInitialLoadRunsQueuesNoSecondOne() async { + struct Boom: Error {} + contests.result = .failure(Boom()) + let store = makeStore() + let list = VotingListViewModel(store: store, normalizedLabel: { $0.lowercased() }) + await store.refreshIfNeeded() + XCTAssertEqual(list.emptyState, .couldNotLoad) + + contests.holdNextLoad = true + let reappeared = Task { await store.refreshIfNeeded() } + while contests.loads < 2 { await Task.yield() } + XCTAssertTrue(store.isRefreshing) + XCTAssertEqual(list.emptyState, .loading, "the initial load shows progress") + let tap = Task { await store.retry() } + for _ in 0..<20 { await Task.yield() } + contests.holdNextLoad = false + contests.result = .success([contest("back")]) + contests.release() + await reappeared.value + await tap.value + + XCTAssertEqual(contests.loads, 2, "Try again added no load") + XCTAssertFalse(store.isRefreshing) + XCTAssertEqual(store.contests.map(\.normalizedLabel), ["back"]) + } + + /// The list reappears after contests have loaded and a later refresh + /// failed, while a contest refresh holds the queue: nothing will load, so + /// the list does not read as refreshing and Try again stays. + func testReappearingAfterContestsLoadedLeavesTryAgain() async { + struct Boom: Error {} + contests.result = .success([contest("a")]) + let store = makeStore() + await store.refreshIfNeeded() + contests.result = .failure(Boom()) + await store.refresh() + XCTAssertTrue(store.loadFailed) + + contests.holdNextVoteState = true + let busy = Task { await store.refreshContest(normalizedLabel: "a") } + while !contests.voteStateHeld { await Task.yield() } + let reappeared = Task { await store.refreshIfNeeded() } + for _ in 0..<20 { await Task.yield() } + + XCTAssertFalse(store.isRefreshing, "Try again stays while the queue is busy") + + contests.releaseVoteState() + await busy.value + await reappeared.value + XCTAssertEqual(contests.loads, 2, "the reappearing list loaded nothing") + XCTAssertFalse(store.isRefreshing) + } + + func testNoOpenContestsIsTheEmptyStateOnlyAfterASuccessfulLoad() async { + contests.result = .success([]) + let store = makeStore() + let list = VotingListViewModel(store: store, normalizedLabel: { $0.lowercased() }) + + await store.refresh() + + XCTAssertEqual(list.loadState, .noContests) + } + + /// Try again after a failed first load succeeds: the error clears. + func testRetryAfterFailedFirstLoadShowsTheContests() async { + struct Boom: Error {} + contests.result = .failure(Boom()) + let store = makeStore() + let list = VotingListViewModel(store: store, normalizedLabel: { $0.lowercased() }) + await store.refresh() + + contests.result = .success([contest("johndoe")]) + await store.refresh() + + XCTAssertEqual(list.loadState, .contests(refreshFailed: false)) + } + + // MARK: Send and the one outcome (AC-05, AC-06, AC-14b) + + private var caster: ScriptedCaster! + + private func landed(_ node: VoterNode, recorded: Bool = true) -> VoteOutcome { + VoteOutcome(node: node, failure: nil, historyRecorded: recorded) + } + + private func refused(_ node: VoterNode, _ reason: String = "No votes left") -> VoteOutcome { + VoteOutcome(node: node, failure: reason) + } + + /// Two ticked masternodes with an empty, known history on "johndoe". + private func makeVotingStore() async -> (store: VotingStore, a: VoterNode, b: VoterNode, johndoe: DPNSContest) { + let a = node(1), b = node(2) + nodes.resolution = .init(nodes: [a, b], mayBeIncomplete: false) + prefs.votingNodeSelection = [a.proTxHash, b.proTxHash] + let johndoe = contest("johndoe", endsAt: Date().addingTimeInterval(30 * day), lock: 1) + contests.result = .success([johndoe]) + contests.voteStateResult = .success(ongoing("johndoe", lock: 7)) + caster = ScriptedCaster() + caster.history = history + let store = makeStore(caster: caster) + await store.refresh() + return (store, a, b, johndoe) + } + + func testAllLandedGivesSuccessToastAndUpdatesCountsAndMyVote() async throws { + let (store, a, b, johndoe) = await makeVotingStore() + caster.script = .outcomes([landed(a), landed(b)]) + + await store.send(choice: approve, on: johndoe, from: [a, b]) + + guard case .success(let toast)? = store.outcome else { + return XCTFail("expected .success, got \(String(describing: store.outcome))") + } + XCTAssertEqual(toast.message, "Voted \(johndoe.displayTitle) username") + let limit = try XCTUnwrap(store.voteHistoryByContest["johndoe"]) + XCTAssertEqual(limit.votesLeft(a.proTxHash), VoteLimit.maxCastsPerNode - 1) + XCTAssertEqual(limit.votesLeft(b.proTxHash), VoteLimit.maxCastsPerNode - 1) + XCTAssertEqual(store.myChoices(on: "johndoe"), [approve]) + XCTAssertEqual(store.votedNodeCount(on: "johndoe"), 2) + XCTAssertEqual(store.contests.first?.lockVotes, 7, "the contest's tallies are re-read once the votes landed") + XCTAssertFalse(store.isSending(normalizedLabel: "johndoe")) + XCTAssertEqual(caster.calls.count, 1) + XCTAssertEqual(caster.calls.first?.label, "johndoe") + XCTAssertEqual(caster.calls.first?.nodes.map(\.proTxHash), [a.proTxHash, b.proTxHash]) + } + + /// A full refresh that ran while the vote was in flight already counted + /// it; when the store cannot be read afterwards, the patch must not count + /// the same vote again — a fourth vote stays a fourth, with one left. + func testAVoteAFullRefreshAlreadyCountedIsNotCountedAgainWhenTheReReadFails() async throws { + let (store, a, _, johndoe) = await makeVotingStore() + history.records = [CastVoteRecord( + proTxHash: a.proTxHash, normalizedLabel: "johndoe", choice: approve, castAt: epoch, castCount: 3)] + await store.refresh() + caster.history = nil + caster.script = .outcomes([landed(a)]) + caster.holdNextCall = true + + let send = Task { await store.send(choice: approve, on: johndoe, from: [a]) } + while !caster.started { await Task.yield() } + // The caster wrote the fourth cast; a refresh reads it while the cast + // is still returning. + history.records = [CastVoteRecord( + proTxHash: a.proTxHash, normalizedLabel: "johndoe", choice: approve, castAt: Date(), castCount: 4)] + await store.refresh() + XCTAssertEqual(store.voteHistoryByContest["johndoe"]?.votesLeft(a.proTxHash), 1) + history.records = nil + caster.release() + await send.value + + let limit = try XCTUnwrap(store.voteHistoryByContest["johndoe"]) + XCTAssertEqual(limit.votesLeft(a.proTxHash), 1, "the landed vote is counted once") + } + + /// The twin: no load saw the vote, so when the store cannot be read + /// afterwards the patch counts it — a fourth vote leaves one, not two. + func testAVoteNoLoadSawIsCountedWhenTheReReadFails() async throws { + let (store, a, _, johndoe) = await makeVotingStore() + history.records = [CastVoteRecord( + proTxHash: a.proTxHash, normalizedLabel: "johndoe", choice: approve, castAt: epoch, castCount: 3)] + await store.refresh() + caster.history = nil + caster.script = .outcomes([landed(a)]) + caster.holdNextCall = true + + let send = Task { await store.send(choice: approve, on: johndoe, from: [a]) } + while !caster.started { await Task.yield() } + history.records = nil + caster.release() + await send.value + + let limit = try XCTUnwrap(store.voteHistoryByContest["johndoe"]) + XCTAssertEqual(limit.votesLeft(a.proTxHash), 1, "the landed vote is counted") + } + + /// Owner decision: Platform accepted the vote but the history write + /// failed. The cast is spent all the same. + func testLandedWithoutHistoryRecordStillSpendsACast() async throws { + let (store, a, _, johndoe) = await makeVotingStore() + caster.script = .outcomes([landed(a, recorded: false)]) + + await store.send(choice: approve, on: johndoe, from: [a]) + + guard case .success? = store.outcome else { + return XCTFail("expected .success, got \(String(describing: store.outcome))") + } + let limit = try XCTUnwrap(store.voteHistoryByContest["johndoe"]) + XCTAssertEqual(limit.votesLeft(a.proTxHash), VoteLimit.maxCastsPerNode - 1) + XCTAssertEqual(store.myChoices(on: "johndoe"), [approve]) + } + + /// The unrecorded cast stays spent when the contest's history is read + /// again — opening Request details does that. + func testUnrecordedCastStaysSpentAfterTheContestHistoryReloads() async throws { + let (store, a, _, johndoe) = await makeVotingStore() + caster.script = .outcomes([landed(a, recorded: false)]) + await store.send(choice: approve, on: johndoe, from: [a]) + + await store.loadVotedNodes(for: "johndoe") + + let limit = try XCTUnwrap(store.voteHistoryByContest["johndoe"]) + XCTAssertEqual(limit.votesLeft(a.proTxHash), VoteLimit.maxCastsPerNode - 1) + XCTAssertEqual(store.myChoices(on: "johndoe"), [approve]) + XCTAssertEqual(store.votedNodeCount(on: "johndoe"), 1) + } + + /// Same across a pull-to-refresh, which re-reads every contest's history. + func testUnrecordedCastStaysSpentAfterAFullRefresh() async throws { + let (store, a, _, johndoe) = await makeVotingStore() + caster.script = .outcomes([landed(a, recorded: false)]) + await store.send(choice: approve, on: johndoe, from: [a]) + + await store.refresh() + + let limit = try XCTUnwrap(store.voteHistoryByContest["johndoe"]) + XCTAssertEqual(limit.votesLeft(a.proTxHash), VoteLimit.maxCastsPerNode - 1) + XCTAssertEqual(store.myChoices(on: "johndoe"), [approve]) + } + + /// A recorded cast is in the store's rows; reading them again does not + /// count it a second time. + func testRecordedCastIsCountedOnceAfterAReload() async throws { + let (store, a, _, johndoe) = await makeVotingStore() + caster.script = .outcomes([landed(a)]) + await store.send(choice: approve, on: johndoe, from: [a]) + + await store.loadVotedNodes(for: "johndoe") + await store.refresh() + + let limit = try XCTUnwrap(store.voteHistoryByContest["johndoe"]) + XCTAssertEqual(limit.votesLeft(a.proTxHash), VoteLimit.maxCastsPerNode - 1) + } + + /// A full refresh read the history before the cast was written and applies + /// what it read after the cast returned: the cast is still there. + func testFullRefreshThatReadTheHistoryBeforeACastDoesNotEraseIt() async throws { + let (store, a, _, johndoe) = await makeVotingStore() + history.holdNextListRead = true + let full = Task { await store.refresh() } + while !history.listReadHeld { await Task.yield() } + + caster.script = .outcomes([landed(a)]) + let send = Task { await store.send(choice: approve, on: johndoe, from: [a]) } + while !caster.started { await Task.yield() } + for _ in 0..<20 { await Task.yield() } + history.releaseListRead() + await full.value + await send.value + + let limit = try XCTUnwrap(store.voteHistoryByContest["johndoe"]) + XCTAssertEqual(limit.votesLeft(a.proTxHash), VoteLimit.maxCastsPerNode - 1) + XCTAssertEqual(store.myChoices(on: "johndoe"), [approve]) + } + + func testAllFailedGivesFailureOutcomeAndClearsInFlight() async throws { + let (store, a, b, johndoe) = await makeVotingStore() + caster.script = .outcomes([refused(a, "No votes left"), refused(b, "The vote was not cast. Check your connection and try again.")]) + + await store.send(choice: approve, on: johndoe, from: [a, b]) + + guard case .failure(let message)? = store.outcome else { + return XCTFail("expected .failure, got \(String(describing: store.outcome))") + } + // Rule: the first failed outcome's message (already plain words, mapped by the caster). + XCTAssertEqual(message, "No votes left") + XCTAssertFalse(store.isSending(normalizedLabel: "johndoe"), "the pills are tappable again") + let limit = try XCTUnwrap(store.voteHistoryByContest["johndoe"]) + XCTAssertEqual(limit.votesLeft(a.proTxHash), VoteLimit.maxCastsPerNode) + XCTAssertEqual(store.myChoices(on: "johndoe"), []) + } + + /// The caster throws before anything is sent (here: the owner cancelled + /// authentication): the outcome is the plain message of that error. + func testThrownErrorGivesFailureWithThePlainMessage() async { + let (store, a, _, johndoe) = await makeVotingStore() + caster.script = .throwing(MasternodeVoteCaster.CastError.authenticationCancelled) + + await store.send(choice: approve, on: johndoe, from: [a]) + + guard case .failure(let message)? = store.outcome else { + return XCTFail("expected .failure, got \(String(describing: store.outcome))") + } + XCTAssertEqual(message, "Authentication cancelled. Your vote was not cast.") + XCTAssertFalse(store.isSending(normalizedLabel: "johndoe")) + } + + /// A contest kept after a full refresh left it out, which Platform had in + /// fact closed: the caster's "closed" refusal closes it in the store, so no + /// vote can start on it again, and its row stays until its voting end. + func testClosedRefusalClosesAKeptContest() async { + let (store, a, _, johndoe) = await makeVotingStore() + contests.result = .success([]) + await store.refresh() + XCTAssertTrue(store.canStartVote(approve, on: "johndoe"), "left out is not known to be closed") + caster.script = .throwing(MasternodeVoteCaster.CastError.contestClosed("johndoe")) + + await store.send(choice: approve, on: johndoe, from: [a]) + + XCTAssertTrue(store.isClosed(normalizedLabel: "johndoe")) + XCTAssertFalse(store.canStartVote(approve, on: "johndoe")) + XCTAssertFalse(store.canStartVote(.lock, on: "johndoe")) + XCTAssertEqual(store.contests.map(\.normalizedLabel), ["johndoe"], "the row stays until its voting end") + guard case .failure? = store.outcome else { + return XCTFail("expected .failure, got \(String(describing: store.outcome))") + } + } + + /// A full refresh asked for before the cast, whose answer still lists the + /// contest open, lands after the "closed" refusal: the contest stays closed. + func testClosedRefusalOutlivesARefreshAskedForBeforeIt() async { + let (store, a, _, johndoe) = await makeVotingStore() + let loadsBefore = contests.loads + contests.holdNextLoad = true + let refresh = Task { await store.refresh() } + while contests.loads == loadsBefore { await Task.yield() } + caster.script = .throwing(MasternodeVoteCaster.CastError.contestClosed("johndoe")) + + let send = Task { await store.send(choice: approve, on: johndoe, from: [a]) } + while !caster.started { await Task.yield() } + for _ in 0..<20 { await Task.yield() } + contests.holdNextLoad = false + contests.release() + await refresh.value + await send.value + + XCTAssertEqual(store.contests.map(\.normalizedLabel), ["johndoe"], "the refresh listed it open") + XCTAssertTrue(store.isClosed(normalizedLabel: "johndoe")) + XCTAssertFalse(store.canStartVote(approve, on: "johndoe")) + } + + /// Any other refusal says nothing about the contest: it stays open. + func testOtherRefusalLeavesTheContestOpen() async { + let (store, a, _, johndoe) = await makeVotingStore() + caster.script = .throwing(MasternodeVoteCaster.CastError.authenticationCancelled) + + await store.send(choice: approve, on: johndoe, from: [a]) + + XCTAssertFalse(store.isClosed(normalizedLabel: "johndoe")) + } + + func testThrownPlatformRefusalNeverShowsPlatformsText() async { + let (store, a, _, johndoe) = await makeVotingStore() + let raw = "Masternode with id: abc already voted 5 times and is trying to vote again" + caster.script = .throwing(SDKError.consensusRejection(PlatformConsensusError(code: 40303, kind: .state), raw)) + + await store.send(choice: approve, on: johndoe, from: [a]) + + guard case .failure(let message)? = store.outcome else { + return XCTFail("expected .failure, got \(String(describing: store.outcome))") + } + XCTAssertEqual(message, "No votes left") + } + + func testMixedGivesReportAndCountsOnlyTheLandedOnes() async throws { + let (store, a, b, johndoe) = await makeVotingStore() + caster.script = .outcomes([landed(a), refused(b)]) + + await store.send(choice: approve, on: johndoe, from: [a, b]) + + guard case .mixed(let report)? = store.outcome else { + return XCTFail("expected .mixed, got \(String(describing: store.outcome))") + } + XCTAssertEqual(report.succeeded.map(\.node.proTxHash), [a.proTxHash]) + XCTAssertEqual(report.failed.map(\.node.proTxHash), [b.proTxHash]) + let limit = try XCTUnwrap(store.voteHistoryByContest["johndoe"]) + XCTAssertEqual(limit.votesLeft(a.proTxHash), VoteLimit.maxCastsPerNode - 1) + XCTAssertEqual(limit.votesLeft(b.proTxHash), VoteLimit.maxCastsPerNode) + XCTAssertEqual(store.votedNodeCount(on: "johndoe"), 1) + XCTAssertFalse(store.isSending(normalizedLabel: "johndoe")) + } + + func testContestIsInFlightWhileTheCasterIsHeldAndASecondSendIsIgnored() async { + let (store, a, b, johndoe) = await makeVotingStore() + caster.script = .outcomes([landed(a)]) + caster.holdNextCall = true + XCTAssertFalse(store.isSending(normalizedLabel: "johndoe")) + + let first = Task { await store.send(choice: approve, on: johndoe, from: [a]) } + while !caster.started { await Task.yield() } + XCTAssertTrue(store.isSending(normalizedLabel: "johndoe")) + XCTAssertFalse(store.isSending(normalizedLabel: "other"), "only the contest being sent is in flight") + + await store.send(choice: .lock, on: johndoe, from: [b]) + XCTAssertEqual(caster.calls.count, 1, "the second send on the same contest is ignored") + + caster.release() + await first.value + XCTAssertFalse(store.isSending(normalizedLabel: "johndoe")) + XCTAssertEqual(caster.calls.count, 1) + } + + func testBeginAttemptClearsThePreviousOutcome() async { + let (store, a, _, johndoe) = await makeVotingStore() + caster.script = .outcomes([landed(a)]) + await store.send(choice: approve, on: johndoe, from: [a]) + XCTAssertNotNil(store.outcome) + + store.beginAttempt() + + XCTAssertNil(store.outcome) + } + + /// A send clears the previous outcome before it casts: no old toast sits + /// next to a vote in progress. + func testSendClearsThePreviousOutcomeWhileItIsInFlight() async { + let (store, a, b, johndoe) = await makeVotingStore() + caster.script = .outcomes([landed(a)]) + await store.send(choice: approve, on: johndoe, from: [a]) + XCTAssertNotNil(store.outcome) + + caster.holdNextCall = true + let second = Task { await store.send(choice: .abstain, on: johndoe, from: [b]) } + while caster.calls.count < 2 { await Task.yield() } + XCTAssertNil(store.outcome) + + caster.release() + await second.value + } + + // MARK: Plain-words error mapping (AC-06) + + private func consensus(_ code: UInt32) -> SDKError { + .consensusRejection(PlatformConsensusError(code: code, kind: .state), "RAW-PLATFORM-TEXT \(code)") + } + + func testPlatformTooManyVotesRefusalReadsNoVotesLeft() { + XCTAssertEqual(VoteErrorMessage.plain(for: consensus(40303)), "No votes left") + } + + func testNetworkFailuresReadAsAConnectionProblem() { + let expected = "The vote was not cast. Check your connection and try again." + XCTAssertEqual(VoteErrorMessage.plain(for: SDKError.networkError("RAW grpc status 14")), expected) + XCTAssertEqual(VoteErrorMessage.plain(for: SDKError.timeout("RAW deadline")), expected) + XCTAssertEqual(VoteErrorMessage.plain(for: URLError(.notConnectedToInternet)), expected) + } + + func testClosedContestReadsAsClosed() { + let expected = "The vote was not cast. Voting on this name has closed." + XCTAssertEqual(VoteErrorMessage.plain(for: MasternodeVoteCaster.CastError.contestClosed("johndoe")), expected) + XCTAssertEqual(VoteErrorMessage.plain(for: consensus(40302)), expected) + } + + func testKeyNotOfAnActiveMasternodeReadsAsSuch() { + let expected = "The vote was not cast. This voting key does not belong to an active masternode." + XCTAssertEqual(VoteErrorMessage.plain(for: consensus(40300)), expected) + XCTAssertEqual(VoteErrorMessage.plain(for: consensus(40305)), expected) + XCTAssertEqual(VoteErrorMessage.plain(for: consensus(40306)), expected) + } + + func testAuthenticationCancelledAndFailedReadAsNothingSent() { + XCTAssertEqual(VoteErrorMessage.plain(for: MasternodeVoteCaster.CastError.authenticationCancelled), + "Authentication cancelled. Your vote was not cast.") + XCTAssertEqual(VoteErrorMessage.plain(for: MasternodeVoteCaster.CastError.authenticationFailed), + "Authentication failed. Your vote was not cast.") + } + + /// Anything unmapped gets the generic plain message, never Platform's text. + func testUnknownErrorsNeverCarryRawText() { + struct Odd: LocalizedError { var errorDescription: String? { "RAW-PLATFORM-TEXT odd" } } + let generic = "The vote was not cast. Please try again." + XCTAssertEqual(VoteErrorMessage.plain(for: Odd()), generic) + XCTAssertEqual(VoteErrorMessage.plain(for: SDKError.internalError("RAW-PLATFORM-TEXT")), generic) + XCTAssertEqual(VoteErrorMessage.plain(for: consensus(40307)), generic) + XCTAssertFalse(VoteErrorMessage.plain(for: consensus(40304)).contains("RAW-PLATFORM-TEXT")) + } +} diff --git a/docs/adr/0013-treat-dashuikit-and-swiftdashsdk-as-library-surfaces.md b/docs/adr/0013-treat-dashuikit-and-swiftdashsdk-as-library-surfaces.md new file mode 100644 index 0000000000..af180b2d69 --- /dev/null +++ b/docs/adr/0013-treat-dashuikit-and-swiftdashsdk-as-library-surfaces.md @@ -0,0 +1,42 @@ +# 0013 — Treat DashUIKit and SwiftDashSDK as library surfaces of this feature + +- **Status:** Proposed +- **Date:** 2026-11-04 +- **Deciders:** romchornyi, with Claude during the design pass + +## Context + +The redesign needs work in three repositories: the voting screens in dashwallet-ios, new shared components in DashUIKit (stage 0: VotePill, FilterBar; follow-ups #52, #55) and the request date in the platform SDK (stage 5a: `DPNSContender.createdAt`, platform#5718). The SDD pipeline reads `target_surfaces` to decide which contract `api` writes, which task layers `tasks` plans and which test tiers `plan-tests` adds. We had to decide whether the libraries are dependencies the feature only consumes, or surfaces it owns. + +## Decision drivers + +- The owner changes all three repositories through PRs, so a later stage may add to a library instead of working around it in the app (decision during design, 2026-11-04). +- Every stage leaves the app shippable, and DashUIKit's public API changes by additions only, because the app tracks DashUIKit `master` (spec §6, SAD §1 QG-3). +- US-13 / AC-22 is a library story (the SDK read), and stage 5b depends on its public API. + +## Considered options + +1. **Only `mobile-app`** — the libraries are external dependencies; their changes live in their own PRs outside this pipeline, and AC-22 is traced to platform#5718. +2. **`mobile-app` + `library-sdk`** — the libraries' feature-specific public API is part of this feature; already-merged or approved library work is recorded as done. + +## Decision outcome + +**Chosen:** Option 2, `target_surfaces: [mobile-app, library-sdk]`. The owner can and may need to change DashUIKit or the SDK in later stages, and the pipeline should plan and trace that work instead of treating it as out of band. + +## Consequences + +**Positive** +- `api` documents the public API the feature adds to the libraries (`contracts/public-api.md`), so stage 5b builds against a written contract. +- `tasks` can plan a DashUIKit or platform PR when a stage needs one, and `review` traces AC-22 through it. + +**Negative** +- Downstream stages must skip stage 0 and stage 5a work that is already merged or approved, or they duplicate it. +- Work spans three repositories with separate reviews and release cycles; a library change that is not additive breaks develop at once (DashUIKit `master`). + +**Neutral** +- The C4 Context (SAD §3) still shows DashUIKit and SwiftDashSDK as separate systems: they are separate repositories; the C4 Container view (SAD §5) draws the parts this feature owns. + +## Links + +- Feature summary: [docs/features/username-voting/README.md](../features/username-voting/README.md) +- Related ADR: [0014 — Split voting state into a shared store and per-screen view models](0014-split-voting-state-into-a-shared-store-and-per-screen-view-models.md) diff --git a/docs/adr/0014-split-voting-state-into-a-shared-store-and-per-screen-view-models.md b/docs/adr/0014-split-voting-state-into-a-shared-store-and-per-screen-view-models.md new file mode 100644 index 0000000000..bb63e1d043 --- /dev/null +++ b/docs/adr/0014-split-voting-state-into-a-shared-store-and-per-screen-view-models.md @@ -0,0 +1,43 @@ +# 0014 — Split voting state into a shared store and per-screen view models + +- **Status:** Proposed +- **Date:** 2026-11-04 +- **Deciders:** romchornyi, with Claude during the design pass + +## Context + +Today one `@MainActor` `VotingViewModel` (826 lines) serves the list, the contest screen and the key flow: contests, votable and ticked masternodes, vote history, filters, casting, toast. The redesign adds Request details, Quick voting, the vote-limit and lock-is-final dialogs and the result sheet, and every one of them must see the same data — a vote from Request details has to fill the pill on the list. We had to decide where that state lives. + +## Decision drivers + +- Vote safety: one source for my vote and the vote limit, so no screen decides on stale counts (SAD §1 QG-1; CONTEXT invariant "No masternode of this wallet ever exceeds the vote limit"). +- Testability: today `VoteHistoryDAOImpl.shared` is hard-wired into the view model, and there are no tests for `VotingViewModel` or `MasternodeVoteCaster`. +- SwiftUI-first with `@MainActor` `ObservableObject` view models (CLAUDE.md, SAD §2). + +## Considered options + +1. **Keep one `VotingViewModel`, extract pure planners** — the view model stays the single source of truth for every screen; new rules go into pure value types in their own files. +2. **A shared store plus one view model per screen** — a `@MainActor` store owns contests, masternodes, history, in-flight votes and the outcome; list, Request details, voting keys and Quick voting each get a small view model over it; rules live in pure value types. + +## Decision outcome + +**Chosen:** Option 2. Each screen's view model stays small and testable on its own, and the store is the one place that owns my vote and the vote limit; the owner preferred the cleaner split now over growing the existing view model further. + +## Consequences + +**Positive** +- One owner for the data every screen shares; screen view models hold only presentation state. +- The caster keeps writing each landed vote to the vote history as it lands (so an interrupted run loses nothing) and re-checks the votes left before each cast; the store owns the in-memory view of my vote and every decision on the vote limit. +- The store takes its dependencies (contest service, registry, caster, vote history, prefs) by injection, so it and the planners can be unit-tested. + +**Negative** +- Brings forward part of the clean-code rework spec §3 lists as a non-goal; stage PRs grow, and the list and filter code already written for stages 1–2 moves onto the store. +- More types to wire and review; screens must not cache store data in their own state. + +**Neutral** +- The later clean-code rework (spec §3) starts from this split instead of from one view model. + +## Links + +- Feature summary: [docs/features/username-voting/README.md](../features/username-voting/README.md) +- Related ADR: [0013 — Treat DashUIKit and SwiftDashSDK as library surfaces of this feature](0013-treat-dashuikit-and-swiftdashsdk-as-library-surfaces.md) diff --git a/docs/adr/README.md b/docs/adr/README.md index 7542e1ce04..d619cd6ce7 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -18,6 +18,8 @@ where they disagree, ADR-0001 wins. | [0010](0010-probe-live-swap-routes-with-address-free-forced-quotes.md) | Probe live routes with address-free quotes forced to one provider | swap | Proposed | | | [0011](0011-keep-live-swap-route-answers-in-one-shared-in-memory-store.md) | Keep live route answers in one shared in-memory store with two-step ageing | swap | Proposed | | | [0012](0012-detect-a-near-outage-from-sentinel-coins.md) | Detect a NEAR outage from sentinel coins before per-coin checks | swap | Proposed | | +| [0013](0013-treat-dashuikit-and-swiftdashsdk-as-library-surfaces.md) | Treat DashUIKit and SwiftDashSDK as library surfaces of this feature | ui | Proposed | | +| [0014](0014-split-voting-state-into-a-shared-store-and-per-screen-view-models.md) | Split voting state into a shared store and per-screen view models | ui | Proposed | | | [0015](0015-fence-a-pending-sign-in-on-disconnect.md) | Fence a pending sign-in on disconnect and recover forward only | platform | Proposed | | | [0016](0016-turn-off-unrecorded-keys-on-disconnect-without-asking.md) | Turn off unrecorded keys on disconnect without asking | platform | Proposed | | | [0017](0017-answer-an-app-connect-request-at-most-once.md) | Answer an App Connect request at most once | platform | Proposed | | diff --git a/docs/features/username-voting/README.md b/docs/features/username-voting/README.md new file mode 100644 index 0000000000..c9ca7c36bf --- /dev/null +++ b/docs/features/username-voting/README.md @@ -0,0 +1,55 @@ +# Username voting: decide and vote from the list + +**Owner:** romchornyi · Introduced in stages; this page grows with each stage PR. + +## Why + +A masternode owner opens Username Voting to decide who should get a contested name, and the old +screen gave them little to decide with: contenders by name and vote count only, the link, the +identity and the voting period behind a separate contest screen, bulk voting behind an unlabelled +menu, and an open contest that could disappear from the list mid-session. The Android wallet already +has the redesigned flow, and the designer has drawn it for iOS. Masternode owners vote from both +wallets, so iOS follows Android's rules where the design is silent, minus Android's known bugs. + +## What changed + +Stages 1–3 (this set of PRs): + +- **The list follows the design.** A large title with an explanation, "All" with the number of open + usernames, a username search, and the contests grouped under "Voting ends today / in N days", + soonest day first; contests with no known voting end come last. Each row shows a block pill and an + approve pill with their counts, and the pill that carries my vote is filled. +- **Filters.** A sheet sorts by date or by votes and keeps only names I approved, names I have not + voted on, names with block votes, or names with several requests. A bar at the bottom names the + sort. "Vote on several" is removed; Quick voting replaces it in a later stage. +- **Several requests open in place.** A name with more than one request shows «N requests» and an + expand pill; it opens in place and lists each request with its own approve pill. +- **Request details opens straight from a row**, with the username, the link, the identity and the + voting end. The separate contest screen is gone. +- **The list keeps what it knows.** A contest stays until its voting end even when a later read of + it comes back empty or fails, newer data always wins over an older read, and a list that cannot + load says so and offers Try again instead of showing an empty list. +- **One owner for voting state.** A shared store holds contests, masternodes, my vote history and + the vote limit; each screen has a small view model over it + ([ADR-0014](../../adr/0014-split-voting-state-into-a-shared-store-and-per-screen-view-models.md)). + The shared components come from DashUIKit and the request dates from SwiftDashSDK, both changed + through their own PRs ([ADR-0013](../../adr/0013-treat-dashuikit-and-swiftdashsdk-as-library-surfaces.md)). + +## What it guarantees + +- No masternode of this wallet votes more than 5 times on one contest; the limit is checked again + before each cast. +- A vote that landed is never shown as not cast because an older list read arrived later. +- A contest is not removed from the list before its voting end. + +## Not in scope here + +Later stage PRs of the same feature: + +- Voting straight from the pills, the "One vote left", "No votes left" and lock-is-final dialogs, + the vote-result sheet, and "Add your voting keys" with tick-boxes (stage 4). +- Request dates, "Link included", the voting period start, "Only requests with links" and Quick + voting (stage 5b, after the platform SDK change for request dates). +- Votes cast from another device stay invisible: the vote history is local, as on Android. + +The screens follow the design canon in [`docs/design-system.md`](../../design-system.md). diff --git a/docs/review/username-voting/README.md b/docs/review/username-voting/README.md new file mode 100644 index 0000000000..b8744ea1a0 --- /dev/null +++ b/docs/review/username-voting/README.md @@ -0,0 +1,13 @@ +# Username voting review captures + +Captured on 2026-11-09 on an iPhone 17 simulator (iOS 26.5, light appearance) with a new wallet +that holds no masternode voting keys, against the open contests on mainnet at that time. The +contests come from the network: the names, counts and voting ends are whatever was open then. + +- `before-*`: develop at `7defb2472`, before the redesign. +- `stage1-list`: the list restyle (stage 1). +- `stage2-*`: the Filters sheet and a filtered list (stage 2). +- `stage3-*`: the list on the shared store and Request details opened from a row (stage 3). + +Two captures are cropped at the bottom to leave out offensive usernames that were open on the +network. No several-request contest was open, so the expanded row is not captured here. diff --git a/docs/review/username-voting/before-details.png b/docs/review/username-voting/before-details.png new file mode 100644 index 0000000000..08a56ec69e Binary files /dev/null and b/docs/review/username-voting/before-details.png differ diff --git a/docs/review/username-voting/before-list.png b/docs/review/username-voting/before-list.png new file mode 100644 index 0000000000..4fae35999b Binary files /dev/null and b/docs/review/username-voting/before-list.png differ diff --git a/docs/review/username-voting/stage1-list.png b/docs/review/username-voting/stage1-list.png new file mode 100644 index 0000000000..0ce5f20159 Binary files /dev/null and b/docs/review/username-voting/stage1-list.png differ diff --git a/docs/review/username-voting/stage2-filtered.png b/docs/review/username-voting/stage2-filtered.png new file mode 100644 index 0000000000..eeeb97697c Binary files /dev/null and b/docs/review/username-voting/stage2-filtered.png differ diff --git a/docs/review/username-voting/stage2-list.png b/docs/review/username-voting/stage2-list.png new file mode 100644 index 0000000000..77b7b9b439 Binary files /dev/null and b/docs/review/username-voting/stage2-list.png differ diff --git a/docs/review/username-voting/stage2-sheet.png b/docs/review/username-voting/stage2-sheet.png new file mode 100644 index 0000000000..073573ddb3 Binary files /dev/null and b/docs/review/username-voting/stage2-sheet.png differ diff --git a/docs/review/username-voting/stage3-details.png b/docs/review/username-voting/stage3-details.png new file mode 100644 index 0000000000..6bae64052d Binary files /dev/null and b/docs/review/username-voting/stage3-details.png differ diff --git a/docs/review/username-voting/stage3-list.png b/docs/review/username-voting/stage3-list.png new file mode 100644 index 0000000000..c24a3369ee Binary files /dev/null and b/docs/review/username-voting/stage3-list.png differ