diff --git a/app/src/main/java/to/bitkit/data/SettingsStore.kt b/app/src/main/java/to/bitkit/data/SettingsStore.kt index fbf896117e..4af64ea843 100644 --- a/app/src/main/java/to/bitkit/data/SettingsStore.kt +++ b/app/src/main/java/to/bitkit/data/SettingsStore.kt @@ -242,14 +242,6 @@ data class SettingsData( val isQuickPayEnabled: Boolean = false, val quickPayAmount: Int = 5, val quickPayDailyLimitMultiplier: Int = 5, - /** - * The paired Wear OS watch's own QuickPay, set here and pushed to the watch, and carried by the settings backup - * to a watch that reads it. Off until the user turns it on; it holds on the watch only while [isQuickPayEnabled] - * is on too. Older builds and bitkit-ios ignore these keys, and a backup without them gives these defaults. - */ - val isWatchQuickPayEnabled: Boolean = false, - val watchQuickPayAmount: Int = 5, - val watchQuickPayDailyLimitMultiplier: Int = 5, /** Whether the prompt to install Bitkit on a connected watch was shown; it shows once. */ val watchInstallPromptSeen: Boolean = false, val isPinEnabled: Boolean = false, diff --git a/app/src/main/java/to/bitkit/data/WatchLinkStore.kt b/app/src/main/java/to/bitkit/data/WatchLinkStore.kt index 1811b0bd3e..bad790a729 100644 --- a/app/src/main/java/to/bitkit/data/WatchLinkStore.kt +++ b/app/src/main/java/to/bitkit/data/WatchLinkStore.kt @@ -65,10 +65,6 @@ class WatchLinkStore internal constructor( override val record: Flow = store.data.map { it.record }.distinctUntilChanged() - /** The watch's last QuickPay count as it changes, or null without a paired watch or before its first count. */ - val watchQuickPayUpdates: Flow = - store.data.map { data -> data.watchQuickPay?.takeIf { data.record != null } }.distinctUntilChanged() - override suspend fun load(): LinkRecord? = store.data.first().record override suspend fun update(transform: (LinkRecord?) -> LinkRecord?): LinkRecord? = diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index 85845593bf..4f0525c74d 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -989,10 +989,7 @@ class QuickPayAuthorization( val useBiometrics: Boolean, ) -/** - * One QuickPay setting the user asked to change, with its new value: the phone's own QuickPay or the watch's. Both - * follow one rule: a raise asks for the PIN or biometric check while payments need the PIN. - */ +/** One QuickPay setting the user asked to change, with its new value. */ sealed interface QuickPayChange { fun isRaise(settings: SettingsData): Boolean fun applyTo(settings: SettingsData): SettingsData @@ -1011,21 +1008,6 @@ sealed interface QuickPayChange { override fun isRaise(settings: SettingsData) = value > settings.quickPayDailyLimitMultiplier override fun applyTo(settings: SettingsData) = settings.copy(quickPayDailyLimitMultiplier = value) } - - data class WatchEnabled(val value: Boolean) : QuickPayChange { - override fun isRaise(settings: SettingsData) = value && !settings.isWatchQuickPayEnabled - override fun applyTo(settings: SettingsData) = settings.copy(isWatchQuickPayEnabled = value) - } - - data class WatchAmount(val value: Int) : QuickPayChange { - override fun isRaise(settings: SettingsData) = value > settings.watchQuickPayAmount - override fun applyTo(settings: SettingsData) = settings.copy(watchQuickPayAmount = value) - } - - data class WatchDailyLimitMultiplier(val value: Int) : QuickPayChange { - override fun isRaise(settings: SettingsData) = value > settings.watchQuickPayDailyLimitMultiplier - override fun applyTo(settings: SettingsData) = settings.copy(watchQuickPayDailyLimitMultiplier = value) - } } fun interface QuickPayInvoiceParser { diff --git a/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt b/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt index d8ca2a092a..c0d1470bfa 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt @@ -17,7 +17,6 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.Flow @@ -25,20 +24,14 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch -import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import kotlinx.coroutines.withTimeoutOrNull -import kotlinx.datetime.TimeZone -import kotlinx.datetime.toLocalDateTime import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore import to.bitkit.data.SettingsData @@ -54,20 +47,15 @@ import to.bitkit.utils.Logger import to.bitkit.wearlink.AttestationPolicy import to.bitkit.wearlink.AttestationStatusList import to.bitkit.wearlink.AttestationVerifier -import to.bitkit.wearlink.HandoffInbox import to.bitkit.wearlink.LinkCrypto -import to.bitkit.wearlink.LinkGuards -import to.bitkit.wearlink.LinkHandoff import to.bitkit.wearlink.LinkKeyStore import to.bitkit.wearlink.LinkNode import to.bitkit.wearlink.LinkPacket -import to.bitkit.wearlink.LinkPaths import to.bitkit.wearlink.LinkRecord import to.bitkit.wearlink.LinkTransport import to.bitkit.wearlink.OpenSend import to.bitkit.wearlink.PairingState import to.bitkit.wearlink.PairingThrottle -import to.bitkit.wearlink.PayResult import to.bitkit.wearlink.PeerInvoice import to.bitkit.wearlink.PeerStateListener import to.bitkit.wearlink.PhoneLink @@ -78,11 +66,9 @@ import to.bitkit.wearlink.SeedPayload import to.bitkit.wearlink.SettingsDoc import to.bitkit.wearlink.WalletLink import java.io.ByteArrayOutputStream -import java.security.SecureRandom import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Clock -import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime @@ -99,7 +85,6 @@ import kotlin.time.ExperimentalTime * wallet and pushes it the settings: nothing secret is sent then. * * The phone's settings are published to the paired watch when the pairing is made and whenever one of them changes, - * the watch's own QuickPay limits with them, * and so are the shared guards' documents: the phone's own unexpired Spark invoices, its QuickPay count of its day, * and its open Spark sends. Each document has one publisher, which also publishes it again once the watch's first * status shows it noted the pairing, since the watch drops what arrives before that. What the watch publishes of its @@ -140,9 +125,6 @@ class WatchLinkRepo internal constructor( /** The Play listing of an app, completed with its application id. */ private const val MARKET_URI = "market://details?id=" - /** How long the phone waits for the watch to answer a handed-off request before it calls it unreachable. */ - private val HANDOFF_ANSWER_TIMEOUT = 10.seconds - /** * Reads Google's attestation status list: one GET of a public file that is the same for everyone. The * request names no user, wallet or watch. A response longer than the list may be is refused by its @@ -243,14 +225,6 @@ class WatchLinkRepo internal constructor( /** The paired watch, or null. */ val record: Flow = store.record - /** - * What the paired watch spent under QuickPay on this phone's day, in US cents, as it last said: 0 before its first - * count or for a count of another day, and null without a paired watch. - */ - val watchSpentTodayCents: Flow = combine(store.record, store.watchQuickPayUpdates) { record, quickPay -> - record?.let { LinkGuards.peerCents(quickPay, todayKey()) } - }.distinctUntilChanged() - private val _pairing = MutableStateFlow(WatchPairingStatus.Idle) val pairing: StateFlow = _pairing.asStateFlow() @@ -389,61 +363,6 @@ class WatchLinkRepo internal constructor( .onFailure { Logger.warn("Failed to open the Play listing on the watch", it, context = TAG) } } - /** Whether the paired watch, with Bitkit, is connected to this phone now. */ - suspend fun isWatchReachable(): Boolean = withContext(ioDispatcher) { - runSuspendCatching { - val record = store.load()?.takeIf { it.removal == null } ?: return@runSuspendCatching false - transport.nodes().any { it.id == record.peerNodeId && it.hasApp } - }.onFailure { Logger.warn("Failed to look for the paired watch", it, context = TAG) }.getOrDefault(false) - } - - /** - * Hands the payment request [input] to the paired watch, to be reviewed and held to pay there, never under - * QuickPay (`docs/wear.md`, Pairing › Payment handoff). The request goes over the link as a one-shot message; - * once the watch kept it, the phone opens its link on the watch, which names only the request's id. Emits what - * became of it: [PayOnWatchResult.Sent], [PayOnWatchResult.Busy], [PayOnWatchResult.Refused] when the watch - * answered that it does not take it, or [PayOnWatchResult.Unreachable] when it could not be reached or did not - * answer; and after a [PayOnWatchResult.Sent] a later [PayOnWatchResult.Busy] or [PayOnWatchResult.Refused] when - * the watch dropped it, for a send under way or because it could not show it. Neither the request nor its input - * is logged. - */ - @OptIn(ExperimentalStdlibApi::class) - fun payOnWatch(input: String): Flow = channelFlow { - val id = ByteArray(LinkHandoff.ID_CHARS / 2).also(SecureRandom()::nextBytes).toHexString() - val answers = link.payResults.filter { it.id == id } - val answer = async(start = CoroutineStart.UNDISPATCHED) { - withTimeoutOrNull(HANDOFF_ANSWER_TIMEOUT) { answers.first() } - } - val sent = runSuspendCatching { link.requestPay(id, input) } - .onFailure { Logger.warn("Failed to hand a payment request to the watch", it, context = TAG) } - if (sent.isFailure) { - answer.cancel() - send(PayOnWatchResult.Unreachable) - return@channelFlow - } - val result = answer.await()?.result - Logger.info("Handed a payment request to the watch, which answered '$result'", context = TAG) - when (result) { - PayResult.Busy -> send(PayOnWatchResult.Busy) - PayResult.Received -> { - val opened = runSuspendCatching { link.openOnWatch(LinkPaths.payUri(id)) } - .onFailure { Logger.warn("Failed to open the handed-off request on the watch", it, context = TAG) } - if (opened.isFailure) { - send(PayOnWatchResult.Unreachable) - return@channelFlow - } - send(PayOnWatchResult.Sent) - val dropped = withTimeoutOrNull(HandoffInbox.WINDOW_MS.milliseconds) { - answers.first { it.result != PayResult.Received } - } ?: return@channelFlow - Logger.info("Heard the watch dropped the handed-off request as '${dropped.result}'", context = TAG) - send(if (dropped.result == PayResult.Busy) PayOnWatchResult.Busy else PayOnWatchResult.Refused) - } - PayResult.Refused -> send(PayOnWatchResult.Refused) - null -> send(PayOnWatchResult.Unreachable) - } - }.flowOn(ioDispatcher) - /** * Ends the pairing that runs, as when its screen goes away, and forgets the last one's end. A pairing that has * not found the watch yet ends without opening anything on it. @@ -462,11 +381,11 @@ class WatchLinkRepo internal constructor( private suspend fun isPinSet(): Boolean = settingsStore.data.first().isPinEnabled /** - * Asks the watch to forget this phone, and with [isErase] to delete its wallet. The watch stays listed, marked, - * until it acknowledges: an erase is best effort, since a watch that never reconnects never reads it. + * The user's unpair: asks the watch to forget this phone and to delete its wallet. The watch stays listed, + * marked, until it acknowledges: the erase is best effort, since a watch that never reconnects never reads it. */ - suspend fun remove(isErase: Boolean): Result = withContext(ioDispatcher) { - runSuspendCatching { link.remove(isErase) } + suspend fun unpair(): Result = withContext(ioDispatcher) { + runSuspendCatching { link.remove() } .onFailure { Logger.warn("Failed to remove the watch", it, context = TAG) } } @@ -517,14 +436,8 @@ class WatchLinkRepo internal constructor( isQuickPayEnabled = isQuickPayEnabled, quickPayAmount = quickPayAmount, quickPayDailyLimitMultiplier = quickPayDailyLimitMultiplier, - isWatchQuickPayEnabled = isWatchQuickPayEnabled, - watchQuickPayAmount = watchQuickPayAmount, - watchQuickPayDailyLimitMultiplier = watchQuickPayDailyLimitMultiplier, ) - /** The phone's day as its QuickPay count names it: the ISO date of the device's own time zone. */ - private fun todayKey(): String = clock.now().toLocalDateTime(TimeZone.currentSystemDefault()).date.toString() - private inner class PairingEnv : PhonePairingEnv { override val appId: String = this@WatchLinkRepo.appId override val name: String = Build.MODEL.orEmpty() @@ -587,13 +500,6 @@ sealed interface WatchPairingStatus { data class Failed(val error: Throwable) : WatchPairingStatus } -/** - * What became of a payment request handed to the watch: the one line the send review shows. [Refused] when the watch - * was reached and answered that it does not take the request, or dropped it where it could not show it; - * [Unreachable] when it was not reached or did not answer. - */ -enum class PayOnWatchResult { Sent, Busy, Refused, Unreachable } - sealed class WatchLinkError(message: String) : AppError(message) { /** No connected watch has Bitkit and is reached directly. */ class NoWatch : WatchLinkError("No watch with Bitkit is connected nearby") diff --git a/app/src/main/java/to/bitkit/ui/components/SheetIntro.kt b/app/src/main/java/to/bitkit/ui/components/SheetIntro.kt index 22face51ba..82e54c8531 100644 --- a/app/src/main/java/to/bitkit/ui/components/SheetIntro.kt +++ b/app/src/main/java/to/bitkit/ui/components/SheetIntro.kt @@ -5,15 +5,18 @@ import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource @@ -26,6 +29,34 @@ import to.bitkit.ui.theme.Colors /** Width fraction used by intro sheet artwork. */ const val SHEET_INTRO_IMAGE_WIDTH_FRACTION = 0.8f +/** The size of a one-colour icon that stands in for intro sheet artwork, centred in the artwork's slot. */ +private val SHEET_INTRO_ICON_SIZE = 160.dp + +/** + * A one-colour [icon] that stands in for intro sheet artwork where none exists, enlarged and centred in the artwork's + * slot, in Brand orange, as the intro sheets' accented titles. + */ +@Composable +fun ColumnScope.SheetIntroIcon( + @DrawableRes icon: Int, + modifier: Modifier = Modifier, +) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .fillMaxWidth() + .weight(1f) + ) { + Image( + painter = painterResource(icon), + contentDescription = null, + contentScale = ContentScale.Fit, + colorFilter = ColorFilter.tint(Colors.Brand), + modifier = modifier.size(SHEET_INTRO_ICON_SIZE) + ) + } +} + @Composable fun SheetIntro( navTitle: String, @@ -42,6 +73,7 @@ fun SheetIntro( testTag: String = "SheetIntro", cancelTestTag: String = "${testTag}Cancel", continueTestTag: String = "${testTag}Continue", + isImageIcon: Boolean = false, ) { Column( modifier = modifier @@ -55,21 +87,25 @@ fun SheetIntro( Column( modifier = Modifier.padding(horizontal = 32.dp), ) { - Box( - contentAlignment = Alignment.BottomCenter, - modifier = Modifier - .fillMaxWidth() - .weight(1f) - ) { - Image( - painter = painterResource(image), - contentDescription = null, - contentScale = ContentScale.Fit, + if (isImageIcon) { + SheetIntroIcon(icon = image, modifier = Modifier.testTag("${testTag}Image")) + } else { + Box( + contentAlignment = Alignment.BottomCenter, modifier = Modifier - .fillMaxWidth(SHEET_INTRO_IMAGE_WIDTH_FRACTION) - .heightIn(max = 320.dp) - .testTag("${testTag}Image") - ) + .fillMaxWidth() + .weight(1f) + ) { + Image( + painter = painterResource(image), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier + .fillMaxWidth(SHEET_INTRO_IMAGE_WIDTH_FRACTION) + .heightIn(max = 320.dp) + .testTag("${testTag}Image") + ) + } } VerticalSpacer(32.dp) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/PayOnWatch.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/PayOnWatch.kt deleted file mode 100644 index 690fac4230..0000000000 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/PayOnWatch.kt +++ /dev/null @@ -1,97 +0,0 @@ -package to.bitkit.ui.screens.wallets.send - -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.size -import androidx.compose.material3.Icon -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.testTag -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.tooling.preview.Preview -import androidx.compose.ui.unit.dp -import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import to.bitkit.R -import to.bitkit.repositories.PayOnWatchResult -import to.bitkit.ui.components.BodyS -import to.bitkit.ui.components.ButtonSize -import to.bitkit.ui.components.SecondaryButton -import to.bitkit.ui.components.VerticalSpacer -import to.bitkit.ui.theme.AppThemeSurface -import to.bitkit.ui.theme.Colors - -/** - * The send review's secondary action for a Lightning request while the paired watch is reachable: it hands [input] - * to the watch, which shows its review and asks for its hold to pay, and then shows one line of what became of it. - */ -@Composable -fun PayOnWatch( - input: String, - modifier: Modifier = Modifier, - viewModel: PayOnWatchViewModel = hiltViewModel(), -) { - val uiState by viewModel.uiState.collectAsStateWithLifecycle() - LaunchedEffect(viewModel) { viewModel.refresh() } - if (!uiState.isAvailable) return - Content( - uiState = uiState, - onClick = { viewModel.onPayOnWatchClick(input) }, - modifier = modifier, - ) -} - -@Composable -private fun Content( - uiState: PayOnWatchUiState, - modifier: Modifier = Modifier, - onClick: () -> Unit = {}, -) { - Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier) { - SecondaryButton( - text = stringResource(R.string.wallet__send_pay_on_watch), - onClick = onClick, - icon = { - Icon( - painter = painterResource(R.drawable.ic_watch), - contentDescription = null, - tint = Colors.Purple, - modifier = Modifier.size(16.dp) - ) - }, - isLoading = uiState.isSending, - size = ButtonSize.Small, - fullWidth = false, - testTag = "SendPayOnWatch", - ) - uiState.result?.let { result -> - VerticalSpacer(8.dp) - BodyS( - text = stringResource( - when (result) { - PayOnWatchResult.Sent -> R.string.wallet__send_pay_on_watch_sent - PayOnWatchResult.Busy -> R.string.wallet__send_pay_on_watch_busy - PayOnWatchResult.Refused -> R.string.wallet__send_pay_on_watch_refused - PayOnWatchResult.Unreachable -> R.string.wallet__send_pay_on_watch_unreachable - }, - ), - color = if (result == PayOnWatchResult.Sent) Colors.White64 else Colors.Red, - textAlign = TextAlign.Center, - modifier = Modifier.testTag("SendPayOnWatchResult") - ) - } - VerticalSpacer(8.dp) - } -} - -@Preview(showBackground = true) -@Composable -private fun Preview() { - AppThemeSurface { - Content(uiState = PayOnWatchUiState(isAvailable = true, result = PayOnWatchResult.Sent)) - } -} diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/PayOnWatchViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/PayOnWatchViewModel.kt deleted file mode 100644 index ab5d368469..0000000000 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/PayOnWatchViewModel.kt +++ /dev/null @@ -1,59 +0,0 @@ -package to.bitkit.ui.screens.wallets.send - -import androidx.compose.runtime.Immutable -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import to.bitkit.repositories.PayOnWatchResult -import to.bitkit.repositories.WatchLinkRepo -import javax.inject.Inject - -/** - * Pay on Watch on the send review: offered for a Lightning request while the paired watch is reachable, it hands the - * request to the watch, which reviews it and asks for its hold to pay (`docs/wear.md`, Pairing › Payment handoff). - * Only created while the watch link is enabled. - */ -@HiltViewModel -class PayOnWatchViewModel @Inject constructor( - private val watchLinkRepo: WatchLinkRepo, -) : ViewModel() { - private val _uiState = MutableStateFlow(PayOnWatchUiState()) - val uiState: StateFlow = _uiState.asStateFlow() - - private var handoff: Job? = null - - /** Looks whether the paired watch is reachable, as the review shows. */ - fun refresh() { - viewModelScope.launch { - val isAvailable = watchLinkRepo.isWatchReachable() - _uiState.update { it.copy(isAvailable = isAvailable) } - } - } - - /** Hands [input], the request under review, to the watch; a tap while one is on its way does nothing. */ - fun onPayOnWatchClick(input: String) { - if (_uiState.value.isSending) return - handoff?.cancel() - _uiState.update { it.copy(isSending = true, result = null) } - handoff = viewModelScope.launch { - watchLinkRepo.payOnWatch(input).collect { result -> - _uiState.update { it.copy(isSending = false, result = result) } - } - _uiState.update { it.copy(isSending = false) } - } - } -} - -/** [isAvailable] while the paired watch is reachable; [result] is the one line shown after a tap. */ -@Immutable -data class PayOnWatchUiState( - val isAvailable: Boolean = false, - val isSending: Boolean = false, - val result: PayOnWatchResult? = null, -) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index 9913cc5b26..509a556446 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -147,7 +147,6 @@ fun SendConfirmScreen( onLockChange: (Boolean) -> Unit = {}, syncNodeVariant: SyncNodeVariant = SyncNodeVariant.LIGHTNING, autoPayContent: (@Composable () -> Unit)? = null, - payOnWatchContent: (@Composable (String) -> Unit)? = null, ) { val scope = rememberCoroutineScope() var isLoading by rememberSaveable { mutableStateOf(false) } @@ -226,7 +225,6 @@ fun SendConfirmScreen( syncNodeVariant = syncNodeVariant, initialShowDetails = uiState.isInitialSubscriptionPayment && !uiState.shouldAutomaticallyPay, autoPayContent = autoPayContent, - payOnWatchContent = payOnWatchContent, onBack = onBack, onEvent = onEvent, onClickAddTag = onClickAddTag, @@ -308,7 +306,6 @@ internal fun SendConfirmContent( initialShowDetails: Boolean = false, syncNodeVariant: SyncNodeVariant = SyncNodeVariant.LIGHTNING, autoPayContent: (@Composable () -> Unit)? = null, - payOnWatchContent: (@Composable (String) -> Unit)? = null, onBack: () -> Unit = {}, onEvent: (SendEvent) -> Unit = {}, onClickAddTag: () -> Unit = {}, @@ -366,7 +363,6 @@ internal fun SendConfirmContent( preparingRequest = preparingRequest, preparingContact = preparingContact, initialShowDetails = initialShowDetails, - payOnWatchContent = payOnWatchContent.takeIf { !isLocked && !isLoading }, // The payment's inputs stay as swiped while the swipe runs onEvent = { if (!isLocked) onEvent(it) }, onClickAddTag = { if (!isLocked) onClickAddTag() }, @@ -425,7 +421,6 @@ private fun ContentRunning( preparingRequest: PaykitPaymentRequest? = null, preparingContact: PubkyProfile? = null, initialShowDetails: Boolean = false, - payOnWatchContent: (@Composable (String) -> Unit)? = null, onEvent: (SendEvent) -> Unit = {}, onClickAddTag: () -> Unit = {}, onClickTag: (String) -> Unit = {}, @@ -550,11 +545,6 @@ private fun ContentRunning( } } - val payOnWatchInput = uiState.payOnWatchInput().takeIf { !isPreparing } - if (payOnWatchContent != null && payOnWatchInput != null) { - Box(modifier = Modifier.align(Alignment.CenterHorizontally)) { payOnWatchContent(payOnWatchInput) } - } - if ((!isLnurlPay || uiState.isPaymentRequest) && !isPreparing) { PrimaryButton( text = stringResource( @@ -1019,25 +1009,6 @@ private val SendUiState.paysLnurl: Boolean get() = lnurl is LnurlParams.LnurlPay && payMethod == SendMethod.LIGHTNING && routedPaykitRoute?.serviceLeg == null && activePaykitSwapRoute == null -/** - * The BOLT11 invoice the paired watch can be handed to pay, or null: the invoice of a plain Lightning send from the - * wallet that carries its amount. Not an invoice without an amount, since only the invoice is handed over and the - * amount typed on the phone would be lost; nor an LNURL, a contact's payment request or one that goes over a Spark - * leg or a swap instead of the invoice, a subscription or a hardware wallet's send. - */ -internal fun SendUiState.payOnWatchInput(): String? = decodedInvoice?.takeIf { - it.bolt11.isNotBlank() && - it.amountSatoshis > 0uL && - payMethod == SendMethod.LIGHTNING && - !paysLnurl && - routedPaykitRoute?.serviceLeg == null && - activePaykitSwapRoute == null && - !isPaymentRequest && - !isSubscriptionPayment && - !isInitialSubscriptionPayment && - hardwareWalletId == null -}?.bolt11 - private val SendUiState.confirmationRequestNote: String? get() = paymentRequestNote?.trim()?.takeIf { isPaymentRequest && it.isNotEmpty() } diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index f24e612906..df8dfbe392 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -41,7 +41,6 @@ import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.serialization.Serializable import to.bitkit.R -import to.bitkit.env.Env import to.bitkit.ext.getSatsPerVByteFor import to.bitkit.ext.supportPaymentRequest import to.bitkit.ext.toSendFailureDetails @@ -71,7 +70,6 @@ import to.bitkit.ui.screens.wallets.send.AddTagScreen import to.bitkit.ui.screens.wallets.send.HwSendSignScreen import to.bitkit.ui.screens.wallets.send.HwSendViewModel import to.bitkit.ui.screens.wallets.send.PIN_CHECK_RESULT_KEY -import to.bitkit.ui.screens.wallets.send.PayOnWatch import to.bitkit.ui.screens.wallets.send.RECOVERY_PIN_CHECK_RESULT_KEY import to.bitkit.ui.screens.wallets.send.SEND_CONFIRM_RESET_RESULT_KEY import to.bitkit.ui.screens.wallets.send.SendAddressScreen @@ -608,11 +606,6 @@ fun SendSheet( onNavigateToPin = { navController.navigateTo(SendRoute.PinCheck) }, isSwipeRunning = isSwipeRunning, onLockChange = onConfirmLockChange, - payOnWatchContent = if (Env.isWatchLinkEnabled) { - { input -> PayOnWatch(input = input) } - } else { - null - }, autoPayContent = initialSubscription?.let { subscription -> { SubscriptionFirstPaymentProgress( diff --git a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchInstallSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchInstallSheet.kt index 00a6b53bc4..8d5bdb80d4 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchInstallSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchInstallSheet.kt @@ -45,7 +45,8 @@ private fun Content( navTitle = stringResource(R.string.settings__watch__nav_title), title = stringResource(R.string.settings__watch__install_title).withAccent(accentColor = Colors.Brand), description = AnnotatedString(stringResource(R.string.settings__watch__install_text).replace("{name}", name)), - image = R.drawable.phone, + image = R.drawable.ic_watch, + isImageIcon = true, continueText = stringResource(R.string.settings__watch__install_button), onContinue = onInstall, cancelText = stringResource(R.string.common__later), diff --git a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchPairSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchPairSheet.kt index c80f389213..f2f56daec6 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchPairSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchPairSheet.kt @@ -27,7 +27,8 @@ fun WatchPairSheet( navTitle = stringResource(R.string.settings__watch__nav_title), title = stringResource(R.string.settings__watch__pair_prompt_title).withAccent(accentColor = Colors.Brand), description = AnnotatedString(stringResource(R.string.settings__watch__pair_prompt_text)), - image = R.drawable.phone, + image = R.drawable.ic_watch, + isImageIcon = true, continueText = stringResource(R.string.settings__watch__pair_confirm), onContinue = onPair, cancelText = stringResource(R.string.common__later), diff --git a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchQuickPayViewModel.kt b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchQuickPayViewModel.kt deleted file mode 100644 index 701f157ea6..0000000000 --- a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchQuickPayViewModel.kt +++ /dev/null @@ -1,109 +0,0 @@ -package to.bitkit.ui.sheets.watch - -import android.content.Context -import androidx.compose.runtime.Immutable -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import dagger.hilt.android.lifecycle.HiltViewModel -import dagger.hilt.android.qualifiers.ApplicationContext -import kotlinx.coroutines.flow.SharingStarted -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.stateIn -import kotlinx.coroutines.launch -import to.bitkit.R -import to.bitkit.data.SettingsStore -import to.bitkit.models.Toast -import to.bitkit.repositories.QuickPayAuthorization -import to.bitkit.repositories.QuickPayChange -import to.bitkit.repositories.QuickPayRepo -import to.bitkit.repositories.WatchLinkRepo -import to.bitkit.ui.shared.toast.ToastEventBus -import to.bitkit.utils.Logger -import javax.inject.Inject - -/** - * The watch's own QuickPay in the Watch sheet: on or off, the amount of one payment and the daily limit, kept in the - * phone's settings and pushed to the paired watch (`docs/wear.md`, QuickPay). Turning it on or raising a limit asks - * for the app's PIN or biometric check while payments need the PIN, by the same rule and through the same queue as the - * phone's own QuickPay settings ([QuickPayRepo.requestSettingsChange]); turning it off or lowering one never asks. - */ -@HiltViewModel -class WatchQuickPayViewModel @Inject constructor( - @ApplicationContext private val context: Context, - settingsStore: SettingsStore, - private val quickPayRepo: QuickPayRepo, - watchLinkRepo: WatchLinkRepo, -) : ViewModel() { - companion object { - private const val TAG = "WatchQuickPayViewModel" - - /** Keeps the state alive across short configuration changes. */ - private const val STOP_TIMEOUT_MS = 5_000L - } - - val uiState: StateFlow = combine( - settingsStore.data, - quickPayRepo.pendingSettingsChange, - watchLinkRepo.watchSpentTodayCents, - ) { settings, authorization, spentCents -> - WatchQuickPayUiState( - isEnabled = settings.isWatchQuickPayEnabled, - amount = settings.watchQuickPayAmount, - dailyLimitMultiplier = settings.watchQuickPayDailyLimitMultiplier, - isPhoneQuickPayEnabled = settings.isQuickPayEnabled, - spentTodayCents = spentCents, - authorization = authorization, - ) - }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), WatchQuickPayUiState()) - - fun setEnabled(isEnabled: Boolean) = requestChange(QuickPayChange.WatchEnabled(isEnabled)) - - fun setAmount(amount: Int) = requestChange(QuickPayChange.WatchAmount(amount)) - - fun setDailyLimitMultiplier(multiplier: Int) = requestChange(QuickPayChange.WatchDailyLimitMultiplier(multiplier)) - - fun onAuthorized(authorization: QuickPayAuthorization) { - viewModelScope.launch { - quickPayRepo.applyAuthorizedSettingsChange(authorization) - .onFailure { - Logger.error("Failed to save watch QuickPay change '${authorization.change}'", it, context = TAG) - toastError() - } - } - } - - fun onAuthorizationCancelled() = quickPayRepo.cancelSettingsChange() - - private fun requestChange(change: QuickPayChange) { - val result = quickPayRepo.requestSettingsChange(change) - viewModelScope.launch { - result.await() - .onFailure { - Logger.error("Failed to request watch QuickPay change '$change'", it, context = TAG) - toastError() - } - } - } - - private suspend fun toastError() = ToastEventBus.send( - type = Toast.ToastType.ERROR, - title = context.getString(R.string.common__error), - description = context.getString(R.string.common__error_body), - ) -} - -/** - * [isPhoneQuickPayEnabled] is the phone's own QuickPay, without which the watch's holds nothing. [spentTodayCents] is - * what the paired watch said it spent under QuickPay today, or null without a paired watch. [authorization] is the - * PIN or biometric check a change waits on. - */ -@Immutable -data class WatchQuickPayUiState( - val isEnabled: Boolean = false, - val amount: Int = 5, - val dailyLimitMultiplier: Int = 5, - val isPhoneQuickPayEnabled: Boolean = false, - val spentTodayCents: Long? = null, - val authorization: QuickPayAuthorization? = null, -) diff --git a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheet.kt index 7c2d8d35f4..ee363f03ae 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheet.kt @@ -12,13 +12,10 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale @@ -33,27 +30,19 @@ import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.repeatOnLifecycle -import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.delay import to.bitkit.R -import to.bitkit.models.FIAT_DECIMALS -import to.bitkit.models.formatCurrency import to.bitkit.ui.components.AuthCheckView import to.bitkit.ui.components.BodyM import to.bitkit.ui.components.BodyMSB import to.bitkit.ui.components.BottomSheetPreview -import to.bitkit.ui.components.Caption13Up import to.bitkit.ui.components.Display -import to.bitkit.ui.components.PaymentAuthorizationHost import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SecondaryButton +import to.bitkit.ui.components.SheetIntroIcon import to.bitkit.ui.components.SheetSize -import to.bitkit.ui.components.Slider import to.bitkit.ui.components.Title import to.bitkit.ui.components.VerticalSpacer -import to.bitkit.ui.components.settings.SettingsButtonRow -import to.bitkit.ui.components.settings.SettingsButtonValue -import to.bitkit.ui.components.settings.SettingsSwitchRow import to.bitkit.ui.scaffold.AppAlertDialog import to.bitkit.ui.scaffold.SheetTopBar import to.bitkit.ui.settingsViewModel @@ -63,7 +52,6 @@ import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors import to.bitkit.viewmodels.AppViewModel import to.bitkit.wearlink.KeyLevel -import java.math.BigDecimal import kotlin.time.Duration.Companion.seconds /** How often the sheet looks for a connected watch while it has none to pair. */ @@ -73,7 +61,8 @@ private val REFRESH_INTERVAL = 3.seconds * Everything about the Wear OS watch in one sheet, opened from Settings › General › Watch. It shows the connected * watch with Pair, or what is missing; then the pairing: one code on both screens, the app's PIN or biometric check * when confirming sends the watch this phone's wallet, the transfer, and its end; and for a paired watch its state - * with Unpair and Erase. A phone without a PIN sends no wallet: that pairing ends on a line that says to set one. + * with Unpair, which also erases the watch's wallet, behind a dialog. A phone without a PIN sends no wallet: that + * pairing ends on a line that says to set one. * A pairing under way is cancelled when the sheet closes, unless the wallet is already on its way. With * [pairNodeId], as from the prompt to pair, the sheet opens on a pairing with that watch as if Pair were tapped. */ @@ -82,12 +71,9 @@ fun WatchSheet( app: AppViewModel, pairNodeId: String? = null, viewModel: WatchSheetViewModel = hiltViewModel(), - quickPayViewModel: WatchQuickPayViewModel = hiltViewModel(), ) { val settings = settingsViewModel ?: return val uiState by viewModel.uiState.collectAsStateWithLifecycle() - val quickPay by quickPayViewModel.uiState.collectAsStateWithLifecycle() - val authorization = quickPay.authorization val isWaitingForWatch = uiState.pairing == null && uiState.paired == null LaunchedEffect(viewModel) { viewModel.onSheetOpen(pairNodeId) } @@ -106,35 +92,18 @@ fun WatchSheet( onDispose { viewModel.onSheetClose() } } - // Back leaves the watch's QuickPay for the watch; the PIN check, composed after this, takes Back first. - BackHandler(enabled = uiState.isQuickPayShown, onBack = viewModel::onQuickPayBack) Box { - PaymentAuthorizationHost( - useBiometrics = authorization?.useBiometrics, - pinDescriptionRes = R.string.security__pin_quickpay, - onCancel = quickPayViewModel::onAuthorizationCancelled, - onVerify = { authorization?.let(quickPayViewModel::onAuthorized) }, - ) { - Content( - uiState = uiState, - quickPay = quickPay, - onPairClick = viewModel::onPairClick, - onInstallClick = viewModel::onInstallClick, - onPairClose = viewModel::onPairClose, - onPairConfirm = viewModel::onPairConfirm, - onUnpairClick = viewModel::onUnpairClick, - onEraseClick = viewModel::onEraseClick, - onStopWaitingClick = viewModel::onStopWaitingClick, - onDialogConfirm = viewModel::onDialogConfirm, - onDialogDismiss = viewModel::onDialogDismiss, - onQuickPayClick = viewModel::onQuickPayClick, - onQuickPayBack = viewModel::onQuickPayBack, - onQuickPayToggle = { quickPayViewModel.setEnabled(!quickPay.isEnabled) }, - onQuickPayAmountChange = quickPayViewModel::setAmount, - onQuickPayLimitChange = quickPayViewModel::setDailyLimitMultiplier, - onDismiss = { app.hideSheet() }, - ) - } + Content( + uiState = uiState, + onPairClick = viewModel::onPairClick, + onInstallClick = viewModel::onInstallClick, + onPairClose = viewModel::onPairClose, + onPairConfirm = viewModel::onPairConfirm, + onUnpairClick = viewModel::onUnpairClick, + onStopWaitingClick = viewModel::onStopWaitingClick, + onUnpairConfirm = viewModel::onUnpairConfirm, + onUnpairDismiss = viewModel::onUnpairDismiss, + ) if (uiState.isAuthShown) { AuthCheckView( appViewModel = app, @@ -153,26 +122,17 @@ fun WatchSheet( private fun Content( uiState: WatchSheetUiState, modifier: Modifier = Modifier, - quickPay: WatchQuickPayUiState = WatchQuickPayUiState(), onPairClick: () -> Unit = {}, onInstallClick: () -> Unit = {}, onPairClose: () -> Unit = {}, onPairConfirm: () -> Unit = {}, onUnpairClick: () -> Unit = {}, - onEraseClick: () -> Unit = {}, onStopWaitingClick: () -> Unit = {}, - onDialogConfirm: () -> Unit = {}, - onDialogDismiss: () -> Unit = {}, - onQuickPayClick: () -> Unit = {}, - onQuickPayBack: () -> Unit = {}, - onQuickPayToggle: () -> Unit = {}, - onQuickPayAmountChange: (Int) -> Unit = {}, - onQuickPayLimitChange: (Int) -> Unit = {}, - onDismiss: () -> Unit = {}, + onUnpairConfirm: () -> Unit = {}, + onUnpairDismiss: () -> Unit = {}, ) { val pairing = uiState.pairing val paired = uiState.paired - val isQuickPayShown = uiState.isQuickPayShown && pairing == null Column( modifier = modifier .sheetHeight(SheetSize.LARGE) @@ -183,36 +143,19 @@ private fun Content( ) { SheetTopBar( titleText = stringResource( - when { - isQuickPayShown -> R.string.settings__watch__quickpay - pairing == null -> R.string.settings__watch__nav_title - else -> R.string.settings__watch__pair_title - }, + if (pairing == null) R.string.settings__watch__nav_title else R.string.settings__watch__pair_title, ), - onBack = onQuickPayBack.takeIf { isQuickPayShown }, ) VerticalSpacer(16.dp) when { - isQuickPayShown -> WatchQuickPay( - state = quickPay, - onToggle = onQuickPayToggle, - onAmountChange = onQuickPayAmountChange, - onLimitChange = onQuickPayLimitChange, - ) pairing != null -> Pairing(step = pairing, onClose = onPairClose, onConfirm = onPairConfirm) paired != null -> Paired( watch = paired, - isQuickPayEnabled = quickPay.isEnabled, - onQuickPayClick = onQuickPayClick, onUnpairClick = onUnpairClick, - onEraseClick = onEraseClick, onStopWaitingClick = onStopWaitingClick, - onDismiss = onDismiss, ) else -> Unpaired( uiState = uiState, - isQuickPayEnabled = quickPay.isEnabled, - onQuickPayClick = onQuickPayClick, onPairClick = onPairClick, onInstallClick = onInstallClick, ) @@ -220,21 +163,14 @@ private fun Content( VerticalSpacer(16.dp) } - uiState.dialog?.let { dialog -> - val isErase = dialog == WatchRemoveDialog.Erase + if (uiState.isUnpairDialogShown) { AppAlertDialog( - title = stringResource( - if (isErase) R.string.settings__watch__erase_title else R.string.settings__watch__unpair_title, - ), - text = stringResource( - if (isErase) R.string.settings__watch__erase_text else R.string.settings__watch__unpair_text, - ), - confirmText = stringResource( - if (isErase) R.string.settings__watch__erase_confirm else R.string.settings__watch__unpair, - ), - confirmTextColor = if (isErase) Colors.Red else Colors.Brand, - onConfirm = onDialogConfirm, - onDismiss = onDialogDismiss, + title = stringResource(R.string.settings__watch__unpair_title), + text = stringResource(R.string.settings__watch__unpair_text), + confirmText = stringResource(R.string.settings__watch__unpair), + confirmTextColor = Colors.Red, + onConfirm = onUnpairConfirm, + onDismiss = onUnpairDismiss, modifier = Modifier.testTag("PairedWatchRemoveDialog") ) } @@ -243,8 +179,6 @@ private fun Content( @Composable private fun ColumnScope.Unpaired( uiState: WatchSheetUiState, - isQuickPayEnabled: Boolean, - onQuickPayClick: () -> Unit, onPairClick: () -> Unit, onInstallClick: () -> Unit, ) { @@ -261,9 +195,7 @@ private fun ColumnScope.Unpaired( color = Colors.White64, modifier = Modifier.testTag("PairedWatchStatus") ) - VerticalSpacer(16.dp) - QuickPayRow(isEnabled = isQuickPayEnabled, onClick = onQuickPayClick) - Illustration(R.drawable.phone) + SheetIntroIcon(icon = R.drawable.ic_watch) if (connected != null && !connected.hasApp) { PrimaryButton( text = stringResource(R.string.settings__watch__install_on_watch), @@ -287,12 +219,8 @@ private fun ColumnScope.Unpaired( @Composable private fun ColumnScope.Paired( watch: PairedWatch, - isQuickPayEnabled: Boolean, - onQuickPayClick: () -> Unit, onUnpairClick: () -> Unit, - onEraseClick: () -> Unit, onStopWaitingClick: () -> Unit, - onDismiss: () -> Unit, ) { Title(text = watch.name, modifier = Modifier.testTag("PairedWatchName")) VerticalSpacer(16.dp) @@ -327,13 +255,7 @@ private fun ColumnScope.Paired( if (watch.isRemoving) { VerticalSpacer(16.dp) BodyM( - text = stringResource( - if (watch.isErasing) { - R.string.settings__watch__erase_pending - } else { - R.string.settings__watch__unpair_pending - }, - ), + text = stringResource(R.string.settings__watch__erase_pending), color = Colors.White64, modifier = Modifier.testTag("PairedWatchRemovePending") ) @@ -346,129 +268,15 @@ private fun ColumnScope.Paired( ) return } - VerticalSpacer(16.dp) - QuickPayRow(isEnabled = isQuickPayEnabled, onClick = onQuickPayClick) - Illustration(if (watch.keyLevel == null) R.drawable.shield else R.drawable.shield_check) - Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { - SecondaryButton( - text = stringResource(R.string.settings__watch__unpair), - onClick = onUnpairClick, - fullWidth = false, - modifier = Modifier.weight(1f), - testTag = "PairedWatchUnpair", - ) - PrimaryButton( - text = stringResource(R.string.common__ok), - onClick = onDismiss, - fullWidth = false, - modifier = Modifier - .weight(1f) - .testTag("PairedWatchClose") - ) - } - VerticalSpacer(16.dp) + SheetIntroIcon(icon = R.drawable.ic_watch) SecondaryButton( - text = stringResource(R.string.settings__watch__erase), - onClick = onEraseClick, + text = stringResource(R.string.settings__watch__unpair), + onClick = onUnpairClick, modifier = Modifier.fillMaxWidth(), - testTag = "PairedWatchErase", - ) -} - -@Composable -private fun QuickPayRow( - isEnabled: Boolean, - onClick: () -> Unit, -) { - SettingsButtonRow( - title = stringResource(R.string.settings__watch__quickpay), - value = SettingsButtonValue.StringValue( - stringResource(if (isEnabled) R.string.settings__bg__on else R.string.settings__bg__off), - ), - onClick = onClick, - modifier = Modifier.testTag("PairedWatchQuickPay") + testTag = "PairedWatchUnpair", ) } -/** - * The watch's own QuickPay: the switch, the amount of one payment and the daily limit, with the sliders of the - * phone's QuickPay settings, and what the paired watch spent under QuickPay today. - */ -@Composable -private fun ColumnScope.WatchQuickPay( - state: WatchQuickPayUiState, - onToggle: () -> Unit, - onAmountChange: (Int) -> Unit, - onLimitChange: (Int) -> Unit, -) { - val amountSteps = remember { persistentListOf(1, 5, 10, 20, 50) } - val limitSteps = remember { persistentListOf(1, 3, 5, 10, 50) } - val multiplierFormat = stringResource(R.string.settings__quickpay__settings__multiplier_format) - Column( - modifier = Modifier - .weight(1f) - .verticalScroll(rememberScrollState()) - ) { - SettingsSwitchRow( - title = stringResource(R.string.settings__watch__quickpay), - isChecked = state.isEnabled, - onClick = onToggle, - modifier = Modifier.testTag("PairedWatchQuickPayToggle") - ) - VerticalSpacer(16.dp) - if (!state.isPhoneQuickPayEnabled) { - BodyMSB( - text = stringResource(R.string.settings__watch__quickpay_phone_off), - modifier = Modifier.testTag("PairedWatchQuickPayPhoneOff") - ) - VerticalSpacer(16.dp) - } - BodyM( - text = stringResource(R.string.settings__watch__quickpay_text).replace("{amount}", "${state.amount}"), - color = Colors.White64, - ) - VerticalSpacer(32.dp) - Caption13Up(text = stringResource(R.string.settings__quickpay__settings__label), color = Colors.White64) - VerticalSpacer(16.dp) - Slider( - value = state.amount, - steps = amountSteps, - onValueChange = onAmountChange, - stopTestTag = { "PairedWatchQuickPayAmountStop-${amountSteps[it]}" }, - modifier = Modifier.testTag("PairedWatchQuickPayAmount") - ) - VerticalSpacer(32.dp) - Caption13Up(text = stringResource(R.string.settings__quickpay__settings__daily_label), color = Colors.White64) - VerticalSpacer(16.dp) - BodyM( - text = stringResource(R.string.settings__watch__quickpay_daily_text) - .replace("{limit}", "${state.amount * state.dailyLimitMultiplier}"), - color = Colors.White64, - ) - VerticalSpacer(16.dp) - Slider( - value = state.dailyLimitMultiplier, - steps = limitSteps, - onValueChange = onLimitChange, - formatLabel = { multiplierFormat.replace("{multiplier}", it.toString()) }, - stopTestTag = { "PairedWatchQuickPayLimitStop-${limitSteps[it]}" }, - modifier = Modifier.testTag("PairedWatchQuickPayLimit") - ) - state.spentTodayCents?.let { cents -> - VerticalSpacer(32.dp) - BodyM( - text = stringResource(R.string.settings__watch__quickpay_spent).replace("{spent}", dollars(cents)), - color = Colors.White64, - modifier = Modifier.testTag("PairedWatchSpentToday") - ) - } - } -} - -private fun dollars(cents: Long): String = BigDecimal.valueOf(cents, FIAT_DECIMALS).let { - it.formatCurrency() ?: it.toPlainString() -} - @Composable private fun ColumnScope.Pairing( step: WatchPairStep, @@ -478,7 +286,7 @@ private fun ColumnScope.Pairing( when (step) { WatchPairStep.Connecting -> { Message(R.string.settings__watch__pair_connecting, "PairedWatchPairConnecting") - Illustration(R.drawable.phone) + SheetIntroIcon(icon = R.drawable.ic_watch) SecondaryButton( text = stringResource(R.string.common__cancel), onClick = onClose, @@ -658,7 +466,6 @@ private fun PreviewPaired() { keyLevel = KeyLevel.StrongBox, isSettingsUpToDate = false, isRemoving = false, - isErasing = false, ), ), modifier = Modifier.sheetHeight(), @@ -666,22 +473,3 @@ private fun PreviewPaired() { } } } - -@Preview(showSystemUi = true) -@Composable -private fun PreviewQuickPay() { - AppThemeSurface { - BottomSheetPreview { - Content( - uiState = WatchSheetUiState(isLoading = false, isQuickPayShown = true), - quickPay = WatchQuickPayUiState( - isEnabled = true, - amount = 5, - dailyLimitMultiplier = 3, - spentTodayCents = 125, - ), - modifier = Modifier.sheetHeight(), - ) - } - } -} diff --git a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheetViewModel.kt b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheetViewModel.kt index 8c5b91847e..e2e12404df 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheetViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheetViewModel.kt @@ -15,9 +15,11 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import to.bitkit.R +import to.bitkit.models.Toast import to.bitkit.repositories.WatchLinkError import to.bitkit.repositories.WatchLinkRepo import to.bitkit.repositories.WatchPairingStatus +import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.wearlink.AbortReason import to.bitkit.wearlink.AttestationFailure import to.bitkit.wearlink.AttestationVerdict @@ -26,7 +28,6 @@ import to.bitkit.wearlink.LinkError import to.bitkit.wearlink.LinkRecord import to.bitkit.wearlink.PairingMode import to.bitkit.wearlink.PairingState -import to.bitkit.wearlink.Removal import to.bitkit.wearlink.StoreFailure import javax.inject.Inject @@ -60,7 +61,7 @@ class WatchSheetViewModel @Inject constructor( it.copy( paired = record?.toPairedWatch(), pairingId = record?.pairingId, - dialog = it.dialog.takeIf { isSameWatch }, + isUnpairDialogShown = it.isUnpairDialogShown && isSameWatch, ) } } @@ -91,7 +92,7 @@ class WatchSheetViewModel @Inject constructor( } isTransferLeft = false _uiState.update { - it.copy(isLoading = true, connected = null, pairing = shown, isAuthShown = false, isQuickPayShown = false) + it.copy(isLoading = true, connected = null, pairing = shown, isAuthShown = false) } lookForWatch() if (!isPairRequested || shown != null) return @@ -125,7 +126,7 @@ class WatchSheetViewModel @Inject constructor( private fun startPairing(nodeId: String?) { watchLinkRepo.cancelPairing() - _uiState.update { it.copy(pairing = WatchPairStep.Connecting, isAuthShown = false, isQuickPayShown = false) } + _uiState.update { it.copy(pairing = WatchPairStep.Connecting, isAuthShown = false) } watchLinkRepo.startPairing(nodeId) } @@ -170,14 +171,9 @@ class WatchSheetViewModel @Inject constructor( pairRequestJob?.cancel() isTransferLeft = _uiState.value.pairing == WatchPairStep.Sending if (!isTransferLeft) watchLinkRepo.cancelPairing() - _uiState.update { it.copy(pairing = null, isAuthShown = false, dialog = null, isQuickPayShown = false) } + _uiState.update { it.copy(pairing = null, isAuthShown = false, isUnpairDialogShown = false) } } - /** Shows the watch's own QuickPay limits in the sheet. */ - fun onQuickPayClick() = _uiState.update { it.copy(isQuickPayShown = true) } - - fun onQuickPayBack() = _uiState.update { it.copy(isQuickPayShown = false) } - /** Opens Bitkit's Play listing on the connected watch that has no Bitkit, and says whether it opened. */ fun onInstallClick() { val watch = _uiState.value.connected?.takeIf { !it.hasApp } ?: return @@ -187,16 +183,24 @@ class WatchSheetViewModel @Inject constructor( } } - fun onUnpairClick() = _uiState.update { it.copy(dialog = WatchRemoveDialog.Unpair) } + /** Asks first: Unpair also erases the watch's wallet. */ + fun onUnpairClick() = _uiState.update { it.copy(isUnpairDialogShown = true) } - fun onEraseClick() = _uiState.update { it.copy(dialog = WatchRemoveDialog.Erase) } + fun onUnpairDismiss() = _uiState.update { it.copy(isUnpairDialogShown = false) } - fun onDialogDismiss() = _uiState.update { it.copy(dialog = null) } - - fun onDialogConfirm() { - val dialog = _uiState.value.dialog ?: return - _uiState.update { it.copy(dialog = null) } - viewModelScope.launch { watchLinkRepo.remove(isErase = dialog == WatchRemoveDialog.Erase) } + /** Unpairs the watch and erases its wallet, or says it could not ask the watch to. */ + fun onUnpairConfirm() { + if (!_uiState.value.isUnpairDialogShown) return + _uiState.update { it.copy(isUnpairDialogShown = false) } + viewModelScope.launch { + watchLinkRepo.unpair().onFailure { + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.common__error), + description = context.getString(R.string.common__error_body), + ) + } + } } /** Drops a watch whose removal was never acknowledged. */ @@ -209,7 +213,6 @@ class WatchSheetViewModel @Inject constructor( keyLevel = keyLevel, isSettingsUpToDate = isSettingsUpToDate, isRemoving = removal != null, - isErasing = removal == Removal.Erase, ) private fun WatchSheetUiState.withStep(step: WatchPairStep) = @@ -261,7 +264,7 @@ class WatchSheetViewModel @Inject constructor( /** * [pairing] is the step of the pairing the user started from the sheet, or null while none shows. [isAuthShown] * while the app's PIN or biometric check covers the code, before a confirmation that sends the wallet. - * [isQuickPayShown] while the sheet shows the watch's own QuickPay limits instead of the watch. + * [isUnpairDialogShown] while Unpair asks first, since it also erases the watch's wallet. */ @Immutable data class WatchSheetUiState( @@ -271,8 +274,7 @@ data class WatchSheetUiState( val pairingId: String? = null, val pairing: WatchPairStep? = null, val isAuthShown: Boolean = false, - val dialog: WatchRemoveDialog? = null, - val isQuickPayShown: Boolean = false, + val isUnpairDialogShown: Boolean = false, ) /** A watch connected to this phone, with whether it has Bitkit and whether it is reached directly. */ @@ -288,11 +290,8 @@ data class PairedWatch( val keyLevel: KeyLevel?, val isSettingsUpToDate: Boolean, val isRemoving: Boolean, - val isErasing: Boolean, ) -enum class WatchRemoveDialog { Unpair, Erase } - sealed interface WatchPairStep { /** Waiting for the watch to answer. */ data object Connecting : WatchPairStep diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 099ad2db9d..c1e9d09c55 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -889,11 +889,7 @@ فشل الإرسال Bitkit من تصميم Synonym Software, S.A. DE C.V. ©2025. جميع الحقوق محفوظة. الدعم - إلغاء الإقران ومسح الساعة - مسح في انتظار أن تمسح الساعة محفظتها. الساعة التي لا تعاود الاتصال أبدًا تحتفظ بها. - ستنسى الساعة هذا الهاتف وتحذف محفظتها عند اتصالها في المرة القادمة. الساعة التي لا تعاود الاتصال أبدًا تحتفظ بالمحفظة، لذا انقل أموالك إلى محفظة جديدة إذا فُقدت الساعة. - مسح الساعة؟ تم إلغاء الإقران. تم إلغاء الإقران من الساعة. الساعة تحتوي على محفظة مختلفة. @@ -932,18 +928,12 @@ لا توجد محفظة على هذه الساعة. الإقران يرسل إليها عبارة الاسترداد الخاصة بك، فتصبح حاملة لمحفظتك الكاملة. إقران الساعة أكّد الرمز على ساعتك. - QuickPay على الساعة - تدفع ساعتك بهذه الطريقة حتى ${limit} يوميًا. ومع هذا الهاتف تبقى ضمن حد QuickPay اليومي لهذا الهاتف. - QuickPay متوقف على هذا الهاتف، لذا فهو متوقف على ساعتك أيضًا. - المُنفق اليوم عبر QuickPay على ساعتك: ${spent} - المدفوعات حتى ${amount} على ساعتك لا تحتاج إلى الضغط المطوّل للدفع. لا يوجد رمز PIN على ساعتك، لذا اجعل هذا المبلغ منخفضًا. {name} جاهزة للإقران. الإعدادات ليست على الساعة بعد. إعدادات الساعة محدّثة. إيقاف الانتظار إلغاء الإقران - في انتظار إلغاء إقران الساعة. - ستنسى الساعة هذا الهاتف. تبقى المحفظة على الساعة. + ستنسى الساعة هذا الهاتف وتحذف محفظتها عند اتصالها في المرة القادمة. الساعة التي لا تعاود الاتصال أبدًا تحتفظ بالمحفظة، لذا انقل أموالك إلى محفظة جديدة إذا فُقدت الساعة. إلغاء إقران الساعة؟ الأدوات الأدوات @@ -1243,11 +1233,6 @@ انتهاء صلاحية الفاتورة الحد الأقصى القابل للإنفاق أقل قليلاً بسبب الرصيد الاحتياطي المطلوب. الرصيد الاحتياطي - ادفع على الساعة - ساعتك مشغولة بدفعة أخرى. - تعذّر على ساعتك استلام هذه الدفعة. - أُرسل إلى ساعتك. اضغط مطولًا هناك للدفع. - تعذّر الوصول إلى ساعتك. ليس لدى جهة الاتصال هذه أي طريقة دفع يمكن لـ Bitkit استخدامها الآن. لا يمكن الدفع لجهة الاتصال هذه لا يزال سحب سابق من رصيد الإنفاق قيد التسوية. حاول مرة أخرى بعد اكتماله. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 0c2467dbbd..b3f27468eb 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -910,11 +910,7 @@ Fallo en el envío Bitkit fue creado por Synonym Software, S.A. DE C.V. ©2025. Todos los derechos reservados. Soporte - Desvincular y borrar el reloj - Borrar Esperando a que el reloj borre la billetera. Un reloj que no vuelva a conectarse la conservará. - El reloj olvidará este teléfono y eliminará la billetera la próxima vez que se conecte. Un reloj que no vuelva a conectarse conservará la billetera, así que mueva sus fondos a una billetera nueva si pierde el reloj. - ¿Borrar el reloj? Vinculación cancelada. La vinculación se canceló en el reloj. El reloj contiene una billetera distinta. @@ -953,18 +949,12 @@ Este reloj no tiene billetera. Al vincularlo se le envía su frase de recuperación, por lo que contendrá su billetera completa. Vincular reloj Confirme el código en su reloj. - QuickPay en el reloj - Tu reloj paga así hasta ${limit} al día. Junto con este teléfono, se mantiene dentro del límite diario de QuickPay de este teléfono. - QuickPay está desactivado en este teléfono, así que también en tu reloj. - Gastado hoy con QuickPay en tu reloj: ${spent} - Los pagos de hasta ${amount} en tu reloj no requieren mantener presionado para pagar. Tu reloj no tiene PIN, así que mantén este monto bajo. {name} está listo para vincularse. Los ajustes aún no están en el reloj. Ajustes del reloj actualizados. Dejar de esperar Desvincular - Esperando a que el reloj se desvincule. - El reloj olvidará este teléfono. La billetera permanece en el reloj. + El reloj olvidará este teléfono y eliminará la billetera la próxima vez que se conecte. Un reloj que no vuelva a conectarse conservará la billetera, así que mueva sus fondos a una billetera nueva si pierde el reloj. ¿Desvincular el reloj? Widgets Widgets @@ -1274,11 +1264,6 @@ Expiración de la factura La cantidad máxima que se puede gastar es un poco más baja debido al saldo de reserva exigido. Saldo de reserva - Pagar en el reloj - Tu reloj está ocupado con otro pago. - Tu reloj no pudo recibir este pago. - Enviado a tu reloj. Mantén presionado allí para pagar. - Tu reloj no está disponible. Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. No se puede pagar a este contacto Un retiro anterior de tu saldo para gastos aún se está liquidando. Inténtalo de nuevo cuando termine. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 376f1f2f8a..c4c1debeb5 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -904,11 +904,7 @@ Error en enviar Bitkit ha estat creat per Synonym Software, S.A. DE C.V. ©2025. Tots els drets reservats. Suport - Desvincular i esborrar el rellotge - Esborrar S\'està esperant que el rellotge esborri la seva cartera. Un rellotge que no es torni a connectar la conservarà. - El rellotge oblidarà aquest telèfon i eliminarà la seva cartera la pròxima vegada que es connecti. Un rellotge que no es torni a connectar conservarà la cartera, així que mou els teus fons a una cartera nova si perds el rellotge. - Esborrar el rellotge? Vinculació cancel·lada. La vinculació s\'ha cancel·lat al rellotge. El rellotge conté una cartera diferent. @@ -947,18 +943,12 @@ Aquest rellotge no té cartera. En vincular-lo se li envia la teva frase de recuperació, de manera que contindrà la teva cartera completa. Vincular rellotge Confirma el codi al teu rellotge. - QuickPay al rellotge - El rellotge paga així fins a ${limit} al dia. Juntament amb aquest telèfon, es manté dins del límit diari de QuickPay d\'aquest telèfon. - QuickPay està desactivat en aquest telèfon, així que també al rellotge. - Gastat avui amb QuickPay al rellotge: ${spent} - Els pagaments de fins a ${amount} al rellotge no cal mantenir-los premuts per pagar. El rellotge no té PIN, així que mantingues aquest import baix. {name} està a punt per vincular. La configuració encara no és al rellotge. Configuració del rellotge actualitzada. Deixar d\'esperar Desvincular - S\'està esperant que el rellotge es desvinculi. - El rellotge oblidarà aquest telèfon. La cartera es queda al rellotge. + El rellotge oblidarà aquest telèfon i eliminarà la seva cartera la pròxima vegada que es connecti. Un rellotge que no es torni a connectar conservarà la cartera, així que mou els teus fons a una cartera nova si perds el rellotge. Desvincular el rellotge? Ginys Ginys @@ -1268,11 +1258,6 @@ Caducitat de la factura L\'import màxim gastable és una mica inferior a causa d\'un saldo de reserva requerit. Saldo de reserva - Paga al rellotge - El rellotge està ocupat amb un altre pagament. - El rellotge no ha pogut rebre aquest pagament. - Enviat al rellotge. Mantén premut allà per pagar. - El rellotge no és accessible. Aquest contacte no té cap mètode de pagament que Bitkit pugui fer servir ara. No es pot pagar aquest contacte Una retirada anterior del teu saldo de despesa encara s\'està liquidant. Torna-ho a provar quan es completi. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 5e9af241bc..7b521ff44b 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -909,11 +909,7 @@ Odeslání se nezdařilo Bitkit vytvořila společnost Synonym Software, S.A. DE C.V. ©2025. Všechna práva vyhrazena. Podpora - Zrušit spárování a vymazat hodinky - Vymazat Čeká se, až hodinky vymažou svou peněženku. Hodinky, které se už nepřipojí, si ji ponechají. - Hodinky zapomenou tento telefon a při příštím připojení smažou svou peněženku. Hodinky, které se už nepřipojí, si peněženku ponechají, proto při ztrátě hodinek přesuňte prostředky do nové peněženky. - Vymazat hodinky? Párování zrušeno. Párování bylo zrušeno na hodinkách. Hodinky obsahují jinou peněženku. @@ -952,18 +948,12 @@ Tyto hodinky nemají peněženku. Spárováním se do nich odešle vaše fráze pro obnovení, takže budou obsahovat vaši celou peněženku. Spárovat hodinky Potvrďte kód na hodinkách. - QuickPay na hodinkách - Hodinky takto zaplatí až ${limit} denně. Spolu s tímto telefonem zůstávají v denním limitu QuickPay tohoto telefonu. - QuickPay je na tomto telefonu vypnutý, takže i na hodinkách. - Dnes utraceno přes QuickPay na hodinkách: ${spent} - Platby do ${amount} na hodinkách nevyžadují podržení. Hodinky nemají PIN, proto nechte částku nízkou. Zařízení {name} je připraveno ke spárování. Nastavení zatím není v hodinkách. Nastavení hodinek je aktuální. Přestat čekat Zrušit spárování - Čeká se na zrušení spárování hodinek. - Hodinky zapomenou tento telefon. Peněženka v hodinkách zůstane. + Hodinky zapomenou tento telefon a při příštím připojení smažou svou peněženku. Hodinky, které se už nepřipojí, si peněženku ponechají, proto při ztrátě hodinek přesuňte prostředky do nové peněženky. Zrušit spárování hodinek? Widgety Widgety @@ -1272,11 +1262,6 @@ Expirace faktury Maximální částka, kterou lze utratit, je o něco nižší kvůli požadovanému zůstatku rezervy. Zůstatek rezervy - Zaplatit na hodinkách - Hodinky zpracovávají jinou platbu. - Hodinky tuto platbu nemohly přijmout. - Odesláno do hodinek. Podržením na nich zaplatíte. - Hodinky nejsou dostupné. Tento kontakt nemá žádnou platební metodu, kterou by Bitkit mohl nyní použít. Tomuto kontaktu nelze zaplatit Dřívější výběr z vašeho zůstatku pro výdaje se stále vypořádává. Zkuste to znovu, až se dokončí. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 0d27bc288f..dcdb9b5750 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -746,11 +746,7 @@ Früher verwendete Tags Oberfläche Zahlungen - Entkoppeln und Uhr löschen - Löschen Warte darauf, dass die Uhr ihr Wallet löscht. Eine Uhr, die sich nie wieder verbindet, behält es. - Die Uhr vergisst dieses Telefon und löscht ihr Wallet, sobald sie sich das nächste Mal verbindet. Eine Uhr, die sich nie wieder verbindet, behält das Wallet. Verschiebe dein Guthaben daher in ein neues Wallet, falls die Uhr verloren geht. - Uhr löschen? Kopplung abgebrochen. Die Kopplung wurde auf der Uhr abgebrochen. Auf der Uhr befindet sich ein anderes Wallet. @@ -789,18 +785,12 @@ Diese Uhr hat kein Wallet. Beim Koppeln wird deine Wiederherstellungsphrase an sie gesendet, sodass sie dein vollständiges Wallet enthält. Uhr koppeln Bestätige den Code auf deiner Uhr. - QuickPay auf der Uhr - Deine Uhr zahlt so bis zu ${limit} pro Tag. Zusammen mit diesem Telefon bleibt sie im täglichen QuickPay-Limit dieses Telefons. - QuickPay ist auf diesem Telefon aus, also auch auf deiner Uhr. - Heute mit QuickPay auf deiner Uhr ausgegeben: ${spent} - Zahlungen bis ${amount} auf deiner Uhr kommen ohne Gedrückthalten aus. Deine Uhr hat keine PIN, halte den Betrag also niedrig. {name} ist bereit zum Koppeln. Einstellungen noch nicht auf der Uhr. Einstellungen der Uhr sind aktuell. Nicht mehr warten Entkoppeln - Warte darauf, dass die Uhr entkoppelt wird. - Die Uhr vergisst dieses Telefon. Das Wallet bleibt auf der Uhr. + Die Uhr vergisst dieses Telefon und löscht ihr Wallet, sobald sie sich das nächste Mal verbindet. Eine Uhr, die sich nie wieder verbindet, behält das Wallet. Verschiebe dein Guthaben daher in ein neues Wallet, falls die Uhr verloren geht. Uhr entkoppeln? Widgets Widgets @@ -1107,11 +1097,6 @@ Senden Empfangen Bitcoin senden - Auf der Uhr zahlen - Deine Uhr ist mit einer anderen Zahlung beschäftigt. - Deine Uhr konnte diese Zahlung nicht annehmen. - An deine Uhr gesendet. Halte dort gedrückt, um zu zahlen. - Deine Uhr ist nicht erreichbar. Dieser Kontakt hat derzeit keine Zahlungsmethode, die Bitkit nutzen kann. Zahlung an diesen Kontakt nicht möglich Eine frühere Auszahlung von deinem Ausgabenguthaben wird noch abgewickelt. Versuche es erneut, sobald sie abgeschlossen ist. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 3f684bc1c4..224473b1a2 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -889,11 +889,7 @@ Αποτυχία αποστολής Το Bitkit δημιουργήθηκε από τη Synonym Software, S.A. DE C.V. ©2025. Με επιφύλαξη παντός δικαιώματος. Υποστήριξη - Αποσύζευξη και διαγραφή ρολογιού - Διαγραφή Αναμονή για τη διαγραφή του πορτοφολιού από το ρολόι. Ένα ρολόι που δεν συνδεθεί ποτέ ξανά το διατηρεί. - Το ρολόι θα ξεχάσει αυτό το τηλέφωνο και θα διαγράψει το πορτοφόλι του την επόμενη φορά που θα συνδεθεί. Ένα ρολόι που δεν συνδεθεί ποτέ ξανά διατηρεί το πορτοφόλι, γι\' αυτό μετάφερε τα χρήματά σου σε νέο πορτοφόλι αν το ρολόι χαθεί. - Διαγραφή ρολογιού; Η σύζευξη ακυρώθηκε. Η σύζευξη ακυρώθηκε στο ρολόι. Το ρολόι περιέχει διαφορετικό πορτοφόλι. @@ -932,18 +928,12 @@ Αυτό το ρολόι δεν έχει πορτοφόλι. Η σύζευξη του στέλνει τη φράση ανάκτησής σου, οπότε θα περιέχει ολόκληρο το πορτοφόλι σου. Σύζευξη ρολογιού Επιβεβαίωσε τον κωδικό στο ρολόι σου. - QuickPay στο ρολόι - Το ρολόι σας πληρώνει έτσι έως ${limit} την ημέρα. Μαζί με αυτό το τηλέφωνο μένει εντός του ημερήσιου ορίου QuickPay αυτού του τηλεφώνου. - Το QuickPay είναι απενεργοποιημένο σε αυτό το τηλέφωνο, άρα και στο ρολόι σας. - Δαπανήθηκαν σήμερα με QuickPay στο ρολόι σας: ${spent} - Οι πληρωμές έως ${amount} στο ρολόι σας δεν χρειάζονται παρατεταμένο πάτημα. Το ρολόι σας δεν έχει PIN, οπότε κρατήστε το ποσό χαμηλό. Το {name} είναι έτοιμο για σύζευξη. Οι ρυθμίσεις δεν είναι ακόμη στο ρολόι. Οι ρυθμίσεις του ρολογιού είναι ενημερωμένες. Διακοπή αναμονής Αποσύζευξη - Αναμονή για την αποσύζευξη του ρολογιού. - Το ρολόι θα ξεχάσει αυτό το τηλέφωνο. Το πορτοφόλι παραμένει στο ρολόι. + Το ρολόι θα ξεχάσει αυτό το τηλέφωνο και θα διαγράψει το πορτοφόλι του την επόμενη φορά που θα συνδεθεί. Ένα ρολόι που δεν συνδεθεί ποτέ ξανά διατηρεί το πορτοφόλι, γι\' αυτό μετάφερε τα χρήματά σου σε νέο πορτοφόλι αν το ρολόι χαθεί. Αποσύζευξη ρολογιού; Widgets Widgets @@ -1248,11 +1238,6 @@ Λήξη τιμολογίου Το μέγιστο δαπανήσιμο ποσό είναι λίγο χαμηλότερο λόγω απαιτούμενου αποθεματικού υπολοίπου. Αποθεματικό υπόλοιπο - Πληρωμή στο ρολόι - Το ρολόι σας είναι απασχολημένο με άλλη πληρωμή. - Το ρολόι σας δεν μπόρεσε να δεχτεί αυτή την πληρωμή. - Στάλθηκε στο ρολόι σας. Πατήστε παρατεταμένα εκεί για πληρωμή. - Το ρολόι σας δεν είναι προσβάσιμο. Αυτή η επαφή δεν έχει τρόπο πληρωμής που μπορεί να χρησιμοποιήσει το Bitkit αυτή τη στιγμή. Δεν είναι δυνατή η πληρωμή αυτής της επαφής Μια προηγούμενη ανάληψη από το υπόλοιπο δαπανών σου διακανονίζεται ακόμη. Δοκίμασε ξανά μόλις ολοκληρωθεί. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 569abefc79..8751aead44 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -907,11 +907,7 @@ Error al enviar Bitkit fue creado por Synonym Software, S.A. DE C.V. ©2025. Todos los derechos reservados. Soporte - Desvincular y borrar el reloj - Borrar Esperando a que el reloj borre la cartera. Un reloj que no vuelva a conectarse la conservará. - El reloj olvidará este teléfono y eliminará la cartera la próxima vez que se conecte. Un reloj que no vuelva a conectarse conservará la cartera, así que mueve tus fondos a una cartera nueva si pierdes el reloj. - ¿Borrar el reloj? Vinculación cancelada. La vinculación se canceló en el reloj. El reloj contiene una cartera distinta. @@ -950,18 +946,12 @@ Este reloj no tiene cartera. Al vincularlo se le envía tu frase de recuperación, por lo que contendrá tu cartera completa. Vincular reloj Confirma el código en tu reloj. - QuickPay en el reloj - Tu reloj paga así hasta ${limit} al día. Junto con este teléfono, se mantiene dentro del límite diario de QuickPay de este teléfono. - QuickPay está desactivado en este teléfono, así que también en tu reloj. - Gastado hoy con QuickPay en tu reloj: ${spent} - Los pagos de hasta ${amount} en tu reloj no requieren mantener pulsado para pagar. Tu reloj no tiene PIN, así que mantén este importe bajo. {name} está listo para vincularse. Los ajustes aún no están en el reloj. Ajustes del reloj actualizados. Dejar de esperar Desvincular - Esperando a que el reloj se desvincule. - El reloj olvidará este teléfono. La cartera permanece en el reloj. + El reloj olvidará este teléfono y eliminará la cartera la próxima vez que se conecte. Un reloj que no vuelva a conectarse conservará la cartera, así que mueve tus fondos a una cartera nueva si pierdes el reloj. ¿Desvincular el reloj? Widgets Widgets @@ -1269,11 +1259,6 @@ Expiración de la factura La cantidad máxima gastable es un poco menor debido a un saldo de reserva requerido. Saldo de reserva - Pagar en el reloj - Tu reloj está ocupado con otro pago. - Tu reloj no ha podido recibir este pago. - Enviado a tu reloj. Mantén pulsado allí para pagar. - Tu reloj no está disponible. Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. No se puede pagar a este contacto Un retiro anterior de tu saldo de gasto aún se está liquidando. Inténtalo de nuevo cuando termine. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 004e097c11..1c48fbc718 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -743,11 +743,7 @@ Etiquetas utilizadas anteriormente Interfaz Pagos - Desvincular y borrar el reloj - Borrar Esperando a que el reloj borre la cartera. Un reloj que no vuelva a conectarse la conservará. - El reloj olvidará este teléfono y eliminará la cartera la próxima vez que se conecte. Un reloj que no vuelva a conectarse conservará la cartera, así que mueva sus fondos a una cartera nueva si pierde el reloj. - ¿Borrar el reloj? Vinculación cancelada. La vinculación se canceló en el reloj. El reloj contiene una cartera distinta. @@ -786,18 +782,12 @@ Este reloj no tiene cartera. Al vincularlo se le envía su frase de recuperación, por lo que contendrá su cartera completa. Vincular reloj Confirme el código en su reloj. - QuickPay en el reloj - Tu reloj paga así hasta ${limit} al día. Junto con este teléfono, se mantiene dentro del límite diario de QuickPay de este teléfono. - QuickPay está desactivado en este teléfono, así que también en tu reloj. - Gastado hoy con QuickPay en tu reloj: ${spent} - Los pagos de hasta ${amount} en tu reloj no requieren mantener pulsado para pagar. Tu reloj no tiene PIN, así que mantén este importe bajo. {name} está listo para vincularse. Los ajustes aún no están en el reloj. Ajustes del reloj actualizados. Dejar de esperar Desvincular - Esperando a que el reloj se desvincule. - El reloj olvidará este teléfono. La cartera permanece en el reloj. + El reloj olvidará este teléfono y eliminará la cartera la próxima vez que se conecte. Un reloj que no vuelva a conectarse conservará la cartera, así que mueva sus fondos a una cartera nueva si pierde el reloj. ¿Desvincular el reloj? Widgets Widgets @@ -1105,11 +1095,6 @@ Recibir Transferencia Entrante: Enviar Bitcoin - Pagar en el reloj - Tu reloj está ocupado con otro pago. - Tu reloj no ha podido recibir este pago. - Enviado a tu reloj. Mantén pulsado allí para pagar. - Tu reloj no está disponible. Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. No se puede pagar a este contacto Un retiro anterior de tu saldo de gasto aún se está liquidando. Inténtalo de nuevo cuando termine. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 4bb96d9303..dda38c0381 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -746,11 +746,7 @@ Étiquettes précédemment utilisées Interface Paiements - Dissocier et effacer la montre - Effacer En attente de l\'effacement du portefeuille par la montre. Une montre qui ne se reconnecte jamais le conserve. - La montre oubliera ce téléphone et supprimera son portefeuille à sa prochaine connexion. Une montre qui ne se reconnecte jamais conserve le portefeuille : transférez donc vos fonds vers un nouveau portefeuille si la montre est perdue. - Effacer la montre ? Association annulée. L\'association a été annulée sur la montre. La montre contient un autre portefeuille. @@ -789,18 +785,12 @@ Cette montre n\'a pas de portefeuille. L\'association lui envoie votre phrase de récupération : elle contiendra donc votre portefeuille complet. Associer la montre Confirmez le code sur votre montre. - QuickPay sur la montre - Votre montre paie ainsi jusqu\'à ${limit} par jour. Avec ce téléphone, elle reste dans la limite QuickPay quotidienne de ce téléphone. - QuickPay est désactivé sur ce téléphone, donc aussi sur votre montre. - Dépensé avec QuickPay sur votre montre aujourd\'hui : ${spent} - Les paiements jusqu\'à ${amount} sur votre montre se passent du maintien pour payer. Votre montre n\'a pas de PIN : gardez ce montant bas. Vous pouvez associer {name}. Paramètres pas encore sur la montre. Paramètres de la montre à jour. Ne plus attendre Dissocier - En attente de la dissociation de la montre. - La montre oubliera ce téléphone. Le portefeuille reste sur la montre. + La montre oubliera ce téléphone et supprimera son portefeuille à sa prochaine connexion. Une montre qui ne se reconnecte jamais conserve le portefeuille : transférez donc vos fonds vers un nouveau portefeuille si la montre est perdue. Dissocier la montre ? Widgets Widgets @@ -1108,11 +1098,6 @@ Envoyer Recevoir Envoyer des bitcoins - Payer sur la montre - Votre montre traite un autre paiement. - Votre montre n\'a pas pu prendre ce paiement. - Envoyé à votre montre. Maintenez pour payer sur la montre. - Votre montre est injoignable. Ce contact n\'a aucun moyen de paiement que Bitkit peut utiliser pour le moment. Impossible de payer ce contact Un retrait précédent de votre solde dépenses est encore en cours de règlement. Réessayez une fois terminé. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 3114685e44..4bae36016b 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -906,11 +906,7 @@ Impossibile inviare Bitkit è stato realizzato da Synonym Software, S.A. DE C.V. ©2025. Tutti i diritti riservati. Supporto - Dissocia e Cancella Orologio - Cancella In attesa che l\'orologio cancelli il suo wallet. Un orologio che non si riconnette mai lo conserva. - L\'orologio dimenticherà questo telefono ed eliminerà il suo wallet alla prossima connessione. Un orologio che non si riconnette mai conserva il wallet, quindi sposta i tuoi fondi su un nuovo wallet se l\'orologio viene smarrito. - Cancellare l\'Orologio? Associazione annullata. L\'associazione è stata annullata sull\'orologio. L\'orologio contiene un wallet diverso. @@ -949,18 +945,12 @@ Questo orologio non ha un wallet. L\'associazione gli invia la tua frase di ripristino, quindi conterrà il tuo wallet completo. Associa Orologio Conferma il codice sul tuo orologio. - QuickPay sull\'orologio - L\'orologio paga così fino a ${limit} al giorno. Insieme a questo telefono resta entro il limite giornaliero QuickPay di questo telefono. - QuickPay è disattivato su questo telefono, quindi anche sull\'orologio. - Speso oggi con QuickPay sull\'orologio: ${spent} - I pagamenti fino a ${amount} sull\'orologio non richiedono di tenere premuto per pagare. L\'orologio non ha un PIN, quindi tieni basso questo importo. {name} è pronto per l\'associazione. Impostazioni non ancora sull\'orologio. Impostazioni dell\'orologio aggiornate. Smetti di Attendere Dissocia - In attesa che l\'orologio venga dissociato. - L\'orologio dimenticherà questo telefono. Il wallet resta sull\'orologio. + L\'orologio dimenticherà questo telefono ed eliminerà il suo wallet alla prossima connessione. Un orologio che non si riconnette mai conserva il wallet, quindi sposta i tuoi fondi su un nuovo wallet se l\'orologio viene smarrito. Dissociare l\'Orologio? Widget Widget @@ -1270,11 +1260,6 @@ Scadenza invoice L\'importo massimo spendibile e\' leggermente inferiore a causa di un saldo di riserva richiesto. Saldo di Riserva - Paga sull\'orologio - L\'orologio è impegnato con un altro pagamento. - L\'orologio non ha potuto accettare questo pagamento. - Inviato all\'orologio. Tieni premuto lì per pagare. - L\'orologio non è raggiungibile. Questo contatto non ha alcun metodo di pagamento che Bitkit possa usare ora. Impossibile pagare questo contatto Un precedente prelievo dal tuo saldo di spesa è ancora in fase di regolamento. Riprova al termine. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 5bb726f5ec..8d4cfd9b22 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -904,11 +904,7 @@ Verzenden mislukt Bitkit is gemaakt door Synonym Software, S.A. DE C.V. ©2025. Alle rechten voorbehouden. Ondersteuning - Ontkoppelen en horloge wissen - Wissen Wachten tot het horloge zijn wallet wist. Een horloge dat nooit meer verbinding maakt, behoudt de wallet. - Het horloge vergeet deze telefoon en verwijdert zijn wallet zodra het weer verbinding maakt. Een horloge dat nooit meer verbinding maakt, behoudt de wallet. Verplaats je geld dus naar een nieuwe wallet als je het horloge kwijt bent. - Horloge wissen? Koppelen geannuleerd. Het koppelen is op het horloge geannuleerd. Het horloge bevat een andere wallet. @@ -947,18 +943,12 @@ Dit horloge heeft geen wallet. Bij het koppelen wordt je herstelzin ernaartoe gestuurd, zodat het je volledige wallet bevat. Horloge koppelen Bevestig de code op je horloge. - QuickPay op horloge - Je horloge betaalt zo tot ${limit} per dag. Samen met deze telefoon blijft het binnen de dagelijkse QuickPay-limiet van deze telefoon. - QuickPay staat uit op deze telefoon, dus ook op je horloge. - Vandaag met QuickPay op je horloge uitgegeven: ${spent} - Betalingen tot ${amount} op je horloge slaan het ingedrukt houden over. Je horloge heeft geen pincode, dus houd dit laag. {name} is klaar om te koppelen. Instellingen nog niet op het horloge. Horloge-instellingen zijn up-to-date. Stoppen met wachten Ontkoppelen - Wachten tot het horloge is ontkoppeld. - Het horloge vergeet deze telefoon. De wallet blijft op het horloge. + Het horloge vergeet deze telefoon en verwijdert zijn wallet zodra het weer verbinding maakt. Een horloge dat nooit meer verbinding maakt, behoudt de wallet. Verplaats je geld dus naar een nieuwe wallet als je het horloge kwijt bent. Horloge ontkoppelen? Widgets Widgets @@ -1265,11 +1255,6 @@ Factuutvervaldatum Het maximaal te besteden bedrag is iets lager vanwege een vereist reservesaldo. Reservesaldo - Betalen op horloge - Je horloge is bezig met een andere betaling. - Je horloge kon deze betaling niet aannemen. - Naar je horloge gestuurd. Houd daar ingedrukt om te betalen. - Je horloge is niet bereikbaar. Dit contact heeft nu geen betaalmethode die Bitkit kan gebruiken. Kan dit contact niet betalen Een eerdere opname van je bestedingssaldo wordt nog verwerkt. Probeer het opnieuw zodra die is voltooid. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 553dbda4d5..4b75443e3a 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -747,11 +747,7 @@ Poprzednio używane tagi Interfejs Płatności - Anuluj sparowanie i wyczyść zegarek - Wyczyść Czekam, aż zegarek usunie swój portfel. Zegarek, który nigdy więcej się nie połączy, zachowa go. - Zegarek zapomni ten telefon i usunie swój portfel przy następnym połączeniu. Zegarek, który nigdy więcej się nie połączy, zachowa portfel, więc jeśli zegarek zaginie, przenieś środki do nowego portfela. - Wyczyścić zegarek? Parowanie anulowane. Parowanie zostało anulowane na zegarku. Na zegarku jest inny portfel. @@ -790,18 +786,12 @@ Ten zegarek nie ma portfela. Parowanie wyśle do niego Twoją frazę odzyskiwania, więc będzie przechowywał Twój pełny portfel. Sparuj zegarek Potwierdź kod na zegarku. - QuickPay na zegarku - Zegarek płaci w ten sposób do ${limit} dziennie. Razem z tym telefonem mieści się w dziennym limicie QuickPay tego telefonu. - QuickPay jest wyłączony na tym telefonie, więc również na zegarku. - Wydano dziś przez QuickPay na zegarku: ${spent} - Płatności do ${amount} na zegarku nie wymagają przytrzymania. Zegarek nie ma PIN-u, więc ustaw niską kwotę. {name} jest gotowy do sparowania. Ustawień nie ma jeszcze na zegarku. Ustawienia zegarka są aktualne. Przestań czekać Anuluj sparowanie - Czekam na anulowanie sparowania zegarka. - Zegarek zapomni ten telefon. Portfel pozostanie na zegarku. + Zegarek zapomni ten telefon i usunie swój portfel przy następnym połączeniu. Zegarek, który nigdy więcej się nie połączy, zachowa portfel, więc jeśli zegarek zaginie, przenieś środki do nowego portfela. Anulować sparowanie zegarka? Widgety Widgety @@ -1110,11 +1100,6 @@ Wyślij Otrzymaj Wyślij Bitcoin - Zapłać na zegarku - Zegarek jest zajęty inną płatnością. - Zegarek nie mógł przyjąć tej płatności. - Wysłano na zegarek. Przytrzymaj tam, aby zapłacić. - Zegarek jest nieosiągalny. Ten kontakt nie ma teraz metody płatności, której Bitkit może użyć. Nie można zapłacić temu kontaktowi Wcześniejsza wypłata z Twojego salda wydatków wciąż się rozlicza. Spróbuj ponownie po jej zakończeniu. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 39c8818b00..f4a6228ff5 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -911,11 +911,7 @@ Falha no Envio Bitkit foi criado pela Synonym Software, S.A. DE C.V. ©2025. Todos os direitos reservados. Suporte - Desparear e Apagar Relógio - Apagar Aguardando o relógio apagar a carteira. Um relógio que nunca se reconectar continuará com ela. - O relógio vai esquecer este telefone e excluir a carteira na próxima vez que se conectar. Um relógio que nunca se reconectar continuará com a carteira, então mova seus fundos para uma nova carteira se o relógio for perdido. - Apagar Relógio? Pareamento cancelado. O pareamento foi cancelado no relógio. O relógio contém uma carteira diferente. @@ -954,18 +950,12 @@ Este relógio não tem carteira. O pareamento envia sua frase de recuperação para ele, que passará a conter sua carteira completa. Parear Relógio Confirme o código no seu relógio. - QuickPay no relógio - Seu relógio paga assim até ${limit} por dia. Junto com este celular, fica dentro do limite diário de QuickPay deste celular. - O QuickPay está desativado neste celular, então também no seu relógio. - Gasto hoje com QuickPay no seu relógio: ${spent} - Pagamentos de até ${amount} no relógio dispensam segurar para pagar. Seu relógio não tem PIN, então mantenha este valor baixo. {name} está pronto para parear. Os ajustes ainda não estão no relógio. Ajustes do relógio atualizados. Parar de Esperar Desparear - Aguardando o relógio ser despareado. - O relógio vai esquecer este telefone. A carteira permanece no relógio. + O relógio vai esquecer este telefone e excluir a carteira na próxima vez que se conectar. Um relógio que nunca se reconectar continuará com a carteira, então mova seus fundos para uma nova carteira se o relógio for perdido. Desparear Relógio? Widgets Widgets @@ -1274,11 +1264,6 @@ Vencimento do invoice O valor máximo utilizável é um pouco menor devido a um saldo de reserva obrigatório. Saldo de reserva - Pagar no relógio - Seu relógio está ocupado com outro pagamento. - Seu relógio não pôde receber este pagamento. - Enviado para o seu relógio. Segure lá para pagar. - Seu relógio não está acessível. Este contato não tem nenhum método de pagamento que o Bitkit possa usar agora. Não é possível pagar este contato Um levantamento anterior do seu saldo de gastos ainda está a ser concluído. Tente novamente quando for concluído. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 921ee16736..b796eaefe0 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -725,11 +725,7 @@ Tags usadas anteriormente Interface Pagamentos - Desemparelhar e apagar relógio - Apagar A aguardar que o relógio apague a carteira. Um relógio que nunca volte a ligar-se mantém-na. - O relógio vai esquecer este telemóvel e eliminar a carteira na próxima vez que se ligar. Um relógio que nunca volte a ligar-se mantém a carteira, por isso mova os seus fundos para uma nova carteira se o relógio for perdido. - Apagar relógio? Emparelhamento cancelado. O emparelhamento foi cancelado no relógio. O relógio contém uma carteira diferente. @@ -768,18 +764,12 @@ Este relógio não tem carteira. O emparelhamento envia-lhe a sua frase de recuperação, pelo que ficará com a sua carteira completa. Emparelhar relógio Confirme o código no seu relógio. - QuickPay no relógio - O relógio paga assim até ${limit} por dia. Em conjunto com este telemóvel, fica dentro do limite diário de QuickPay deste telemóvel. - O QuickPay está desativado neste telemóvel, por isso também no relógio. - Gasto hoje com QuickPay no relógio: ${spent} - Os pagamentos até ${amount} no relógio dispensam manter premido para pagar. O relógio não tem PIN, por isso mantenha este valor baixo. {name} está pronto para emparelhar. Os ajustes ainda não estão no relógio. Ajustes do relógio atualizados. Parar de esperar Desemparelhar - A aguardar que o relógio seja desemparelhado. - O relógio vai esquecer este telemóvel. A carteira permanece no relógio. + O relógio vai esquecer este telemóvel e eliminar a carteira na próxima vez que se ligar. Um relógio que nunca volte a ligar-se mantém a carteira, por isso mova os seus fundos para uma nova carteira se o relógio for perdido. Desemparelhar relógio? Widgets Widgets @@ -974,11 +964,6 @@ Enviar Receber Enviar Bitcoin - Pagar no relógio - O relógio está ocupado com outro pagamento. - O relógio não pôde receber este pagamento. - Enviado para o relógio. Mantenha premido lá para pagar. - O relógio não está acessível. Este contacto não tem nenhum método de pagamento que a Bitkit possa usar agora. Não é possível pagar a este contacto Um levantamento anterior do seu saldo de gastos ainda está a ser concluído. Tente novamente quando terminar. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index ca5ba22a98..25ae02b9c9 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -923,11 +923,7 @@ Не Удалось Отправить Bitkit создан компанией Synonym Software, S.A. DE C.V. ©2025. Все права защищены. Поддержка - Отменить Сопряжение И Стереть Часы - Стереть Ожидаем, пока часы сотрут свой кошелёк. Если часы больше не подключатся, кошелёк останется на них. - Часы забудут этот телефон и удалят свой кошелёк при следующем подключении. Если часы больше не подключатся, кошелёк останется на них, поэтому переведите средства в новый кошелёк, если часы утеряны. - Стереть Часы? Сопряжение отменено. Сопряжение было отменено на часах. На часах другой кошелёк. @@ -966,18 +962,12 @@ На этих часах нет кошелька. При сопряжении на них отправляется ваша фраза восстановления, поэтому на них будет храниться ваш кошелёк целиком. Сопряжение Часов Подтвердите код на часах. - QuickPay На Часах - Так часы платят до ${limit} в день. Вместе с этим телефоном они остаются в пределах дневного лимита QuickPay этого телефона. - QuickPay выключен на этом телефоне, а значит, и на часах. - Потрачено сегодня через QuickPay на часах: ${spent} - Платежи до ${amount} на часах проходят без удержания. На часах нет PIN-кода, поэтому держите сумму небольшой. Устройство {name} готово к сопряжению. Настройки ещё не переданы на часы. Настройки часов актуальны. Не Ждать Отменить Сопряжение - Ожидаем отмены сопряжения на часах. - Часы забудут этот телефон. Кошелёк останется на часах. + Часы забудут этот телефон и удалят свой кошелёк при следующем подключении. Если часы больше не подключатся, кошелёк останется на них, поэтому переведите средства в новый кошелёк, если часы утеряны. Отменить Сопряжение? Виджеты Виджеты @@ -1287,11 +1277,6 @@ Срок действия инвойса Максимальная сумма для траты немного меньше из-за необходимого резервного баланса. Резервный баланс - Оплатить На Часах - Часы заняты другим платежом. - Часы не смогли принять этот платёж. - Отправлено на часы. Удерживайте там для оплаты. - Часы недоступны. У этого контакта сейчас нет способа оплаты, который может использовать Bitkit. Невозможно оплатить этому контакту Предыдущий вывод с вашего баланса расходов ещё проводится. Попробуйте ещё раз после его завершения. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index efaee5867c..68e1ddf378 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1247,11 +1247,7 @@ Sent Successfully Failed To Send Support - Unpair and Erase Watch - Erase Waiting for the watch to erase its wallet. A watch that never reconnects keeps it. - The watch will forget this phone and delete its wallet the next time it connects. A watch that never reconnects keeps the wallet, so move your funds to a new wallet if the watch is lost. - Erase Watch? Pairing cancelled. Pairing was cancelled on the watch. The watch holds a different wallet. @@ -1290,18 +1286,12 @@ This watch has no wallet. Pairing sends it your recovery phrase, so it will hold your full wallet. Pair Watch Confirm the code on your watch. - QuickPay on Watch - Your watch pays up to ${limit} a day this way. Together with this phone it stays within this phone\'s daily QuickPay limit. - QuickPay is off on this phone, so it is off on your watch too. - Spent with QuickPay on your watch today: ${spent} - Payments up to ${amount} on your watch skip the hold to pay. Your watch has no PIN, so keep this low. {name} is ready to pair. Settings not on watch yet. Watch settings up to date. Stop Waiting Unpair - Waiting for the watch to unpair. - The watch will forget this phone. Its wallet stays on the watch. + The watch will forget this phone and delete its wallet the next time it connects. A watch that never reconnects keeps the wallet, so move your funds to a new wallet if the watch is lost. Unpair Watch? Widgets Reset Suggestions Cards @@ -1837,11 +1827,6 @@ Invoice expiration The maximum spendable amount is a bit lower due to a required reserve balance. Reserve Balance - Pay on Watch - Your watch is busy with another payment. - Your watch couldn\'t take this payment. - Sent to your watch. Hold to pay there. - Your watch is not reachable. This contact has no payment method Bitkit can use right now. Can\'t pay this contact An earlier withdrawal from your spending balance is still settling. Try again once it completes. diff --git a/app/src/test/java/to/bitkit/data/serializers/WatchLinkSerializerTest.kt b/app/src/test/java/to/bitkit/data/serializers/WatchLinkSerializerTest.kt new file mode 100644 index 0000000000..fb9c479357 --- /dev/null +++ b/app/src/test/java/to/bitkit/data/serializers/WatchLinkSerializerTest.kt @@ -0,0 +1,29 @@ +package to.bitkit.data.serializers + +import kotlinx.serialization.encodeToString +import org.junit.Test +import to.bitkit.data.WatchLinkData +import to.bitkit.di.json +import to.bitkit.test.BaseUnitTest +import to.bitkit.wearlink.LinkRecord +import to.bitkit.wearlink.Removal +import java.io.ByteArrayInputStream +import kotlin.test.assertEquals + +class WatchLinkSerializerTest : BaseUnitTest() { + @Test + fun `read keeps the store of a record with the unpair removal of an earlier build, without the removal`() = test { + val record = LinkRecord("pairing", "peer", "node", "Watch", pairedAtMs = 1, removal = Removal.Erase) + val stored = WatchLinkData( + record = record, + transferAttempts = 2, + transferLockedUntilMs = 100, + pairPromptNodeIds = listOf("node"), + ) + val raw = json.encodeToString(stored).replace("\"Erase\"", "\"Unpair\"") + + val result = WatchLinkSerializer.readFrom(ByteArrayInputStream(raw.encodeToByteArray())) + + assertEquals(stored.copy(record = record.copy(removal = null)), result) + } +} diff --git a/app/src/test/java/to/bitkit/models/BackupJsonTest.kt b/app/src/test/java/to/bitkit/models/BackupJsonTest.kt index 3bbf06ee2d..bb6ab2b17b 100644 --- a/app/src/test/java/to/bitkit/models/BackupJsonTest.kt +++ b/app/src/test/java/to/bitkit/models/BackupJsonTest.kt @@ -70,27 +70,21 @@ class BackupJsonTest { } @Test - fun `a backup without the watch's quickpay keys, as from an older build or bitkit-ios, gives their defaults`() { - val settings = decodeSettingsBackup(iosFixture("settings")).settings - val defaults = SettingsData() + fun `a backup with the watch's own quickpay keys of an earlier build decodes and keeps the phone's quickpay`() { + val raw = """{"version":1,"createdAt":1,"settings":{"isQuickPayEnabled":true,"quickPayAmount":10,""" + + """"isWatchQuickPayEnabled":true,"watchQuickPayAmount":20,"watchQuickPayDailyLimitMultiplier":2}}""" - assertEquals(false, settings.isWatchQuickPayEnabled) - assertEquals(defaults.watchQuickPayAmount, settings.watchQuickPayAmount) - assertEquals(defaults.watchQuickPayDailyLimitMultiplier, settings.watchQuickPayDailyLimitMultiplier) - assertEquals(false, settings.watchInstallPromptSeen) + val settings = decodeSettingsBackup(raw).settings + + assertEquals(true, settings.isQuickPayEnabled) + assertEquals(10, settings.quickPayAmount) } @Test - fun `the watch's quickpay keys are restored, and a reader that does not know them skips them`() { - val raw = """{"version":1,"createdAt":1,"settings":{"isQuickPayEnabled":true,"isWatchQuickPayEnabled":true,""" + - """"watchQuickPayAmount":1,"watchQuickPayDailyLimitMultiplier":3,"someLaterSetting":{"a":[1]}}}""" - - val settings = decodeSettingsBackup(raw).settings + fun `a backup without the watch install prompt key, as from an older build or bitkit-ios, gives its default`() { + val settings = decodeSettingsBackup(iosFixture("settings")).settings - assertEquals(true, settings.isQuickPayEnabled) - assertEquals(true, settings.isWatchQuickPayEnabled) - assertEquals(1, settings.watchQuickPayAmount) - assertEquals(3, settings.watchQuickPayDailyLimitMultiplier) + assertEquals(false, settings.watchInstallPromptSeen) } @Test diff --git a/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt b/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt index 598b89791f..52817bf0f9 100644 --- a/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt +++ b/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt @@ -15,9 +15,8 @@ import kotlin.test.assertEquals /** * The Wear OS app imports the phone's settings by reading the settings backup from VSS (docs/wear.md, Settings - * sync). `wear/src/test/resources/phone-backup-contract.json` holds what it relies on: the backup's key, nine - * settings as this app encodes them (six the phone uses itself and the watch's own three QuickPay limits), and where - * each network's backups live. The watch's `PhoneBackupContractTest` + * sync). `wear/src/test/resources/phone-backup-contract.json` holds what it relies on: the backup's key, six + * settings as this app encodes them, and where each network's backups live. The watch's `PhoneBackupContractTest` * reads the same file. When a test here fails, the watch stops reading the phone's settings: change the watch's * reader and the file together with the phone. */ @@ -35,7 +34,7 @@ class WatchBackupContractTest { } @Test - fun `the settings backup holds the nine settings the watch reads, in the form it reads`() { + fun `the settings backup holds the six settings the watch reads, in the form it reads`() { val expected = contract.getValue("settingsBackup").jsonObject val expectedSettings = expected.getValue("settings").jsonObject val settings = SettingsData( @@ -45,9 +44,6 @@ class WatchBackupContractTest { isQuickPayEnabled = true, quickPayAmount = 10, quickPayDailyLimitMultiplier = 3, - isWatchQuickPayEnabled = true, - watchQuickPayAmount = 1, - watchQuickPayDailyLimitMultiplier = 5, ) val written = written(settings) @@ -58,7 +54,7 @@ class WatchBackupContractTest { } @Test - fun `default settings are written too, so the watch always finds all nine`() { + fun `default settings are written too, so the watch always finds all six`() { val keys = contract.getValue("settingsBackup").jsonObject.getValue("settings").jsonObject.keys val written = written(SettingsData()).getValue("settings").jsonObject diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index ec28f72ce6..65a92e6359 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -222,88 +222,6 @@ class QuickPayRepoTest : BaseUnitTest() { } } - @Test - fun `turning on or raising the watch's quickpay asks for the pin while payments need it`() = test { - stubSettingsUpdate() - listOf(pinSettings(isBiometricEnabled = true), pinSettings()).forEach { start -> - settingsData.value = start - listOf( - QuickPayChange.WatchEnabled(true), - QuickPayChange.WatchAmount(20), - QuickPayChange.WatchDailyLimitMultiplier(10), - ).forEach { - sut.requestSettingsChange(it).await().getOrThrow() - assertEquals(it, assertNotNull(sut.pendingSettingsChange.value).change) - sut.cancelSettingsChange() - } - - assertEquals(start, settingsData.value) - } - } - - @Test - fun `turning off or lowering the watch's quickpay saves at once`() = test { - stubSettingsUpdate() - val gated = pinSettings().copy( - isWatchQuickPayEnabled = true, - watchQuickPayAmount = 20, - watchQuickPayDailyLimitMultiplier = 10, - ) - settingsData.value = gated - - sut.requestSettingsChange(QuickPayChange.WatchEnabled(false)).await().getOrThrow() - sut.requestSettingsChange(QuickPayChange.WatchAmount(1)).await().getOrThrow() - sut.requestSettingsChange(QuickPayChange.WatchDailyLimitMultiplier(1)).await().getOrThrow() - - assertNull(sut.pendingSettingsChange.value) - assertEquals( - gated.copy(isWatchQuickPayEnabled = false, watchQuickPayAmount = 1, watchQuickPayDailyLimitMultiplier = 1), - settingsData.value, - ) - } - - @Test - fun `a raise of the watch's quickpay follows the phone's own rule and saves at once without pin for payments`() = - test { - stubSettingsUpdate() - listOf( - SettingsData(isPinEnabled = false), - SettingsData(isPinEnabled = true, isPinForPaymentsEnabled = false), - SettingsData(isPinEnabled = false, isPinForPaymentsEnabled = true), - ).forEach { start -> - settingsData.value = start - // The phone's own switch and the watch's are decided alike. - sut.requestSettingsChange(QuickPayChange.Enabled(true)).await().getOrThrow() - sut.requestSettingsChange(QuickPayChange.WatchEnabled(true)).await().getOrThrow() - sut.requestSettingsChange(QuickPayChange.WatchAmount(50)).await().getOrThrow() - sut.requestSettingsChange(QuickPayChange.WatchDailyLimitMultiplier(50)).await().getOrThrow() - - assertNull(sut.pendingSettingsChange.value) - assertEquals( - start.copy( - isQuickPayEnabled = true, - isWatchQuickPayEnabled = true, - watchQuickPayAmount = 50, - watchQuickPayDailyLimitMultiplier = 50, - ), - settingsData.value, - ) - } - } - - @Test - fun `an authorized watch change saves only that change`() = test { - stubSettingsUpdate() - settingsData.value = pinSettings() - sut.requestSettingsChange(QuickPayChange.WatchEnabled(true)).await().getOrThrow() - val check = assertNotNull(sut.pendingSettingsChange.value) - - sut.applyAuthorizedSettingsChange(check).getOrThrow() - - assertNull(sut.pendingSettingsChange.value) - assertEquals(pinSettings().copy(isWatchQuickPayEnabled = true), settingsData.value) - } - @Test fun `requestSettingsChange ignores a further raise while a check is open`() = test { val release = holdSettingsUpdates() diff --git a/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt index c98e8d8d99..c7d9e6f3d2 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt @@ -6,12 +6,9 @@ import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runCurrent -import kotlinx.datetime.TimeZone -import kotlinx.datetime.toLocalDateTime import org.junit.Test import org.mockito.kotlin.mock import org.mockito.kotlin.never @@ -39,8 +36,6 @@ import to.bitkit.wearlink.LinkTransport import to.bitkit.wearlink.OpenSend import to.bitkit.wearlink.PairingState import to.bitkit.wearlink.PairingThrottle -import to.bitkit.wearlink.PayRequestDoc -import to.bitkit.wearlink.PayResult import to.bitkit.wearlink.PeerInvoice import to.bitkit.wearlink.QuickPayDoc import to.bitkit.wearlink.Removal @@ -78,7 +73,6 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { const val NOW = 1_800_000_000_000L const val MNEMONIC = "abandon abandon about" const val PASSPHRASE = "pass" - const val INVOICE = "lnbcrt10u1pexample" val HASH = "ab".repeat(32) val OWN_HASH = "cd".repeat(32) @@ -111,10 +105,6 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { var quickPay: QuickPayDoc? = null var sends: List? = null } - - /** The payment requests the watch was handed, and what it answers. */ - private val payRequests = mutableListOf() - private var payAnswer = PayResult.Received private val storedSeeds = mutableListOf() private var erases = 0 private var nowMs = NOW @@ -164,11 +154,6 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { override suspend fun clearPeerState() = Unit override fun onPhonePaired() = Unit - - override suspend fun onPayRequest(request: PayRequestDoc): PayResult { - payRequests += request - return payAnswer - } }, info = { WatchInfo("1.0", isLockSet = false) }, nowMs = { nowMs }, @@ -286,40 +271,6 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertEquals(NOW + 5_000, appliedSettings.last().changedAtMs) } - @Test - fun `the watch's own quickpay limits are pushed with the settings`() = test { - setUp() - pair() - nowMs += 5_000 - - settings.update { it.copy(isWatchQuickPayEnabled = true, watchQuickPayAmount = 1) } - runCurrent() - settings.update { it.copy(watchQuickPayDailyLimitMultiplier = 3) } - runCurrent() - - assertEquals(listOf(false, true, true), appliedSettings.map { it.isWatchQuickPayEnabled }) - assertEquals(5, appliedSettings.first().watchQuickPayAmount) - assertEquals(1, appliedSettings.last().watchQuickPayAmount) - assertEquals(3, appliedSettings.last().watchQuickPayDailyLimitMultiplier) - } - - @Test - fun `the watch's spend today is what it said for the phone's day, and nothing without a pairing`() = test { - setUp() - assertNull(sut.watchSpentTodayCents.first()) - pair() - assertEquals(0L, sut.watchSpentTodayCents.first()) - val today = clock.now().toLocalDateTime(TimeZone.currentSystemDefault()).date.toString() - - watchLink.publishQuickPay(QuickPayDoc(today, 250)) - runCurrent() - assertEquals(250L, sut.watchSpentTodayCents.first()) - - watchLink.publishQuickPay(QuickPayDoc("2000-01-01", 900)) - runCurrent() - assertEquals(0L, sut.watchSpentTodayCents.first()) - } - @Test fun `a setting the watch does not adopt is not pushed`() = test { setUp() @@ -656,33 +607,21 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { // endregion @Test - fun `unpair waits for the watch and then forgets it`() = test { + fun `unpair waits for the watch, which deletes its wallet, and then forgets it`() = test { setUp() pair() network.isConnected = false - sut.remove(isErase = false).getOrThrow() - assertEquals(Removal.Unpair, assertNotNull(store.load()).removal) + sut.unpair().getOrThrow() + assertEquals(Removal.Erase, assertNotNull(store.load()).removal) network.reconnect() runCurrent() assertNull(store.load()) assertNull(watchStore.load()) - assertEquals(0, erases) - assertTrue(phoneKeys.keys.isEmpty()) - } - - @Test - fun `erase deletes the wallet on the watch and forgets it once acknowledged`() = test { - setUp() - pair() - - sut.remove(isErase = true).getOrThrow() - runCurrent() - assertEquals(1, erases) - assertNull(store.load()) + assertTrue(phoneKeys.keys.isEmpty()) } @Test @@ -824,7 +763,7 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { watchLink.publishSends(listOf(OpenSend("key-0", paymentHash = HASH))) runCurrent() - sut.remove(isErase = false).getOrThrow() + sut.unpair().getOrThrow() runCurrent() assertNull(store.load()) @@ -866,124 +805,6 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertTrue(first.contentEquals(store.installId())) } - // region payment handoff - - private fun TestScope.handOff(): MutableList { - val results = mutableListOf() - backgroundScope.launch { sut.payOnWatch(INVOICE).collect { results += it } } - runCurrent() - return results - } - - @Test - fun `the paired watch is reachable only while it is paired and connected`() = test { - setUp() - assertFalse(sut.isWatchReachable()) - - pair() - assertTrue(sut.isWatchReachable()) - - network.isConnected = false - assertFalse(sut.isWatchReachable()) - } - - @Test - fun `a handed-off request reaches the watch and its link opens there`() = test { - setUp() - pair() - - val results = handOff() - - assertEquals(listOf(PayOnWatchResult.Sent), results) - val request = payRequests.single() - assertEquals(INVOICE, request.input) - assertEquals(LinkPaths.payUri(request.id), network.opened.last()) - } - - @Test - fun `a busy watch is said to be busy, and nothing opens on it`() = test { - setUp() - pair() - payAnswer = PayResult.Busy - val opened = network.opened.size - - assertEquals(listOf(PayOnWatchResult.Busy), handOff()) - assertEquals(opened, network.opened.size) - } - - @Test - fun `a watch that refuses is said to have refused, and one that is away is not reachable`() = test { - setUp() - pair() - payAnswer = PayResult.Refused - val opened = network.opened.size - assertEquals(listOf(PayOnWatchResult.Refused), handOff()) - assertEquals(opened, network.opened.size) - - network.isConnected = false - assertEquals(listOf(PayOnWatchResult.Unreachable), handOff()) - } - - @Test - fun `a watch that never answers is not reachable once the wait ends`() = test { - setUp() - pair() - network.intercept = { if (it.path.endsWith(LinkPaths.PAY_RESULT)) null else it.payload } - - val results = handOff() - assertTrue(results.isEmpty()) - testScheduler.advanceTimeBy(11_000) - runCurrent() - - assertEquals(listOf(PayOnWatchResult.Unreachable), results) - } - - @Test - fun `a request the watch dropped later for a send under way turns the line to busy`() = test { - setUp() - pair() - val results = handOff() - - watchLink.answerPay(payRequests.single().id, PayResult.Busy) - runCurrent() - - assertEquals(listOf(PayOnWatchResult.Sent, PayOnWatchResult.Busy), results) - } - - @Test - fun `a request the watch dropped later where it cannot show it turns the line to refused`() = test { - setUp() - pair() - val results = handOff() - - watchLink.answerPay(payRequests.single().id, PayResult.Refused) - runCurrent() - - assertEquals(listOf(PayOnWatchResult.Sent, PayOnWatchResult.Refused), results) - } - - @Test - fun `the answer to another request never turns the line`() = test { - setUp() - pair() - val results = handOff() - - watchLink.answerPay("ef".repeat(16), PayResult.Refused) - runCurrent() - - assertEquals(listOf(PayOnWatchResult.Sent), results) - } - - @Test - fun `no request is handed over without a pairing`() = test { - setUp() - - assertEquals(listOf(PayOnWatchResult.Unreachable), handOff()) - assertTrue(payRequests.isEmpty()) - } - - // endregion - // region install prompt @Test diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/PayOnWatchInputTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/PayOnWatchInputTest.kt deleted file mode 100644 index de524c4e71..0000000000 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/PayOnWatchInputTest.kt +++ /dev/null @@ -1,117 +0,0 @@ -package to.bitkit.ui.screens.wallets.send - -import com.synonym.bitkitcore.LightningInvoice -import com.synonym.bitkitcore.LnurlPayData -import com.synonym.bitkitcore.NetworkType -import com.synonym.bitkitcore.PaykitEndpoint -import com.synonym.bitkitcore.ServiceRouteLeg -import kotlinx.collections.immutable.persistentListOf -import org.junit.Test -import to.bitkit.viewmodels.LnurlParams -import to.bitkit.viewmodels.PaykitRouteUi -import to.bitkit.viewmodels.PaykitSwapRouteUi -import to.bitkit.viewmodels.SendMethod -import to.bitkit.viewmodels.SendUiState -import kotlin.test.assertEquals -import kotlin.test.assertNull - -/** Which send states offer Pay on Watch, and what they hand over. */ -class PayOnWatchInputTest { - private companion object { - const val INVOICE = "lnbcrt10u1pexample" - const val SATS = 1_000uL - - val ENDPOINT = PaykitEndpoint(methodId = "btc-regtest-p2wpkh", value = "bcrt1qexample") - val LNURL = LnurlPayData( - uri = "lnurl1example", - callback = "https://example.com/pay", - minSendable = 1_000_000u, - maxSendable = 1_000_000u, - metadataStr = "[]", - commentAllowed = null, - allowsNostr = false, - nostrPubkey = null, - ) - } - - private fun invoice(bolt11: String = INVOICE, sats: ULong = SATS) = LightningInvoice( - bolt11 = bolt11, - paymentHash = byteArrayOf(1, 2, 3), - amountSatoshis = sats, - timestampSeconds = 0uL, - expirySeconds = 86_400uL, - isExpired = false, - description = "test", - networkType = NetworkType.REGTEST, - payeeNodeId = null, - ) - - private fun lightning() = SendUiState( - amount = SATS, - payMethod = SendMethod.LIGHTNING, - decodedInvoice = invoice(), - ) - - @Test - fun `a bolt11 invoice with an amount is handed over as decoded`() { - assertEquals(INVOICE, lightning().payOnWatchInput()) - } - - @Test - fun `the unused bolt11 field of the send state offers nothing`() { - assertNull(SendUiState(payMethod = SendMethod.LIGHTNING, bolt11 = INVOICE).payOnWatchInput()) - } - - @Test - fun `an invoice without an amount is not offered, whatever was typed on the phone`() { - assertNull(lightning().copy(decodedInvoice = invoice(sats = 0uL)).payOnWatchInput()) - } - - @Test - fun `a blank invoice is not offered`() { - assertNull(lightning().copy(decodedInvoice = invoice(bolt11 = " ")).payOnWatchInput()) - } - - @Test - fun `an onchain send is not offered`() { - assertNull(lightning().copy(payMethod = SendMethod.ONCHAIN).payOnWatchInput()) - } - - @Test - fun `an lnurl pay is not offered`() { - assertNull(lightning().copy(lnurl = LnurlParams.LnurlPay(LNURL)).payOnWatchInput()) - } - - @Test - fun `a payment request is not offered`() { - assertNull(lightning().copy(isPaymentRequest = true).payOnWatchInput()) - } - - @Test - fun `a subscription payment is not offered`() { - assertNull(lightning().copy(isSubscriptionPayment = true).payOnWatchInput()) - assertNull(lightning().copy(isInitialSubscriptionPayment = true).payOnWatchInput()) - } - - @Test - fun `a hardware wallet's send is not offered`() { - assertNull(lightning().copy(hardwareWalletId = "trezor").payOnWatchInput()) - } - - @Test - fun `a contact payment over a spark leg or a swap is not offered`() { - val leg = ServiceRouteLeg( - service = "spark", - endpoint = ENDPOINT, - deliveredSat = SATS, - debitSat = SATS, - atomicity = "trusted", - validUntilUnix = 0uL, - ) - val route = PaykitRouteUi(persistentListOf(ENDPOINT), offersSparkLeg = true, serviceLeg = leg) - - assertNull(lightning().copy(paykitRoute = route).payOnWatchInput()) - assertNull(lightning().copy(paykitSwapRoute = PaykitSwapRouteUi(ENDPOINT)).payOnWatchInput()) - assertEquals(INVOICE, lightning().copy(paykitRoute = route.copy(serviceLeg = null)).payOnWatchInput()) - } -} diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/PayOnWatchViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/PayOnWatchViewModelTest.kt deleted file mode 100644 index 231cfab571..0000000000 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/PayOnWatchViewModelTest.kt +++ /dev/null @@ -1,61 +0,0 @@ -package to.bitkit.ui.screens.wallets.send - -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.flowOf -import org.junit.Test -import org.mockito.kotlin.mock -import org.mockito.kotlin.times -import org.mockito.kotlin.verify -import org.mockito.kotlin.whenever -import to.bitkit.repositories.PayOnWatchResult -import to.bitkit.repositories.WatchLinkRepo -import to.bitkit.test.BaseUnitTest -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNull -import kotlin.test.assertTrue - -class PayOnWatchViewModelTest : BaseUnitTest() { - private companion object { - const val INVOICE = "lnbcrt10u1pexample" - } - - private val repo = mock() - - @Test - fun `pay on watch is offered only while the paired watch is reachable`() = test { - whenever { repo.isWatchReachable() }.thenReturn(false) - val sut = PayOnWatchViewModel(repo) - - sut.refresh() - assertFalse(sut.uiState.value.isAvailable) - - whenever { repo.isWatchReachable() }.thenReturn(true) - sut.refresh() - assertTrue(sut.uiState.value.isAvailable) - } - - @Test - fun `a tap shows each result line the handoff gives`() = test { - whenever(repo.payOnWatch(INVOICE)).thenReturn(flowOf(PayOnWatchResult.Sent, PayOnWatchResult.Busy)) - val sut = PayOnWatchViewModel(repo) - - sut.onPayOnWatchClick(INVOICE) - - assertEquals(PayOnWatchResult.Busy, sut.uiState.value.result) - assertFalse(sut.uiState.value.isSending) - } - - @Test - fun `a tap while a handoff is on its way hands nothing more over`() = test { - whenever(repo.payOnWatch(INVOICE)).thenReturn(MutableSharedFlow()) - val sut = PayOnWatchViewModel(repo) - - sut.onPayOnWatchClick(INVOICE) - sut.onPayOnWatchClick(INVOICE) - - assertTrue(sut.uiState.value.isSending) - assertNull(sut.uiState.value.result) - verify(repo, times(1)).payOnWatch(INVOICE) - } -} diff --git a/app/src/test/java/to/bitkit/ui/sheets/watch/WatchQuickPayViewModelTest.kt b/app/src/test/java/to/bitkit/ui/sheets/watch/WatchQuickPayViewModelTest.kt deleted file mode 100644 index a36c279874..0000000000 --- a/app/src/test/java/to/bitkit/ui/sheets/watch/WatchQuickPayViewModelTest.kt +++ /dev/null @@ -1,115 +0,0 @@ -package to.bitkit.ui.sheets.watch - -import android.content.Context -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.launch -import kotlinx.coroutines.test.TestScope -import kotlinx.coroutines.test.runCurrent -import org.junit.Before -import org.junit.Test -import org.mockito.kotlin.any -import org.mockito.kotlin.inOrder -import org.mockito.kotlin.mock -import org.mockito.kotlin.verify -import org.mockito.kotlin.whenever -import to.bitkit.R -import to.bitkit.data.SettingsData -import to.bitkit.data.SettingsStore -import to.bitkit.repositories.QuickPayAuthorization -import to.bitkit.repositories.QuickPayChange -import to.bitkit.repositories.QuickPayRepo -import to.bitkit.repositories.WatchLinkRepo -import to.bitkit.test.BaseUnitTest -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNull -import kotlin.test.assertSame -import kotlin.test.assertTrue - -@OptIn(ExperimentalCoroutinesApi::class) -class WatchQuickPayViewModelTest : BaseUnitTest() { - private val context: Context = mock() - private val settingsStore: SettingsStore = mock() - private val quickPayRepo: QuickPayRepo = mock() - private val watchLinkRepo: WatchLinkRepo = mock() - private val settings = MutableStateFlow(SettingsData()) - private val pendingCheck = MutableStateFlow(null) - private val spent = MutableStateFlow(null) - - private lateinit var sut: WatchQuickPayViewModel - - @Before - fun setUp() { - whenever(context.getString(R.string.common__error)).thenReturn("Error") - whenever(context.getString(R.string.common__error_body)).thenReturn("Unknown error") - whenever(settingsStore.data).thenReturn(settings) - whenever(quickPayRepo.pendingSettingsChange).thenReturn(pendingCheck) - whenever(quickPayRepo.requestSettingsChange(any())).thenReturn(CompletableDeferred(Result.success(Unit))) - whenever { quickPayRepo.applyAuthorizedSettingsChange(any()) }.thenReturn(Result.success(Unit)) - whenever(watchLinkRepo.watchSpentTodayCents).thenReturn(spent) - sut = WatchQuickPayViewModel(context, settingsStore, quickPayRepo, watchLinkRepo) - } - - @Test - fun `watch quickpay is off by default and shows the phone's own state`() = test { - val state = loadedState() - - assertFalse(state.isEnabled) - assertFalse(state.isPhoneQuickPayEnabled) - assertNull(state.spentTodayCents) - } - - @Test - fun `the state mirrors the stored watch limits, the watch's spend and the open check`() = test { - val check = QuickPayAuthorization(QuickPayChange.WatchAmount(20), useBiometrics = false) - settings.value = SettingsData( - isQuickPayEnabled = true, - isWatchQuickPayEnabled = true, - watchQuickPayAmount = 1, - watchQuickPayDailyLimitMultiplier = 3, - ) - pendingCheck.value = check - spent.value = 125 - - val state = loadedState() - - assertTrue(state.isEnabled) - assertTrue(state.isPhoneQuickPayEnabled) - assertEquals(1, state.amount) - assertEquals(3, state.dailyLimitMultiplier) - assertEquals(125L, state.spentTodayCents) - assertSame(check, state.authorization) - } - - @Test - fun `changes go to the repo's settings queue as watch changes, in tap order`() = test { - sut.setEnabled(true) - sut.setAmount(10) - sut.setDailyLimitMultiplier(3) - - inOrder(quickPayRepo) { - verify(quickPayRepo).requestSettingsChange(QuickPayChange.WatchEnabled(true)) - verify(quickPayRepo).requestSettingsChange(QuickPayChange.WatchAmount(10)) - verify(quickPayRepo).requestSettingsChange(QuickPayChange.WatchDailyLimitMultiplier(3)) - } - } - - @Test - fun `verifying saves the shown check and cancelling closes it`() = test { - val check = QuickPayAuthorization(QuickPayChange.WatchEnabled(true), useBiometrics = true) - - sut.onAuthorized(check) - sut.onAuthorizationCancelled() - - verify(quickPayRepo).applyAuthorizedSettingsChange(check) - verify(quickPayRepo).cancelSettingsChange() - } - - private fun TestScope.loadedState(): WatchQuickPayUiState { - backgroundScope.launch { sut.uiState.collect {} } - runCurrent() - return sut.uiState.value - } -} diff --git a/app/src/test/java/to/bitkit/ui/sheets/watch/WatchSheetViewModelTest.kt b/app/src/test/java/to/bitkit/ui/sheets/watch/WatchSheetViewModelTest.kt index 6b7305f17c..bba98c2db5 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/watch/WatchSheetViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/watch/WatchSheetViewModelTest.kt @@ -225,38 +225,34 @@ class WatchSheetViewModelTest : BaseUnitTest() { } @Test - fun `unpair and erase each ask first and act only on confirm`() = test { - whenever { repo.remove(isErase = true) }.thenReturn(Result.success(Unit)) - whenever { repo.remove(isErase = false) }.thenReturn(Result.success(Unit)) + fun `unpair asks first and unpairs and erases only on confirm`() = test { + whenever { repo.unpair() }.thenReturn(Result.success(Unit)) val sut = WatchSheetViewModel(context, repo) record.update { record() } - sut.onEraseClick() - assertEquals(WatchRemoveDialog.Erase, sut.uiState.value.dialog) - sut.onDialogDismiss() - verify(repo, never()).remove(isErase = true) - - sut.onEraseClick() - sut.onDialogConfirm() - verify(repo).remove(isErase = true) + sut.onUnpairClick() + assertTrue(sut.uiState.value.isUnpairDialogShown) + sut.onUnpairDismiss() + sut.onUnpairConfirm() + verify(repo, never()).unpair() sut.onUnpairClick() - sut.onDialogConfirm() - verify(repo).remove(isErase = false) - assertNull(sut.uiState.value.dialog) + sut.onUnpairConfirm() + verify(repo).unpair() + assertFalse(sut.uiState.value.isUnpairDialogShown) } @Test fun `a dialog stays open while the same watch reports, and closes when the watch is gone`() = test { val sut = WatchSheetViewModel(context, repo) record.update { record() } - sut.onEraseClick() + sut.onUnpairClick() record.update { record(settingsSent = 4) } - assertEquals(WatchRemoveDialog.Erase, sut.uiState.value.dialog) + assertTrue(sut.uiState.value.isUnpairDialogShown) record.update { null } - assertNull(sut.uiState.value.dialog) + assertFalse(sut.uiState.value.isUnpairDialogShown) } @Test @@ -267,7 +263,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { record.update { record().copy(pairingId = "0807060504030201") } - assertNull(sut.uiState.value.dialog) + assertFalse(sut.uiState.value.isUnpairDialogShown) } @Test @@ -277,7 +273,6 @@ class WatchSheetViewModelTest : BaseUnitTest() { record.update { record(removal = Removal.Erase) } assertTrue(sut.uiState.value.paired?.isRemoving == true) - assertTrue(sut.uiState.value.paired?.isErasing == true) sut.onStopWaitingClick() @@ -607,33 +602,20 @@ class WatchSheetViewModelTest : BaseUnitTest() { // endregion - // region the watch's quickpay - @Test - fun `the watch's quickpay shows in the sheet and back returns to the watch`() = test { + fun `an unpair that cannot reach the watch's store shows an error`() = test { + whenever { repo.unpair() }.thenReturn(Result.failure(LinkError.Unreachable())) + whenever(context.getString(R.string.common__error_body)).thenReturn("Unknown error") + val toasts = toasts() val sut = WatchSheetViewModel(context, repo) + record.update { record() } - sut.onQuickPayClick() - assertTrue(sut.uiState.value.isQuickPayShown) - - sut.onQuickPayBack() - assertFalse(sut.uiState.value.isQuickPayShown) - } - - @Test - fun `the sheet opens on the watch again, and a pairing leaves the watch's quickpay`() = test { - val sut = WatchSheetViewModel(context, repo) - sut.onQuickPayClick() - sut.onSheetClose() - assertFalse(sut.uiState.value.isQuickPayShown) + sut.onUnpairClick() + sut.onUnpairConfirm() - sut.onQuickPayClick() - sut.onPairClick() - assertFalse(sut.uiState.value.isQuickPayShown) + assertEquals(listOf(Toast.ToastType.ERROR to "Unknown error"), toasts.map { it.type to it.description }) } - // endregion - @Test fun `install opens the play listing on the connected watch without bitkit, and only on one`() = test { val watch = LinkNode("node", "Pixel Watch", isNearby = true, hasApp = false) diff --git a/docs/screens-map.md b/docs/screens-map.md index e466aeeea0..216c45e2b5 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -375,7 +375,7 @@ Amount entry stays in dollars with a BTC equivalent; QR and shared payment amoun ### Watch pairing -`WatchSheet.kt` (Settings › General › Watch) pairs a Wear OS watch, shows the paired one and sets the watch's own QuickPay limits; see `docs/wear.md`, Pairing. `WatchInstallSheet.kt`, a timed sheet, offers to install Bitkit on a connected watch without it. `WatchPairSheet.kt`, another timed sheet, offers to pair a connected watch that has Bitkit and opens `WatchSheet.kt` on the pairing. `PayOnWatch.kt` adds Pay on Watch to the send review (`SendConfirmScreen.kt`). No design exists for any of them yet. Covered by `journeys/settings/watch-no-watch-connected.xml`, `journeys/settings/watch-quickpay-pin.xml`, `journeys/wear/pair-*.xml`, `journeys/wear/quickpay-watch-limit.xml` and `journeys/wear/pay-request-from-phone.xml`. +`WatchSheet.kt` (Settings › General › Watch) pairs a Wear OS watch and shows the paired one; see `docs/wear.md`, Pairing. `WatchInstallSheet.kt`, a timed sheet, offers to install Bitkit on a connected watch without it. `WatchPairSheet.kt`, another timed sheet, offers to pair a connected watch that has Bitkit and opens `WatchSheet.kt` on the pairing. No design exists for any of them yet. Covered by `journeys/settings/watch-no-watch-connected.xml` and `journeys/wear/pair-*.xml`. ## Wear OS diff --git a/docs/wear.md b/docs/wear.md index a5d5f2bdd2..aaed3b5cf2 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -192,7 +192,8 @@ On-screen copy stays short: a title or one line of at most about six words per s the QR rests: it hides behind the dimmed QR icon (`WatchReceiveHidden`, "Show QR") and the screen may turn off again, so a forgotten QR does not hold the screen at full brightness; a tap anywhere on that screen, or waking the watch from ambient mode, shows it for another 2 min. The invoice is made once the - wallet is ready, under the loading ring; a failure shows one line and a retry (`WatchReceiveError`, + wallet is ready, under the loading ring with the purple Lightning logo the phone puts on its spending QR + (`WatchReceiveLoading`); a failure shows one line and a retry (`WatchReceiveError`, `WatchReceiveRetry`). An invoice is replaced by a new one a minute before it expires, and it stays on screen until the new one exists; a replacement that fails is tried again every 5 s meanwhile, and when none exists by then, the loading ring, or the error, takes its place as it expires. A replaced invoice is still watched until it expires, so @@ -205,13 +206,30 @@ On-screen copy stays short: a title or one line of at most about six words per s amount and without the button, with the same haptic, so the always-on screen shows no amount; the amount shows once the watch wakes. Debug builds log each invoice shown (`Showing invoice`), which is how the journeys read it. While the QR shows, the watch also offers the invoice as an NFC tag, with the NFC hint below the QR (`WatchReceiveNfc`, or `WatchReceiveNfcOff` with NFC off): see NFC › Receive by tap. +- **Celebration.** A success shows the way the phone's new-payment sheet does, with no new library: the check of + a sent result, of a paid receive and of a sent outcome pops in from small with a spring bounce (`PopIn`), and + `Confetti` falls over the screen once, a native Compose canvas copy of the phone's Lottie `confetti_purple` + (squares in the spending purple, swaying, turning and flipping as they fall), over 2 s, then draws nothing more. + Both start on the frame the screen plays its success haptic (the confirm haptic of a send, the firm click of a + receive), so the three come together. In ambient mode there is neither: the always-on screen stays still, and the + haptic plays alone. Whether a success is celebrated is decided once, keyed on it (the payment's id, the outcome's + id, a flow's one send), as it is first shown (`rememberCelebration`): only one first shown awake is, and only + while it stays shown awake, so neither waking the watch on a Paid or Sent screen nor an outcome cut short and shown + again plays it again. Its haptic plays once too, on the frame it is first shown, in ambient mode as well. Both + decisions survive the screen being made again, so neither plays again then. With animations turned off both end + at once. A celebration logs one debug line as it starts (`Showed the success celebration for ''`), which the + journeys read, since a screen dump waits for the confetti to end. `CelebrationTest` checks the decision; `SendResultTest`, `ReceiveQrContentTest` and + `SendOutcomeOverlayTest` check where the confetti falls, that it is gone within 2 s, and that neither a wake, a + new screen nor (for the overlay) an outcome cut short plays the confetti or the haptic again; how it looks on a + device is not checked. - **Tile.** The Bitkit tile (`BalanceTileService`) uses the tiles and ProtoLayout Material 3 libraries: a primary - layout with the balance in the main slot and an edge button below. With a wallet it shows the balance in bitcoin, - in the unit (Modern or Classic) imported from the phone, white, as on the Balance page, and a round Brand orange - edge button with the QR icon ("Receive" to accessibility services), which opens the app on the receive QR: the - launch intent carries the extra `to.bitkit.wear.OPEN` with `receive`, which `LaunchRequest` reads as `Receive`, - and the receive QR opens above Home, as a payment link's send does. Without a wallet it shows the Bitkit mark and - a "Restore" edge button that opens the app. Tiles cannot use the app's fonts, so the balance is in the system font. + layout with the balance in the main slot and an edge button below. With a wallet it shows the balance in bitcoin, in + the unit (Modern or Classic) imported from the phone, white, as on the Balance page, and a round edge button in the + spending purple, as the receive screens, with the QR icon ("Receive" to accessibility services), which opens the app + on the receive QR: the launch intent carries the extra `to.bitkit.wear.OPEN` with `receive`, which `LaunchRequest` + reads as `Receive`, and the receive QR opens above Home, as a payment link's send does. Without a wallet it shows + the Bitkit mark and a "Restore" edge button in Brand orange that opens the app. Tiles cannot use the app's fonts, so + the balance is in the system font. - The tile only reads `WalletRepo`'s state in memory and never starts the wallet, so the balance shows only once the app loaded it in this process and a sync confirmed it, as on the Balance page; until then, and while the watch is locked, the dimmed mark stands in for it. A removed wallet shows the signed-out tile at once. @@ -223,7 +241,7 @@ On-screen copy stays short: a title or one line of at most about six words per s because the watch locked (`WalletStatus.Locked`). Tiles have no ambient mode: in ambient the system shows the watch face, so the app's rule that the always-on screen shows no amount holds without code in the tile. The tile carries no secret: the receive invoice is made by the app after the tap, never by the tile. - - The tile picker shows `tile_preview` (a drawing of the balance and the Receive button, no real amount). + - The tile picker shows `tile_preview` (a drawing of the balance and the purple Receive button, no real amount). `tile_logo` and `tile_logo_dim` are the mark's letters and dot without its black outline, the dim one at 40% opacity baked into its colours, since a tile image cannot be drawn half transparent or tinted per path. - **Send.** There is no Send page or button. A tapped NFC tag with a payment link opens the same flow as the link @@ -270,31 +288,41 @@ On-screen copy stays short: a title or one line of at most about six words per s and while the wallet is offline (`WalletStatus.Offline`), as when the network drops after that sync. With the wallet online and the payment handed to Spark the ring shows alone, also while a hold invoice settles. The screen stays on and the flow cannot be swiped away or left with Back while the send runs. - - Result: sent shows a check, "Sent" and the amount with the confirm haptic, and closes after 2 s. A payment that - did not settle within 10 s, as on the phone, or one that was already under way, from the watch or the phone, - shows a clock, "Pending" and the amount (`WatchSendPending`, `WatchSendResultAmount`) with a soft click; an - outcome Spark could not report shows "Check activity", never a failure; both stay for 5 s. An outcome that - arrives while they show replaces them at once: the check, "Sent" and the confirm haptic, closing 2 s later, - or the cross, "Payment failed", the reject haptic and OK. Only a result the wearer can read is switched: in - ambient mode, with the app off screen, with the watch locked or with the flow's screen gone, the outcome is - left to the outcome overlay, as a later one is (see Pending payments). The result and failure line is one - element that is a polite live region, and the switch changes its text, so it is designed to be said by a screen - reader; `SendResultTest` checks that the line stays the same element, and whether TalkBack on a watch says it is - a manual test, not tried yet. A line that only appears with its screen is not announced by this. The amount is - the one Spark paid. A request that was not sent because another send still holds the wallet shows "Wallet busy" - as a failure, never "Pending"; the request whose own stalled call Spark still holds shows "Pending", since that - call may still pay. A refusal or a failure shows a cross, one line of at most four words and an OK button - (`WatchSendError`, `WatchSendClose`), with the reject haptic. Insufficient funds, an expired or unreadable - invoice and an own invoice end there before any hold. -- **Activity.** The Activity page lists the newest 20 payments from Spark's local list: a direction icon (or a - clock for pending, a cross for failed), the amount with its sign and how long ago (`WatchActivityItem-0` onwards). - An amount too long for one line, as with eight decimals on a small screen, takes a second line. - It is read when Spark connects and after every payment or sync, and the last list stays while Spark is - disconnected, with its times counted again every minute; a list just read counts from its own time. A tap opens the detail: the amount, the fee of a send, the - date and time and the status (`WatchActivityDetailAmount`, `…Fee`, `…Time`, `…Status`); Spark's list carries no payee or description. With no - payments it shows a dimmed icon and "No activity" (`WatchActivityEmpty`). A detail whose payment the list does not - hold, while it loads or after newer payments pushed it out, shows the dimmed icon (`WatchActivityDetailMissing`). - Ambient mode hides the amounts. + - Result: sent shows a check, "Sent" and the amount with the confirm haptic, and closes after 2 s; the check pops in + and the confetti falls (Receive › Celebration, above). A payment that did not settle within 10 s, as on the phone, + or one that was already under way, from the watch or the phone, shows a clock, "Pending" and the amount + (`WatchSendPending`, `WatchSendResultAmount`) with a soft click; an outcome Spark could not report shows "Check + activity", never a failure; both stay for 5 s. An outcome that arrives while they show replaces them at once: the + check, "Sent" and the confirm haptic, closing 2 s later, or the cross, "Payment failed", the reject haptic and OK. + Only a result the wearer can read is switched: in ambient mode, with the app off screen, with the watch locked or + with the flow's screen gone, the outcome is left to the outcome overlay, as a later one is (see Pending payments). + The result and failure line is one element that is a polite live region, and the switch changes its text, so it is + designed to be said by a screen reader; `SendResultTest` checks that the line stays the same element, and whether + TalkBack on a watch says it is a manual test, not tried yet. A line that only appears with its screen is not + announced by this. The amount is the one Spark paid. A request that was not sent because another send still holds + the wallet shows "Wallet busy" as a failure, never "Pending"; the request whose own stalled call Spark still holds + shows "Pending", since that call may still pay. A refusal or a failure shows a cross, one line of at most four + words and an OK button (`WatchSendError`, `WatchSendClose`), with the reject haptic. Insufficient funds, an + expired or unreadable invoice and an own invoice end there before any hold. +- **Activity.** The Activity page lists the newest 20 payments from Spark's local list: the phone's activity icon of a + Lightning payment (`ActivityIcon`, copied from the phone's: the up or down arrow of its direction, an hourglass for + pending, a cross for failed, in the spending purple on its 16 % circle), the amount with its sign and when it was + made (`WatchActivityItem-0` onwards), as the phone's activity list writes it (`uiDateText` with `uiDateStyleFor`, + copied to `ext/DateTime.kt`): the time alone for a payment of today ("9:05 AM", or "09:05" in 24 hours, as the watch + is set), the day and time earlier this year ("March 3, 6:40 PM") and the year too before that. An amount too long + for one line, as with eight decimals on a small screen, takes a second line. It is read when Spark connects and + after every payment or sync, and the last list stays while Spark is disconnected; the clock its times are written by + is read again every minute, so a payment of today reads as a day once midnight passed, and a list just read counts + from its own time. A tap opens the detail: the amount, the fee of a send, the day and time as the phone's detail + writes them ("March 3, 6:40 PM", no year) and the status (`WatchActivityDetailAmount`, `…Fee`, `…Time`, `…Status`), + and the payment's note in up to two lines (`WatchActivityDetailMessage`) when it has one, in the middle of the + screen while the lines fit, else in a list that scrolls, also with the rotary input, so the status stays reachable + on the smallest round screen (`ListScreen`'s `isCentered`); the day and time also take + up to two lines, ending in an ellipsis. The note is as the phone's detail shows it: an LNURL comment of the payer, + or else the invoice's description, from Spark's payment details (`PaymentsRepo`, `Payment.message`); a blank one + shows nothing, and ambient mode hides it. Spark's list carries no payee. With no payments it shows a dimmed icon and + "No activity" (`WatchActivityEmpty`). A detail whose payment the list does not hold, while it loads or after newer + payments pushed it out, shows the dimmed icon (`WatchActivityDetailMissing`). Ambient mode hides the amounts. - **Settings.** A short list of icon rows: About, Phone settings and Remove wallet. The watch has no settings of its own to edit: the units, the currency and QuickPay come from the phone (see Settings sync). The Phone settings row (`WatchSettingsSync`) shows how long ago they were last imported (`WatchSettingsSyncTime`, absent until a first @@ -311,14 +339,17 @@ On-screen copy stays short: a title or one line of at most about six words per s (`BezelLoading`) is a stroke-sized spot at the top of the ring, and the content beneath stays reachable by TalkBack and `android layout`. `BezelPadding` and `BezelStrokeWidth` hold the ring's padding and stroke for other edge rings, such as hold-to-pay. -- **Style.** Black background; Brand orange only on the one primary action (an `EdgeButton`) and accents; Inter - Tight; content centered inside the round screen and clear of the time; icons rather than labels where the icon is - clear; no stacked button lists. A check icon is a success status (Sent, Paid, Paired) and never a screen's - button, anywhere on the watch: a confirm action is a short text `EdgeButton` named by what it does ("Match", - "OK", "Remove", "Unpair", "New invoice"), and cancelling is the watch's swipe-to-dismiss. - The two questions asked in a dialog (Remove wallet, Unpair phone) are the platform's alert dialog with that one - button. Icon and text buttons morph their shape on press and the theme uses the expressive - (spring) motion scheme. Icons are vector drawables in `res/drawable`, with no icon library. +- **Style.** Black background; Brand orange only on the one primary action (an `EdgeButton`) and accents; Inter Tight; + the send and receive screens (the Receive page, the receive QR, the send flow and the outcome overlay) in the + phone's spending purple instead (`SpendingTheme`, `Colors.Purple`, the phone's `Colors.Purple`), on their buttons, + rings and success icons, to say that the watch only spends and receives from the spending balance; content centered + inside the round screen and clear of the time; icons rather than labels where the icon is clear; no stacked button + lists. A check icon is a success status (Sent, Paid, Paired) and never a screen's button, anywhere on the watch: a + confirm action is a short text `EdgeButton` named by what it does ("Match", "OK", "Remove", "Unpair", "New + invoice"), and cancelling is the watch's swipe-to-dismiss. The two questions asked in a dialog (Remove wallet, + Unpair phone) are the platform's alert dialog with that one button. Icon and text buttons morph their shape on press + and the theme uses the expressive (spring) motion scheme. Icons are vector drawables in `res/drawable`, with no icon + library. ## Payments @@ -373,13 +404,13 @@ in any other state. outcome was unknown, and ends sent or failed within its own 10 s shows that on its own result. The watched payment is then forgotten untold, and QuickPay keeps one count for the one payment: the earlier attempt's, with the retry's taken out, or none when it failed. - - Told once. The outcome shows for 2 s, with a haptic: a check in Brand orange for sent (`WatchOutcomeSent`) + - Told once. The outcome shows for 2 s, with a haptic: a check in the spending purple for sent (`WatchOutcomeSent`) or a cross for failed (`WatchOutcomeFailed`), and the amount. It is an overlay in `MainActivity` (`SendOutcomeOverlay`), not a screen and not a button: touches and Back do nothing until it is gone (turning the crown only scrolls the list beneath, and pressing it leaves the app as always). It shows only with the app on screen, out of ambient mode and with the watch unlocked (the lock screen covers the app without stopping - it): until then it waits, and one that was cut short shows again in full. Only an - outcome that showed for its 2 s is forgotten. Several show one after the other. The pending result itself + it): until then it waits, and one that was cut short shows again in full, without its haptic or confetti a second + time. Only an outcome that showed for its 2 s is forgotten. Several show one after the other. The pending result itself takes the outcome in place of the overlay while it is on screen. There is no system notification and nothing runs in the background, so an outcome that arrives while the app is closed is told at the next open. - Never over a payment. The overlay does not cover a screen where it could be taken for something else @@ -461,12 +492,10 @@ in any other state. ### QuickPay -The watch has no QuickPay switch of its own on its screen. The phone sets it: **QuickPay on Watch**, in the phone's -Watch sheet (Pairing › Watch limits), with its own amount per payment in US dollars and its own daily limit, that -amount times a multiplier. It is off until the phone's user turns it on, and it holds only while the phone's own -QuickPay is on too. The watch reads both from the phone's settings, pushed by a paired phone or read from its -settings backup (see Settings sync). The decision follows the rules of the phone's own `QuickPayRepo`, with two -differences that the watch needs, listed below. A send skips the review and the hold, and goes from pricing straight to sending and the +The watch has no QuickPay switch. It follows the phone's: QuickPay on or off, the amount per payment in US dollars +and the daily limit, which is that amount times a multiplier, all read from the phone's settings backup (see +Settings sync). The decision follows the rules of the phone's own `QuickPayRepo`, with two differences that the +watch needs, listed below. A send skips the review and the hold, and goes from pricing straight to sending and the usual result screens, only when every one of these holds: - The wallet is connected and synced (`WalletStatus.Ready`), and no wipe runs. @@ -477,20 +506,16 @@ usual result screens, only when every one of these holds: link's scheme and case change nothing, since the request is what `PaymentsRepo.decoderInput` leaves of it: an uppercase `BITCOIN:` URI with an amount counts like a lowercase one, and an `lnurlp://` link like any LNURL. An amount the wearer typed always gets the review and the hold, and so does a Spark address, which names no amount. -- QuickPay on Watch is on, and so is the phone's own QuickPay, in the settings last imported from the phone. They - count however long ago the import was, as the phone's own settings do on the phone. -- The amount, without the fee, is no more than the lower of the watch's QuickPay amount and the phone's own: the - watch's may be set above the phone's, but the watch never skips the hold for a payment the phone itself would ask - about. As on the phone, that amount is +- QuickPay is on in the settings last imported from the phone. They count however long ago the import was, as the + phone's own settings do on the phone. +- The amount, without the fee, is no more than the phone's QuickPay amount. As on the phone, the QuickPay amount is turned into sats at the dollar rate, rounded half up, and the invoice's sats are compared with that. The invoice's unrounded dollar value is compared with the QuickPay amount too, which is the phone's check when it pays: where the sats rounded up, the last sat is worth a fraction of a cent too much and is reviewed. -- Today's QuickPay payments from this watch, with this one, stay within the watch's own daily limit, and with those a - paired phone last said it made today they stay within the phone's daily limit, the wallet's. The payment counts as its dollar value in cents, rounded half up and at least one cent, as +- Today's QuickPay payments from this watch, with this one, and those a paired phone last said it made today stay + within the daily limit. The payment counts as its dollar value in cents, rounded half up and at least one cent, as on the phone. - The wearer is there: the first of the two differences below. -- The request was not handed over by the paired phone (Pairing › Payment handoff): such a request always ends on the - review and the hold. The rate is the last one the watch fetched, whatever its age: the phone has no age limit on its rates either. The phone keeps its rates across restarts and the watch does not, so when QuickPay is on and no dollar rate is in yet, @@ -520,13 +545,10 @@ The two differences from the phone: (`FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY`), minutes or hours after the wearer saw it. `MainActivity` takes such a launch as a plain one (`isReplayedLaunch`): the app opens on Home and nothing is priced or paid. The check is made where a task is started, `onCreate`, and again in `onNewIntent`, where a link reaches the running app. -- **QuickPay is off until the phone's settings were imported, and turned on for the watch.** The phone has its - settings at hand; the watch has none of its own. So QuickPay is off before the first import, and it is turned off - by an import that finds no backup, a backup that cannot be decrypted or read, one with a newer layout, or QuickPay - values outside what the phone's sliders offer (1 to 50 dollars, 1× to 50×). The watch's own three values are read - the same way: missing, mistyped or out of range, as in the backup of a phone that predates them or of bitkit-ios, - they keep QuickPay off on the watch and leave the phone's values as read. An import that fails, as without a - network, changes nothing. +- **QuickPay is off until the phone's settings were imported.** The phone has its settings at hand; the watch has + none of its own. So QuickPay is off before the first import, and it is turned off by an import that finds no + backup, a backup that cannot be decrypted or read, one with a newer layout, or QuickPay values outside what the + phone's sliders offer (1 to 50 dollars, 1× to 50×). An import that fails, as without a network, changes nothing. Anything that cannot be read answers no, and the wearer holds to pay as without QuickPay: no rate, a settings file or a count that cannot be read. @@ -545,26 +567,21 @@ or a count that cannot be read. applies on the watch from the first import after the phone uploaded its settings. A watch that cannot read the backup, as without a network, and a phone that could not upload it, leave the old settings in force. The Phone settings row shows when they were last imported. -- **Two counts, two limits.** Each device keeps its own count of the day's QuickPay payments. The watch's own count - stays within the watch's daily limit, whatever the phone did. A paired phone and watch also tell each other their - counts and stay together within the phone's daily limit (Pairing › Shared guards). **Known gap:** unpaired, the - watch allows its own daily limit and the phone its own, together up to the sum a day; paired but apart, the two - can go over the phone's limit by what the other spent since they last reached each other. -- **Known limit: a link sent from another app on the phone.** Bitkit's own Pay on Watch never goes out under - QuickPay (Pairing › Payment handoff). Being there is measured as the watch unlocked, the app on screen +- **Two counts, one limit when paired.** Each device keeps its own count of the day's QuickPay payments. A paired + phone and watch tell each other theirs and stay together within the phone's daily limit (Pairing › Shared + guards). **Known gap:** unpaired, each allows the daily limit, together up to twice it a day; paired but apart, + the two can go over it by what the other spent since they last reached each other. +- **Known limit: a link sent from the phone.** Being there is measured as the watch unlocked, the app on screen and out of ambient mode. It is not measured as a look or a touch: the watch has no sensor it could ask. An app on the paired phone can open a `lightning:` link on the watch (`RemoteActivityHelper`) while the wearer looks at the phone. A tapped NFC tag is measured the same way: the tap itself is the wearer's act, and Android reads a tag only with the screen on and the watch unlocked. With the watch on the wrist and unlocked, and the screen lit by the launch, that send counts as attended and goes out under QuickPay with no touch on the watch, as a link from another app on the watch does. It is - bounded by the lower of the watch's and the phone's QuickPay amounts per payment and the watch's daily limit, and - by the two counts above. Whether + bounded by the phone's QuickPay amount per payment and by the daily limit, and by the two counts above. Whether a remote launch lights the screen was not tried on a device. Nothing in V1 tells such a launch from a tap on - the watch; QuickPay on Watch is off until the user turns it on, and turning it off is the way to rule it out. -- **The phone's PIN guards the watch's limits.** The watch has no PIN. Turning QuickPay on for the watch or raising - its amount or daily limit asks for the phone app's PIN or biometric check by the rule of the phone's own QuickPay - settings: while payments need the PIN on the phone (a PIN is set and PIN for payments is on). Turning it off or - lowering a limit never asks (Pairing › Watch limits). + the watch; turning QuickPay off on the phone is the wearer's way to rule it out. +- **Known gap: the phone's payment PIN.** The phone can ask for its PIN before a QuickPay limit is raised; the + watch has no PIN and adopts whatever the phone saved. ## NFC @@ -754,25 +771,14 @@ from VSS and never writes there. `SettingsData` in the phone's `SettingsStore.kt`), stored on VSS under the key `SETTINGS`. The phone uploads it about 5 s after a setting changes. The phone reads a bitkit-ios backup under the same keys, with enums in Swift's form (`BackupJson.kt`), and the watch reads those the same way; no bitkit-ios backup was tried. -- **What the watch adopts.** Nine of those keys, and nothing else: +- **What the watch adopts.** Six of those keys, and nothing else: - `primaryDisplay` (bitcoin or fiat first) and `displayUnit` (`MODERN` for sats, `CLASSIC` for bitcoin with eight decimals). The balance, the send review and result, the paid receive and the activity list and detail are written in that unit; the amount entry of a send stays in sats. - `selectedCurrency`, the fiat currency. - `isQuickPayEnabled`, `quickPayAmount` (US dollars) and `quickPayDailyLimitMultiplier`. - - The watch's own QuickPay, set in the phone's Watch sheet: `isWatchQuickPayEnabled`, `watchQuickPayAmount` (US - dollars) and `watchQuickPayDailyLimitMultiplier`. - - The phone stores no other QuickPay value; none is invented here. -- **The backup's contract across apps and versions.** The watch's three values are plain optional keys of the - phone's `SettingsData` with defaults (off, $5, 5×), so the settings backup carries them with no new version: - `SettingsBackupV1` stays at version 1. An older Android build restores a backup that has them, since it reads the - settings key by key and skips keys it does not know (`decodeSettingsBackup`, `ignoreUnknownKeys`); bitkit-ios's - `JSONDecoder` ignores unknown keys the same way. A backup without them, from an older build or from bitkit-ios, - restores their defaults on the phone, and on the watch keeps QuickPay off. bitkit-ios has no watch app and no Watch - sheet, so it neither writes nor shows them; a wallet restored from an iOS backup has QuickPay on Watch off until - it is turned on from an Android phone. The same goes for `watchInstallPromptSeen`, the install prompt's flag. - `BackupJsonTest` checks both directions on the phone, and `PhoneSettingsParserTest` on the watch. + + The phone stores no other QuickPay value and no watch-specific limit; none is invented here. - **Access.** `VssPhoneBackupReader` sets vss-client up exactly as the phone's `VssBackupClient` and `VssStoreIdProvider` do: the server (`Env.vssServerUrl`), the store id derived from the recovery phrase and passphrase with the prefix `bitkit_v1_` plus the network name, and the LNURL-auth sign-in @@ -780,7 +786,7 @@ from VSS and never writes there. a key from the seed too. Dev and tnet builds use Blocktank's staging servers, as the phone does; the phone's `E2E_VSS_SERVER_URL` override for local backup tests has no counterpart on the watch. - **Kept equal to the phone.** `wear/src/test/resources/phone-backup-contract.json` holds what the watch relies on: - the backup's key, the nine settings in the phone's encoding, and each network's store id prefix and two servers. + the backup's key, the six settings in the phone's encoding, and each network's store id prefix and two servers. The phone's `WatchBackupContractTest` compares it with what the phone app's own serializer writes and with the phone's `Env` for the network it is built for; the watch's `PhoneBackupContractTest` reads the same file with the watch's parser and compares the watch's `Env` for every network. A renamed setting or a moved server fails one of @@ -817,7 +823,7 @@ from VSS and never writes there. up the moment the wallet stops being ready, as on a lock or a pause, whoever started it, and its client is shut down when its HTTP call returns. An import under way when the watch goes ambient or its caller leaves still lands. Reading takes about 2 s; it is given up after 30 s. -- **Outcomes.** A backup that was read replaces the nine values. The phone's `primaryDisplay` is adopted when it +- **Outcomes.** A backup that was read replaces the six values. The phone's `primaryDisplay` is adopted when it differs from the one last imported, so the wearer's own swap on the balance lasts until the phone's setting changes. A display value the backup lacks, or holds in a form the watch cannot read, keeps the watch's. A backup that is missing, cannot be decrypted or decoded, is not the envelope, or has a `version` above 1 keeps the display @@ -879,12 +885,11 @@ that cannot tell refuses the send. The phone app and the watch app can be linked. Pairing does three things: it lets the phone set a watch up by sending it the wallet, it gives the phone a live, authenticated way to push its settings to the watch, and it lets -the phone unpair the watch or erase its wallet. The watch still works without it, by the backup import above. +the phone unpair the watch, which erases its wallet. The watch still works without it, by the backup import above. Part 2 of the pairing work adds the shared guards: the self-send guard's invoice hashes, the QuickPay counts and -the open sends travel both ways (Shared guards, below). Part 3 adds the watch's own QuickPay limits, set on the -phone (Watch limits), a payment handed from the phone to the watch (Payment handoff), the prompt to install the -watch app (Install prompt) and the prompt to pair a watch that has it (Pair prompt). +the open sends travel both ways (Shared guards, below). Part 3 adds the prompt to install the watch app (Install +prompt) and the prompt to pair a watch that has it (Pair prompt). - **Off on mainnet.** `Env.isWatchLinkEnabled` is false on mainnet for as long as the watch app is (#2152). The phone's Watch row is then not shown, the link repository is not created at startup or by Settings, and the @@ -1170,7 +1175,7 @@ for delivery after a reconnect. Each device publishes its three when the pairing other's last count, so the two can together go over the limit by what the other spent since, at most one day's limit. A send the watch made under QuickPay and still watches, cut off inside the call, that the phone then pays under QuickPay after the 5 minutes below, is one payment both count, so the day's shared limit is used twice for - it. That only refuses more, and ends with the day. The watch also holds its own count to its own daily limit (Watch limits). + it. That only refuses more, and ends with the day. - **Open sends: the pending rule.** Before an invoice is sent, the watch (`PaymentsRepo`, before the review and again at the send) and the phone (`SparkRepo.payInvoice`, after its checks of Spark's list and before anything is noted) look up the other's open sends of that payment hash. One that counts refuses the send as pending: the @@ -1237,67 +1242,6 @@ for delivery after a reconnect. Each device publishes its three when the pairing `send-phone-invoice-guard.xml` and `quickpay-shared-daily-limit.xml` over the debug socket, on the local `./spark` stack only (see the note on #2152 in `journeys/wear/README.md`). -### Watch limits - -- **Where.** The phone's Watch sheet has a row **QuickPay on Watch** (`PairedWatchQuickPay`), shown with or without a - paired watch, since the settings backup carries the limits to an unpaired watch too. It opens, in the same sheet, - the switch (`PairedWatchQuickPayToggle`), the amount of one payment (`PairedWatchQuickPayAmount`) and the daily - limit (`PairedWatchQuickPayLimit`), with the sliders and stops of the phone's own QuickPay settings ($1 to $50, 1× - to 50×; stop tags `PairedWatchQuickPayAmountStop-` and `PairedWatchQuickPayLimitStop-`), and - for a paired watch what it spent under QuickPay today (`PairedWatchSpentToday`), its own count of the phone's day - as it last published it. While the phone's QuickPay is off a line says the watch's is off too - (`PairedWatchQuickPayPhoneOff`). -- **Stored.** In the phone's `SettingsData` (`isWatchQuickPayEnabled`, `watchQuickPayAmount`, - `watchQuickPayDailyLimitMultiplier`), so the settings backup carries them; see Settings sync for what older builds - and bitkit-ios do with them. Pushed to a paired watch in `p2w/settings`, three more fields of `SettingsDoc` whose - defaults, as from a phone that predates them, keep QuickPay off on the watch. -- **The PIN.** Turning QuickPay on for the watch or raising one of its limits asks for the phone app's PIN or - biometric check while payments need the PIN (`SettingsData.requiresPaymentAuth`: a PIN is set and PIN for payments - is on), the same rule as the phone's own QuickPay settings and through their queue - (`QuickPayRepo.requestSettingsChange`): the check opens over the sheet and only its success saves the change. - Turning it off or lowering a limit saves at once, and so does any change while payments need no PIN. -- **On the watch** (`QuickPayRepo`): QuickPay holds only while it is on for the watch and on the phone; one payment - is held to the lower of the watch's amount and the phone's, and the day's payments to the watch's own daily limit for its own count and to the - phone's daily limit for its count with the phone's (`QuickPaySpendStore.reserve`, `ownCapCents`). -- **Defaults.** Off, $5 and 5×. A watch that was paired before part 3 follows the phone's QuickPay no longer: its - QuickPay is off until the user turns it on for the watch. - -### Payment handoff - -On the phone's send review, a BOLT11 invoice that carries its amount and that the wallet pays over Lightning, while -the paired watch is reachable, offers **Pay on Watch** (`SendPayOnWatch`), a small secondary button above the -details (`payOnWatchInput`, which reads the review's decoded invoice). An invoice without an amount does not: only -the invoice is handed over, so the amount typed on the phone would be lost and the watch would ask for it again. -Nor do LNURL, a contact's payment request or one that goes over a Spark leg or a swap, a subscription and a hardware -wallet's send. A tap hands the request to the watch, which reviews it and asks -for its hold to pay; the phone's swipe stays, and the phone shows one line (`SendPayOnWatchResult`): "Sent to your -watch. Hold to pay there.", "Your watch is busy with another payment.", "Your watch couldn't take this payment." or -"Your watch is not reachable." - -1. **The request** goes over the link as a one-shot message, `p2w/pay` (`PayRequestDoc`: a random 16-byte id and - the invoice as the phone read it), in the envelope, so it is authenticated, encrypted and never stored by the - carrier. A watch that is away fails it at once. -2. **The watch** (`PhoneLinkRepo.onPayRequest`) takes only a BOLT11 invoice that carries its amount, with or without - the `lightning:` scheme (`HandoffStore.lightningLink`, which reads the invoice's human-readable part: mainnet, - testnet, signet or regtest, and an amount). It refuses everything else, as an invoice without an amount, an - LNURL, a Lightning address or another scheme, and anything without a wallet; answers busy while a send is under way; and otherwise keeps it in memory (`HandoffStore`, over - `:wearlink`'s `HandoffInbox`) and answers `w2p/pay` received. It takes a request once, only within 60 s of its - arrival, and remembers the last 20 ids; the counters of the envelope already refuse a replay. -3. **The link.** A listener service may not start an activity on Wear OS, so the phone then opens - `bitkitwear://pay?id=` on the watch (`RemoteActivityHelper`). The link carries the id alone, so any app may - send it: without the request that arrived over the link it opens nothing. -4. **On the watch** `LaunchGate` takes the request by its id and opens the existing Send flow with it. The flow ends - on the review and the hold whatever QuickPay says (`SendViewModel`, `Routes.SEND_HANDOFF`): the wearer did not - start it on the watch. A request the watch kept and then drops is answered again, which turns the phone's line - while the phone still listens, 60 s: busy for a send under way (`LaunchGate.admit`, and the screens' own check - of a send that started a frame before, `LaunchGate.onDrop`), and refused where nothing can show it, as outside - Home during the restore or on the Wallet removed notice. -5. **The phone's line** follows the answer: received and the link opened reads sent; busy reads busy; a refusal, - at once or later, reads "Your watch couldn't take this payment."; no answer within 10 s, a watch that is away - and a link that cannot be opened read not reachable. - -Not logged: the invoice. The apps log the answer. - ### Install prompt A timed sheet (`docs/timed-sheets.md`), `WatchInstallTimedSheet`, shown once from Home when a connected watch has @@ -1343,10 +1287,11 @@ When it shows again: ### Unpair, erase and wipe -- **Unpair from the phone.** The phone publishes "revoked" and marks its record. The watch forgets the phone, - deletes its link keys and answers; the phone then deletes its record and keys. The wallet stays on the watch. -- **Erase from the phone.** The phone publishes "erase" and keeps that command stored until the watch - acknowledges. The watch first writes the wipe's note to disk (`WalletRepo.noteEraseByPhone`), then acknowledges +- **Unpair from the phone** unpairs the watch and erases its wallet: the phone's Watch sheet offers no unpair that + leaves the wallet on the watch, so a watch handed on or lost does not keep a wallet the phone forgot. It asks first + (`PairedWatchUnpair`, then the dialog's Unpair). The phone publishes "erase" and keeps that command stored until + the watch acknowledges. A command that cannot be stored (a Data Layer write that fails) leaves the watch paired + as before, with an error toast, so the Unpair can be tried again. The watch first writes the wipe's note to disk (`WalletRepo.noteEraseByPhone`), then acknowledges while its keys still exist, then runs the wallet's own wipe (`WalletRepo.eraseByPhone`), which leaves the Wallet removed notice and takes the pairing's record with the settings. From the note on, the wipe is finished when the app's process next starts at the latest, whatever starts it (`PhoneLinkRepo` runs `WalletRepo.recover` at its @@ -1387,14 +1332,14 @@ with the watch it offered, as if Pair Watch had been tapped: - **Transfer and end.** "Sending your wallet…" (`PairedWatchPairSending`), then `PairedWatchPairDone` or one line (`PairedWatchPairError`), each with OK (`PairedWatchPairClose`), which returns to the watch's state. A phone without a PIN gets its line here: "Set a PIN in Bitkit first, then pair your watch." -- **QuickPay on Watch** (`PairedWatchQuickPay`), in the two states above and below: see Watch limits. A watch - without Bitkit gets Install on Watch (`PairedWatchInstall`) instead of Pair. +- **Install.** A watch without Bitkit gets Install on Watch (`PairedWatchInstall`) instead of Pair. - **Paired watch.** Its name (`PairedWatchName`), "holds your full wallet" (`PairedWatchFullWallet`), its key's - verdict (`PairedWatchKeyLevel`), the settings state (`PairedWatchSettingsState`), Unpair (`PairedWatchUnpair`), - OK (`PairedWatchClose`) and Unpair and Erase Watch (`PairedWatchErase`), each removal behind a dialog + verdict (`PairedWatchKeyLevel`), the settings state (`PairedWatchSettingsState`) and one button, Unpair + (`PairedWatchUnpair`), which unpairs the watch and erases its wallet, behind a dialog that says so (`DialogConfirm`, `DialogCancel`); or a pending removal (`PairedWatchRemovePending`, `PairedWatchStopWaiting`). - A watch whose secure hardware was not verified shows a plain shield instead of the checked one. A dialog stays - open while the watch's reports rewrite its record, and closes when that watch is gone. + It shows the watch icon, as the unpaired sheet does; the key's verdict line says whether the watch's secure + hardware was verified. A dialog stays open while the watch's reports rewrite its record, and closes when that + watch is gone. Closing the sheet cancels a pairing under way, at any step, except while the wallet is on its way to the watch: that transfer is left to finish, so the two devices agree on how it ended, and the sheet shows it again when @@ -1402,10 +1347,15 @@ reopened: still sending, the line that says why it failed, or the paired watch. The phone's tags start with `PairedWatch` because the watch app's own start with `Watch`. +Where the sheet, the Pair prompt and the install prompt would show the 3D phone illustration, and on the paired +watch's sheet, they show the watch icon (`ic_watch`) instead, enlarged and centred in the illustration's place, in +Brand orange, all through `SheetIntroIcon`: no 3D watch illustration exists. The other steps keep their +illustrations (hourglass, keyring, transfer, check, cross). + Watch: -- **Onboarding** (`OnboardingScreen`): the Bitkit mark (`WatchOnboardingLogo`), the phone icon with "Start on - phone" (`WatchOnboardingStartOnPhone`), which is text and no button, and Restore (`WatchOnboardingRestore`). +- **Onboarding** (`OnboardingScreen`): the Bitkit mark (`WatchOnboardingLogo`) and Restore + (`WatchOnboardingRestore`), nothing else: pairing starts on the phone. - **Pair** (`PairScreen`, `WatchPairScreen`): "Connecting…" (`WatchPairWaiting`) while it waits for the phone's hello, then the phone's name (`WatchPairPhone`), the code (`WatchPairCode`) and one `EdgeButton` that says "Match" (`WatchPairConfirm`), then @@ -1458,16 +1408,6 @@ Watch: reconnect (Shared guards). A send started on both within the moment it takes a document to cross is refused by neither, and neither is one started more than 5 minutes after the other's that Spark never listed; Spark's shared idempotency key for an invoice still pays it once. -- A handed-off request that the watch kept and then dropped, for a send under way or outside Home, turns the - phone's line to busy or refused only while the phone still listens, 60 s, and only when the watch's later answer - reaches the phone. The phone still shows "Sent" for a request that opens nothing on the watch when the watch's app - never sees the link in time: a link Wear OS did not deliver or a remote launch it ignored, and a link that arrives - more than 60 s after the request. Nothing is paid in any of these: the request is only ever paid by the hold on the - watch. -- **Unreleased version skew.** A watch still on a part 2 build, paired with a phone on part 3, does not know the - three watch keys: it ignores QuickPay on Watch and follows the phone's own QuickPay as before, also while QuickPay - on Watch is off. No such build was released (the link is off on mainnet), so the two parts ship together and no - compatibility code exists for it. - The install prompt opens a Play listing that has no watch build until #2152 is resolved. - A watch that never receives the phone's `bitkitwear://pair` link, as when Wear OS ignores the remote launch, cannot be paired: it has no button of its own to open the Pair screen any more. The phone's pairing then ends diff --git a/journeys/README.md b/journeys/README.md index f06c6d7799..b927739b5c 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -140,7 +140,7 @@ journey PR, which is what made this file conflict on every merge. | A watch to run the Wear OS app on | a Wear OS watch emulator (`Wear_Large_Round_API37`, `Wear_Small_Round_API34`), or a physical watch over Wi-Fi debugging — [wear](wear/README.md) | | Watch gestures: pager swipes, swipe-to-dismiss, rotary crown, ambient mode | `adb shell input swipe`, `adb shell input rotaryencoder scroll --axis SCROLL,` and `KEYCODE_SLEEP`/`KEYCODE_WAKEUP` on the emulator; the real crown, bezel and wrist on a physical watch — [wear](wear/README.md#watch-gestures) | | The phone's settings on the watch (units, currency, QuickPay) | a phone dev build with the same private settings wallet (the test phrase with a passphrase kept on this machine), never the public test phrase alone, writes them to the hosted staging VSS, and the watch imports them; nothing runs locally — [wear](wear/README.md#phone-settings-on-vss) | -| A phone and a watch that reach each other, for pairing and, on the local `./spark` stack only, the shared guards, the watch limits and Pay on Watch | a phone emulator (`Bitkit_Phone_API36`) and a watch emulator with debug builds of both apps, joined by the debug socket carrier over `adb forward` and `adb reverse`; the Wear Data Layer itself, the watch's hardware Keystore and its attestation, and so a release-build seed transfer, the remote launch of Pay on Watch and the install prompt's Play listing, are not covered — [wear](wear/README.md#phone-and-watch-over-the-debug-socket) | +| A phone and a watch that reach each other, for pairing and, on the local `./spark` stack only, the shared guards | a phone emulator (`Bitkit_Phone_API36`) and a watch emulator with debug builds of both apps, joined by the debug socket carrier over `adb forward` and `adb reverse`; the Wear Data Layer itself, the watch's hardware Keystore and its attestation, and so a release-build seed transfer and the install prompt's Play listing, are not covered — [wear](wear/README.md#phone-and-watch-over-the-debug-socket) | | Typing on the watch keyboard | `adb shell input text` after closing the Wear OS keyboard with Back, which otherwise swallows the input — [wear](wear/README.md#typing) | ## Cross-platform @@ -221,8 +221,7 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691): | `settings/quickpay-payment-pin.xml` | same file and steps, paired with synonymdev/bitkit-ios#1326 — on iOS the PIN pad is a sheet whose back control is `NavigationBack`, and a failed biometric check counts as not approved instead of falling back to the PIN pad | | — | `hardware-wallet/transfer-to-spending-over-max.xml` exists only on iOS | | `wear/*` | not ported — Android only for now; bitkit-ios has no watch app yet, and the watch journeys port with that follow-up | -| `settings/watch-quickpay-pin.xml` | not ported — Android only for now; bitkit-ios has no watch app, so no QuickPay on Watch | -| `settings/watch-no-watch-connected.xml` | not ported — Android only for now; bitkit-ios has no watch pairing. The phone's pairing tags are `PairedWatch…`, since the watch app's own start with `Watch…`; an iOS twin takes the same names. The send review's Pay on Watch (`SendPayOnWatch`, `SendPayOnWatchResult`), the install prompt (`WatchInstallSheet`, `WatchInstallConfirm`, `WatchInstallLater`) and the pair prompt (`PairedWatchPrompt`, `PairedWatchPromptPair`, `PairedWatchPromptLater`) are Android only for the same reason | +| `settings/watch-no-watch-connected.xml` | not ported — Android only for now; bitkit-ios has no watch pairing. The phone's pairing tags are `PairedWatch…`, since the watch app's own start with `Watch…`; an iOS twin takes the same names. The install prompt (`WatchInstallSheet`, `WatchInstallConfirm`, `WatchInstallLater`) and the pair prompt (`PairedWatchPrompt`, `PairedWatchPromptPair`, `PairedWatchPromptLater`) are Android only for the same reason | ### Running one on iOS diff --git a/journeys/settings/watch-no-watch-connected.xml b/journeys/settings/watch-no-watch-connected.xml index 0bbc5705a2..b67956f830 100644 --- a/journeys/settings/watch-no-watch-connected.xml +++ b/journeys/settings/watch-no-watch-connected.xml @@ -13,6 +13,7 @@ On the General tab, scroll to Watch (tag "PairedWatchSettings") and verify its value reads "Not paired" Tap "PairedWatchSettings" and verify the Watch sheet opens: "PairedWatchStatus" is listed Wait up to 10 s until "PairedWatchStatus" reads "No watch connected. Connect a Wear OS watch to this phone first." + Verify from a screenshot that the sheet shows a large orange watch icon centred above Pair Watch, not the 3D phone illustration Tap Pair Watch (tag "PairedWatchPair") and verify nothing starts: "PairedWatchPairConnecting" is not listed Press Back and verify the sheet closes: "PairedWatchStatus" is not listed and "PairedWatchSettings" is diff --git a/journeys/settings/watch-quickpay-pin.xml b/journeys/settings/watch-quickpay-pin.xml deleted file mode 100644 index cbb9058e20..0000000000 --- a/journeys/settings/watch-quickpay-pin.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - The watch's own QuickPay, set in the phone's Watch sheet (docs/wear.md › Pairing › Watch limits), follows the - PIN rule of the phone's own QuickPay settings (quickpay-payment-pin.xml): while payments need the PIN, turning it - on or raising a limit asks for the PIN before anything is saved, and turning it off or lowering a limit never - asks; while payments need no PIN, nothing asks. Back, and the sheet's back arrow, leave the QuickPay view for - the watch view and keep the sheet open; over an open PIN check, Back closes the check alone. One phone emulator; - the QuickPay on Watch row is there with or without a paired watch. Android only: bitkit-ios has no watch app yet. - - Precondition: a dev build with a wallet, on Home, with PIN 1111 set and Require PIN for payments on (Settings › - Security, tag "EnablePinForPayments"), no biometrics enrolled on the device, and QuickPay on Watch off at its - defaults, $5 and 5×. The PIN pad is drawn over the sheet and reads "Please enter your PIN code to confirm this - QuickPay change." Never enter a wrong PIN more than once. - - - Open Settings from the drawer (tag "HeaderMenu", then "DrawerSettings"), tap Watch (tag "PairedWatchSettings") on the General tab and then "PairedWatchQuickPay"; verify "PairedWatchQuickPayToggle" is listed and reads off - Tap "PairedWatchQuickPayToggle" and wait up to 5 s until the PIN pad is listed with its QuickPay text; a switch that turns on without it fails this step. Press Back - Verify the PIN pad is gone and "PairedWatchQuickPayToggle" is still listed and reads off: Back closed the check alone, and nothing was saved - Tap "PairedWatchQuickPayToggle", wait up to 5 s until the PIN pad is listed, enter 1111 and verify the PIN pad is gone and the switch reads on - Tap "PairedWatchQuickPayAmountStop-20", wait up to 5 s until the PIN pad is listed, enter 1111 and verify a text starting with "Payments up to $20 on your watch" is listed - Tap "PairedWatchQuickPayAmountStop-1" and verify, for 3 s, that no PIN pad is listed, and that a text starting with "Payments up to $1 on your watch" is listed: lowering never asks - Tap "PairedWatchQuickPayToggle" and verify, for 3 s, that no PIN pad is listed, and that the switch reads off: turning it off never asks - Press Back and verify the watch view shows in the same sheet: "PairedWatchQuickPay" and one of "PairedWatchStatus" or "PairedWatchName" are listed, and "PairedWatchQuickPayToggle" is not - Tap "PairedWatchQuickPay", then the sheet's back arrow (tag "NavigationBack"), and verify the same: "PairedWatchQuickPay" is listed and "PairedWatchQuickPayToggle" is not - Press Back and verify the sheet closes: "PairedWatchQuickPay" is not listed and "PairedWatchSettings" is - On the Security tab (tag "Tab-security") tap "EnablePinForPayments", enter 1111 and verify it reads off; back on the General tab (tag "Tab-general") tap "PairedWatchSettings" and "PairedWatchQuickPay" - Tap "PairedWatchQuickPayToggle" and verify, for 3 s, that no PIN pad is listed, and that the switch reads on: while payments need no PIN, the watch's QuickPay asks none, as the phone's own - - diff --git a/journeys/wear/README.md b/journeys/wear/README.md index b30d4c8726..c7c969410f 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -24,6 +24,18 @@ What `android layout` misses on the watch, verified on the API 37 emulator: - **Screens with `FLAG_SECURE`.** The word, passphrase and Pair screens block screenshots and screen recordings in release builds only, as on the phone; debug builds capture them. Never capture the word or passphrase screens with a recovery phrase on them. +- **The confetti.** `WatchConfetti`, the canvas the confetti of a success falls on for 2 s, has no text or action, + and no screen dump catches it: `uiautomator dump`, and `android layout` with it, waits for the screen to go idle, + and the falling confetti keeps it busy, so the dump lands once the confetti has ended, and on the Sent screen, + which closes 2 s after it shows, often once the screen has closed too (seen on the API 37 emulator). Check the log + instead: the watch logs one debug line as a celebration starts, `[Confetti] Showed the success celebration for + ''`, the key being the paid payment's id on Receive, `sent` on a send's flow and the outcome's id on a send result shown + outside it. A journey clears the log with + `adb logcat -c` before the payment, then checks `adb logcat -d -s BitkitWear | grep "Showed the success + celebration"`: one line where the confetti plays, none in ambient mode or after a wake. A send's Sent screen is + checked from the log too, by "Finished send with outcome 'Sent'". The one screenshot of the confetti, for the + colours, comes from one `adb shell` loop that runs on the watch, polls the log for that line and runs `screencap` + the moment it appears. A dump taken after the 2 s shows that the confetti is gone. ## Emulators @@ -141,8 +153,6 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou | `quickpay-off-holds.xml` | as `quickpay-skips-hold.xml`, after it | yes, 2 000 sats | | `send-phone-invoice-guard.xml` | local only, phone and watch paired over the debug socket ([Two apps on one wallet](#two-apps-on-one-wallet)) | no | | `quickpay-shared-daily-limit.xml` | local only, phone and watch paired over the debug socket ([Two apps on one wallet](#two-apps-on-one-wallet)) | yes, 20 000 sats | -| `pay-request-from-phone.xml` | local only, phone and watch paired over the debug socket ([Two apps on one wallet](#two-apps-on-one-wallet)) | yes, 5 000 sats | -| `quickpay-watch-limit.xml` | local only, phone and watch paired over the debug socket ([Two apps on one wallet](#two-apps-on-one-wallet)) | yes, 5 000 sats | The six settings journeys read the phone's settings backup from Blocktank's hosted staging VSS, which every dev build uses whatever its Spark network is: a watch on the local `./spark` stack reads the same backup as one on hosted @@ -233,8 +243,7 @@ adb shell pm clear to.bitkit.dev adb shell am start -n to.bitkit.dev/to.bitkit.wear.ui.MainActivity ``` -`android layout` lists `WatchOnboardingLogo`, `WatchOnboardingStartOnPhone` ("Start on phone") and -`WatchOnboardingRestore`. +`android layout` lists `WatchOnboardingLogo` and `WatchOnboardingRestore`, and nothing else. ### Restored wallet @@ -358,14 +367,6 @@ names this precondition: - QuickPay (`QuickpaySettings`, past `QuickpayIntro-button` the first time): the switch (`QuickpayToggle`), the amount (`QuickpayAmountSlider`, stops $1 to $50) and the daily limit (`QuickpayDailyLimitSlider`, 1× to 50×). Tap the slider track above a stop's label, as in `settings/quickpay-payment-pin.xml`. - - QuickPay on Watch: the watch's own QuickPay is off until the phone turns it on, and holds only while the - phone's QuickPay is on too (docs/wear.md › QuickPay). In Settings › General › Watch (`PairedWatchSettings`), tap - `PairedWatchQuickPay`, then the switch (`PairedWatchQuickPayToggle`), the amount and the daily limit by their - stops (`PairedWatchQuickPayAmountStop-`, `PairedWatchQuickPayLimitStop-`). The row is - there with or without a paired watch, since the backup carries the values. Turning it on or raising a limit - asks for the phone's PIN only while payments need it (Settings › Security › Require PIN for payments, - `EnablePinForPayments`), as the phone's own QuickPay settings do. The QuickPay journeys set it to the phone's own values unless - they say otherwise. 4. Keep the phone app open and online for 20 s: it uploads the settings about 5 s after the last change. Settings › Security › Data Backups (`BackupSettings`) lists Settings with the time of its last backup. 5. Close the phone app (`adb shell am force-stop to.bitkit.dev` on the phone). The phone and the watch must never be @@ -473,8 +474,8 @@ keep: - **The `pair-*.xml` journeys** use a wallet created in the phone's onboarding for the run, with no funds, and make no payment. Wipe both apps when the run is over ([Fresh app](#fresh-app)). -- **The shared-guard and part 3 journeys** (`send-phone-invoice-guard.xml`, `quickpay-shared-daily-limit.xml`, - `pay-request-from-phone.xml`, `quickpay-watch-limit.xml`) receive and pay on both devices, so they run **only on the local `./spark` stack, with throwaway funds**: the watch as in +- **The two shared-guard journeys** (`send-phone-invoice-guard.xml`, `quickpay-shared-daily-limit.xml`) receive and + pay on both devices, so they run **only on the local `./spark` stack, with throwaway funds**: the watch as in [Local ./spark stack](#local-spark-stack), the phone as in the `spark-regtest` skill (`.claude/plugins/spark-regtest`), with the same `SPARK_LOCAL_CONFIG_B64`. Never run them on hosted regtest or any other Spark network. Build both apps for the local stack before the first pairing journey of the chain, so @@ -485,7 +486,7 @@ keep: wallet: `../bitkit-docker/spark down`, then `up`, and [Fresh app](#fresh-app) on both devices. The pairing these journeys need is one wallet on both devices, paired: `pair-receive-wallet.xml` alone leaves -that, and so does `pair-same-wallet.xml` after it and `pair-unpair-from-phone.xml`. +that, and so does `pair-same-wallet.xml` after it and `pair-unpair-from-watch.xml`. ### Restart @@ -911,8 +912,8 @@ builds (`assembleDevRelease` of both apps with a local keystore). - 3g. With the watch app closed and the watch on onboarding before tapping Pair: the watch app opens on its Pair screen above onboarding. 4. **Different wallet.** Restore another wallet on the watch and pair: both say "different wallet". -5. **Erase a watch that is away.** Paired, close the watch app and lock the watch. On the phone tap Unpair and - Erase Watch. +5. **Unpair a watch that is away.** Paired, close the watch app and lock the watch. On the phone tap Unpair, which + also erases the watch's wallet. - Expected: within seconds the watch's wallet is gone; opening the app shows Wallet removed; the phone's row reads Not paired. - 5a. With the watch switched off: the phone shows the pending removal; switch the watch on and it erases @@ -941,19 +942,7 @@ builds (`assembleDevRelease` of both apps with a local keystore). - 10c. With the watch out of range, make an invoice on the watch and open it on the phone: the phone pays it while the two are apart (known gap); back in range and after a few seconds, a second watch invoice is refused. - Not run yet. -11. **Pay on Watch over the Data Layer.** Paired as in test 2, on the local `./spark` stack with throwaway funds - ([Two apps on one wallet](#two-apps-on-one-wallet)). Open an invoice on the phone and tap Pay on Watch on its - review. - - Expected: the watch app comes to the front by itself on the review with the hold, also with the app closed - and the screen off before; the phone reads "Sent to your watch. Hold to pay there." Note whether the remote - launch lights the screen and whether it needs the watch unlocked. - - 11a. With a payment sending on the watch: the phone reads "Your watch is busy with another payment.", and the - watch's send screen stays. - - 11b. With the watch out of Bluetooth range or switched off: Pay on Watch is not offered on a review opened - then; on one already open, a tap reads "Your watch is not reachable." - - 11c. With the watch connected only through the cloud (Wi-Fi, phone's Bluetooth off): note whether the - request and the remote launch arrive. - - Not run yet. +11. Retired: Pay on Watch was removed from the phone. 12. **Install prompt.** A phone with a wallet and a connected watch without Bitkit, whose listing has a watch build (internal testing at least; none exists until #2152 is resolved). Open the phone app on Home. - Expected: within a few seconds "Bitkit on Your Watch" (`WatchInstallSheet`); Install opens Bitkit's Play @@ -963,9 +952,7 @@ builds (`assembleDevRelease` of both apps with a local keystore). - 12a. A watch with Bitkit, or no watch: no install sheet (a watch with Bitkit gets the pair prompt, test 14). A mainnet build: no sheet. - Not run yet. -13. **Watch limits reach a watch that is away.** Paired, with the watch out of range, lower the watch's QuickPay - amount on the phone: "Settings not on watch yet"; back in range the watch holds a payment above the new amount - without either app being opened. Not run yet. +13. Retired: the watch has no QuickPay limits of its own any more. 14. **Pair prompt over the Data Layer.** A phone with a wallet and a PIN, no paired watch, and a connected watch with Bitkit, whose prompt was never shown (a phone app on a fresh install). Open the phone app on Home. - Expected: within a few seconds "Pair Your Watch" (`PairedWatchPrompt`); Pair opens the Watch sheet on the diff --git a/journeys/wear/activity-list.xml b/journeys/wear/activity-list.xml index 80116eaadb..b28809e52f 100644 --- a/journeys/wear/activity-list.xml +++ b/journeys/wear/activity-list.xml @@ -1,7 +1,10 @@ - The Activity page, after Receive, lists the newest payments with a direction icon, the amount and how long ago; - a tap opens the detail with the amount, the fee of a send, the time and the status. Emulator and physical watch. + The Activity page, after Receive, lists the newest payments with the phone's activity icon (a purple arrow on a + purple circle), the amount and the time as the phone's activity writes it (the time alone today); a tap opens the + detail with the amount, the fee of a send, the payment's note when it has one, the day and time and the status, + in the middle of the screen while it fits, else in a list that scrolls. + Emulator and physical watch. Precondition: Restored wallet on the local ./spark stack after receive-paid.xml and send-deeplink-bolt11.xml, so the newest payment is the 1 000 sat send, see journeys/wear/README.md › Local ./spark stack, on the Balance page @@ -11,14 +14,21 @@ Swipe the pager left to Receive: `adb shell input swipe 400 227 60 227 300` Swipe the pager left to Activity: `adb shell input swipe 400 227 60 227 300` Wait up to 10 s until "WatchActivityItem-0" is listed - Verify "WatchActivityItem-0" shows "- ₿ 1 000" - Verify "WatchActivityItem-0" shows a relative time such as "1 min. ago" - Verify "WatchActivityItem-1" shows "+ ₿ 50 000" - Tap "WatchActivityItem-0" + Verify "WatchActivityItem-0", the newest row, shows "- ₿ 1 000", and note it as <send> + Verify <send> shows the payment's time alone, such as "3:04 PM" (or "15:04" with the watch set to 24 hours), and no "ago" + Find the row that shows "+ ₿ 50 000", scrolling down with `adb shell input swipe 227 380 227 120 300` until it is listed, and note its "WatchActivityItem-N" tag as <receive>: rows are found by what they show, since an earlier rerun of a send journey adds rows above it + Verify from a screenshot that each row's icon is a purple arrow on a purple circle, up for the send and down for the receive + Scroll back up with `adb shell input swipe 227 120 227 380 300` until <send> is listed + Tap <send> Verify "WatchActivityDetailAmount" reads "1 000" Verify "WatchActivityDetailStatus" reads "Completed" - Verify "WatchActivityDetailTime" shows today's date + Verify "WatchActivityDetailTime" shows today's day and the time, such as "November 29, 3:04 PM" + Verify "WatchActivityDetailMessage" reads "Coffee", the description of the invoice send-deeplink-bolt11.xml paid + Swipe to dismiss from the left edge: `adb shell input swipe 20 227 400 227 300` + Verify <send> is listed again + Find <receive> as above and tap it + Verify "WatchActivityDetailStatus" reads "Completed" and "WatchActivityDetailMessage" is not listed: the receive's invoice has no description + Verify the detail sits in the middle of the screen: the middle of the top of "WatchActivityDetailAmount" and the bottom of "WatchActivityDetailStatus" is within 20 px of y 227 Swipe to dismiss from the left edge: `adb shell input swipe 20 227 400 227 300` - Verify "WatchActivityItem-0" is listed again diff --git a/journeys/wear/nfc-pay-background.xml b/journeys/wear/nfc-pay-background.xml index 535f2d4003..5db68b27ea 100644 --- a/journeys/wear/nfc-pay-background.xml +++ b/journeys/wear/nfc-pay-background.xml @@ -25,8 +25,9 @@ Verify "WatchSendAmount" reads "1 000" Run `adb logcat -d -s BitkitWear | grep -c "Dropped a repeat of an NFC tap"` and verify it prints 1: the repeat opened no second flow Hold "WatchSendHold" for 2 s as in README › Holding to pay - Wait up to 15 s until "WatchSendSent" is listed - Verify "WatchSendResultAmount" reads "1 000" + Run `adb shell 'for i in $(seq 150); do logcat -d -s BitkitWear | grep -q "Showed the success celebration" && break; sleep 0.1; done; screencap -p /sdcard/sent.png'`, which waits on the watch up to about 15 s for the celebration's log line and takes a screenshot as soon as it appears, since the screen closes 2 s after it shows and its confetti keeps a dump waiting past that (README › The confetti) + Run `adb logcat -d -s BitkitWear | grep -oE "Finished send with outcome '[^']*'|Showed the success celebration for '[^']*'"` and verify it prints "Finished send with outcome 'Sent'" and "Showed the success celebration for 'sent'": the send went out and the confetti started + Run `adb pull /sdcard/sent.png && adb shell rm /sdcard/sent.png` and verify from sent.png, the screenshot the step above took, that it shows the check, "Sent" and "1 000" Wait up to 6 s until "WatchHomeBalance" is listed: the flow closed by itself on the Balance page diff --git a/journeys/wear/pair-erase-from-phone.xml b/journeys/wear/pair-erase-from-phone.xml deleted file mode 100644 index 32900357dd..0000000000 --- a/journeys/wear/pair-erase-from-phone.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - Unpair and Erase on the phone deletes the wallet from the paired watch: the watch shows Wallet removed, then - onboarding, and its encrypted seed is gone. With the watch app open; an erase that reaches a closed app or a - locked watch needs the Data Layer (manual test 5 in journeys/wear/README.md › Manual tests for pairing). Two - emulators over the debug socket. - - Precondition: journeys/wear/README.md › Phone and watch over the debug socket, paired. Watch: on the Balance - page. Phone: on Home. The journey leaves no wallet on the watch. - - - Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists one file - On the phone, open Settings and tap Watch (tag "PairedWatchSettings") - Tap Unpair and Erase Watch (tag "PairedWatchErase") - Verify the dialog says a watch that never reconnects keeps the wallet, then tap Erase (tag "DialogConfirm") - Wait up to 15 s until the watch lists "WalletRemovedTitle" - Verify the phone lists "PairedWatchPair" and no "PairedWatchName" - On the watch, tap OK (tag "WalletRemovedConfirm") and verify "WatchOnboardingRestore" is listed - Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists no seed file - Restart the watch app (README › Restart) and verify "WatchOnboardingRestore" is listed again - - diff --git a/journeys/wear/pair-prompt.xml b/journeys/wear/pair-prompt.xml index 3f6aace794..12874ea046 100644 --- a/journeys/wear/pair-prompt.xml +++ b/journeys/wear/pair-prompt.xml @@ -14,9 +14,10 @@ Timing: a pairing lasts at most 90 s from the prompt's Pair tap; read each screen once and move on. - Verify the watch lists "WatchOnboardingRestore", "WatchOnboardingStartOnPhone" reading "Start on phone", and no "WatchOnboardingFromPhone" + Verify the watch lists "WatchOnboardingLogo" and "WatchOnboardingRestore", and no "WatchOnboardingFromPhone" or "WatchOnboardingStartOnPhone" Start the phone app and unlock it with the PIN: tap "N1" four times Wait up to 15 s on Home until the phone lists "PairedWatchPrompt" with "PairedWatchPromptPair" and "PairedWatchPromptLater" + Verify from a screenshot that the prompt shows a large orange watch icon centred above its title, not the 3D phone illustration Tap Pair (tag "PairedWatchPromptPair") Wait up to 10 s until the watch lists "WatchPairScreen": the phone opened the Pair screen above onboarding Wait up to 15 s until the phone lists "PairedWatchCode" and note its six digits diff --git a/journeys/wear/pair-receive-wallet.xml b/journeys/wear/pair-receive-wallet.xml index 45cfe85a36..ec87edea18 100644 --- a/journeys/wear/pair-receive-wallet.xml +++ b/journeys/wear/pair-receive-wallet.xml @@ -13,7 +13,7 @@ Wait 3 s on the phone's Home; if it then lists "PairedWatchPrompt" (README › Phone and watch over the debug socket, The Pair prompt), tap Later (tag "PairedWatchPromptLater") - Verify the watch lists "WatchOnboardingRestore", "WatchOnboardingStartOnPhone" reading "Start on phone", and no button that starts a pairing ("WatchOnboardingFromPhone" is not listed) + Verify the watch lists "WatchOnboardingLogo" and "WatchOnboardingRestore", no "WatchOnboardingStartOnPhone", and no button that starts a pairing ("WatchOnboardingFromPhone" is not listed) On the phone, open Settings and tap Watch (tag "PairedWatchSettings") Wait up to 10 s until "PairedWatchStatus" names the watch as ready to pair (the sheet looks again every 3 s), then tap "PairedWatchPair" Wait up to 10 s until the watch lists "WatchPairScreen": the phone opened the Pair screen above onboarding diff --git a/journeys/wear/pair-same-wallet.xml b/journeys/wear/pair-same-wallet.xml index d757b772ec..90c2797950 100644 --- a/journeys/wear/pair-same-wallet.xml +++ b/journeys/wear/pair-same-wallet.xml @@ -4,7 +4,7 @@ about sending the wallet, and the watch stays on its wallet. Two emulators over the debug socket. Precondition: journeys/wear/README.md › Phone and watch over the debug socket. The watch holds the phone's - wallet and is not paired: run pair-receive-wallet.xml, then pair-unpair-from-phone.xml. Watch: on the Balance + wallet and is not paired: run pair-receive-wallet.xml, then pair-unpair-from-watch.xml (an unpair from the phone erases the watch). Watch: on the Balance page. Phone: on Home. diff --git a/journeys/wear/pair-settings-push.xml b/journeys/wear/pair-settings-push.xml index 405fe4c98b..a574478b62 100644 --- a/journeys/wear/pair-settings-push.xml +++ b/journeys/wear/pair-settings-push.xml @@ -13,7 +13,7 @@ Tap EUR in the list Wait up to 10 s until `adb -s $WATCH logcat -d -s BitkitWear` lists "Applied the settings the phone pushed" On the phone, go back to Settings and tap Watch (tag "PairedWatchSettings") - Verify "PairedWatchSettingsState" reads "Watch settings up to date.", then tap OK (tag "PairedWatchClose") + Verify "PairedWatchSettingsState" reads "Watch settings up to date.", then close the sheet with the system Back On the watch, tap "WatchHomeBalanceToggle" until "WatchHomeBalanceSymbol" is a fiat symbol, and verify it reads "€" On the phone, set Local Currency back to USD Wait up to 10 s until "WatchHomeBalanceSymbol" on the watch reads "$" diff --git a/journeys/wear/pair-unpair-from-phone.xml b/journeys/wear/pair-unpair-from-phone.xml index ac0c6838a6..be1b328fb8 100644 --- a/journeys/wear/pair-unpair-from-phone.xml +++ b/journeys/wear/pair-unpair-from-phone.xml @@ -1,19 +1,26 @@ - Unpair on the phone asks first, then ends the pairing on both devices. The watch keeps its wallet. Two emulators - over the debug socket. + Unpair on the phone asks first, then ends the pairing on both devices and deletes the wallet from the watch: the + watch shows Wallet removed, then onboarding, and its encrypted seed is gone. The paired watch has one button, + Unpair, and no separate erase. With the watch app open; an unpair that reaches a closed app or a locked watch + needs the Data Layer (manual test 5 in journeys/wear/README.md › Manual tests for pairing). Two emulators over + the debug socket. - Precondition: journeys/wear/README.md › Phone and watch over the debug socket, paired. Phone: on Home. Watch: - on the Settings page, which lists "WatchSettingsPaired". + Precondition: journeys/wear/README.md › Phone and watch over the debug socket, paired. Watch: on the Balance + page. Phone: on Home. The journey leaves no wallet on the watch. + Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists one file On the phone, open Settings and tap Watch (tag "PairedWatchSettings") + Verify "PairedWatchUnpair" is listed and neither "PairedWatchErase" nor "PairedWatchClose" is + Verify from a screenshot that the sheet shows a large orange watch icon above Unpair, not a shield, with the secure hardware line "PairedWatchKeyLevel" still listed Tap Unpair (tag "PairedWatchUnpair") - Tap Cancel in the dialog (tag "DialogCancel") and verify "PairedWatchName" is still listed - Tap Unpair (tag "PairedWatchUnpair") again, then Unpair in the dialog (tag "DialogConfirm") - Wait up to 10 s until the phone lists "PairedWatchPair" and no "PairedWatchName" - Verify the watch lists "WatchSettingsAbout" and no "WatchSettingsPaired" - On the watch, swipe right three times and verify "WatchHomeBalance" is listed: the wallet is still there - Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists one file + Tap Cancel in the dialog (tag "DialogCancel") and verify "PairedWatchName" is still listed and the watch still lists "WatchHomeBalance" + Tap Unpair (tag "PairedWatchUnpair") again, verify the dialog says the watch will delete its wallet and that a watch that never reconnects keeps it, then tap Unpair in the dialog (tag "DialogConfirm") + Wait up to 15 s until the watch lists "WalletRemovedTitle" + Verify the phone lists "PairedWatchPair" and no "PairedWatchName" + On the watch, tap OK (tag "WalletRemovedConfirm") and verify "WatchOnboardingRestore" is listed + Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists no seed file + Restart the watch app (README › Restart) and verify "WatchOnboardingRestore" is listed again diff --git a/journeys/wear/pay-request-from-phone.xml b/journeys/wear/pay-request-from-phone.xml deleted file mode 100644 index 4dc8909fb1..0000000000 --- a/journeys/wear/pay-request-from-phone.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - A Lightning invoice under review on the phone can be handed to the paired watch (docs/wear.md › Pairing › - Payment handoff): Pay on Watch sends it over the link, the watch opens its own review with the hold to pay, and - the phone shows one line. The watch asks for its hold with QuickPay on Watch on. That a handed-off request never - goes out under QuickPay is held by unit tests (SendViewModelTest, LaunchGateTest), not proven here: an invoice - the phone reviews is above the phone's QuickPay amount, which also caps one QuickPay payment on the watch. Two - emulators over the debug socket. - - Both apps are open on one wallet and the watch pays, which is unsafe on a wallet you keep (#2152): run this only - on the local ./spark stack with throwaway funds, never on hosted regtest (journeys/wear/README.md › Two apps on - one wallet). - - Precondition: journeys/wear/README.md › Phone and watch over the debug socket, with both apps built for the - local ./spark stack from the start and one wallet on both, paired (after pair-receive-wallet.xml), a Spark - balance of at least 5 000 sats and no QuickPay payment on either today. Phone: QuickPay on at $1 and 5×, and - QuickPay on Watch on at $5 and 5× (README › Phone settings on VSS, step 3), Local Currency USD, on Home. Watch: on - the Balance page with the loading ring stopped and a fiat value showing. Note N, the sats worth about $2 at the - dollar rate the phone shows (Settings › Local Currency): above the phone's QuickPay amount, so the phone shows - its review. - - - Run `adb -s $WATCH logcat -c`, then `../bitkit-docker/spark invoice N` and note the BOLT11 invoice it prints as <invoice> - Run `adb -s $PHONE shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` - Wait up to 15 s until the phone shows the review (tag "SendConfirm") with "SendPayOnWatch" - Tap "SendPayOnWatch" on the phone - Wait up to 10 s until "SendPayOnWatchResult" on the phone reads "Sent to your watch. Hold to pay there." - Wait up to 15 s until "WatchSendHold" is listed on the watch, touching nothing, and verify "WatchSendAmount" reads N, grouped as the watch writes it - Wait 5 s and verify "WatchSendHold" is still listed and `adb -s $WATCH logcat -d -s BitkitWear` does not list "Skipped the hold to pay under QuickPay": the handed-off request waits for the hold - Hold "WatchSendHold" for 2 s as in README › Holding to pay - Wait up to 15 s until "WatchSendSent" is listed on the watch - - diff --git a/journeys/wear/quickpay-off-holds.xml b/journeys/wear/quickpay-off-holds.xml index a6e38b67cf..027d79e068 100644 --- a/journeys/wear/quickpay-off-holds.xml +++ b/journeys/wear/quickpay-off-holds.xml @@ -5,8 +5,7 @@ behaves the same. Emulator and physical watch. Precondition: run quickpay-skips-hold.xml first, on its Private settings wallet and never the public test phrase - alone. Then, on the phone with the same wallet, turn QuickPay off, leave QuickPay on Watch on (the watch's QuickPay holds only - while the phone's own is on), and leave Default Unit Bitcoin, Denomination + alone. Then, on the phone with the same wallet, turn QuickPay off and leave Default Unit Bitcoin, Denomination Modern and Local Currency USD as that journey set them, so the amount below reads in sats; wait for the backup and close the phone app, see journeys/wear/README.md › Phone settings on VSS. Watch: the wallet of quickpay-skips-hold.xml on the local ./spark stack with at least 2 000 sats, the app open on the Balance @@ -19,11 +18,12 @@ Wait up to 15 s until `adb logcat -d -s BitkitWear` lists "Imported the phone's settings" Swipe right three times to the Balance page Run `../bitkit-docker/spark invoice 200` and note the BOLT11 invoice it prints as <invoice> + Run `adb logcat -c` Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` Wait up to 10 s until "WatchSendHold" is listed Verify "WatchSendAmount" reads "200" - Verify "WatchSendSent" does not get listed within 5 s: nothing was paid + Wait 5 s, then verify "WatchSendHold" is still listed and `adb logcat -d -s BitkitWear | grep -c "Finished send with outcome"` prints 0: nothing was paid. Count in the log, not a dump: a Sent screen's confetti would keep a dump waiting past the 2 s it shows (README › The confetti) Hold "WatchSendHold" for 2 s as in README › Holding to pay - Wait up to 15 s until "WatchSendSent" is listed + Wait up to 15 s until `adb logcat -d -s BitkitWear` lists "Finished send with outcome 'Sent'", and verify it also lists "Showed the success celebration for 'sent'": the send went out and the confetti started. Read the log, not a dump: the Sent screen's confetti keeps a dump waiting past the 2 s it shows (README › The confetti) diff --git a/journeys/wear/quickpay-on-app-start.xml b/journeys/wear/quickpay-on-app-start.xml index 38004306f5..c25a48e952 100644 --- a/journeys/wear/quickpay-on-app-start.xml +++ b/journeys/wear/quickpay-on-app-start.xml @@ -5,7 +5,7 @@ restart before it decides. The send goes out without the review and the hold. Emulator, or a physical watch that stays on the wrist and unlocked. - Precondition: run quickpay-skips-hold.xml first, so the watch's last import has QuickPay on, for the phone and for the watch, with Default Unit + Precondition: run quickpay-skips-hold.xml first, so the watch's last import has QuickPay on with Default Unit Bitcoin, Denomination Modern and Local Currency USD, which the amount below counts on, and change nothing on the phone since. Watch: the wallet of quickpay-skips-hold.xml on the local ./spark stack with at least 2 000 sats and a network on which the balance comes back within 20 s of a start. A wallet that needs more than 30 s shows the @@ -18,8 +18,9 @@ Run `../bitkit-docker/spark invoice 200` and note the BOLT11 invoice it prints as <invoice> Run `adb logcat -c` Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev`, which starts the app - Wait up to 40 s until "WatchSendSent" is listed, touching nothing - Verify "WatchSendResultAmount" reads "200" + Run `adb shell 'for i in $(seq 400); do logcat -d -s BitkitWear | grep -q "Showed the success celebration" && break; sleep 0.1; done; screencap -p /sdcard/sent.png'`, which waits on the watch up to about 40 s for the celebration's log line and takes a screenshot as soon as it appears, since the screen closes 2 s after it shows and its confetti keeps a dump waiting past that (README › The confetti), touching nothing + Run `adb logcat -d -s BitkitWear | grep -oE "Finished send with outcome '[^']*'|Showed the success celebration for '[^']*'"` and verify it prints "Finished send with outcome 'Sent'" and "Showed the success celebration for 'sent'": the send went out and the confetti started + Run `adb pull /sdcard/sent.png && adb shell rm /sdcard/sent.png` and verify from sent.png, the screenshot the step above took, that it shows the check, "Sent" and "200" Verify `adb logcat -d -s BitkitWear` lists "Skipped the hold to pay under QuickPay" diff --git a/journeys/wear/quickpay-over-limit-holds.xml b/journeys/wear/quickpay-over-limit-holds.xml index 5f4bd655ff..7adf223b22 100644 --- a/journeys/wear/quickpay-over-limit-holds.xml +++ b/journeys/wear/quickpay-over-limit-holds.xml @@ -1,14 +1,13 @@ - With QuickPay on in the phone's settings and for the watch, an invoice above the watch's QuickPay amount still - opens the review and + With QuickPay on in the phone's settings, an invoice above the phone's QuickPay amount still opens the review and is paid only by the hold. Emulator and physical watch. Precondition, in this order, as quickpay-skips-hold.xml: Private settings wallet, never the public test phrase alone, restored on the watch on the local ./spark stack and funded there with at least 12 000 sats before any phone setting changed (journeys/wear/README.md › Private settings wallet, step 5). Then Phone settings on VSS, see README › Phone settings on VSS, with Default Unit Bitcoin, Denomination Modern, Local Currency USD and - QuickPay on at $1 and 5×, QuickPay on Watch on at $1 and 5×, and the phone app closed. Watch: the app open on the Balance page and the loading ring + QuickPay on at $1 and 5×, and the phone app closed. Watch: the app open on the Balance page and the loading ring stopped. The fiat value below is in dollars, which is what those units give. 10 000 sats are above $1 while a bitcoin costs more than $10 000. README › Holding to pay has the hold gesture. @@ -20,10 +19,11 @@ Swipe right three times to the Balance page Wait up to 1 minute until "WatchHomeBalanceSecondary" reads a fiat value: without the rates QuickPay holds whatever the amount Run `../bitkit-docker/spark invoice 10000` and note the BOLT11 invoice it prints as <invoice> + Run `adb logcat -c` Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` Wait up to 10 s until "WatchSendHold" is listed - Verify "WatchSendSent" does not get listed within 5 s: nothing was paid + Wait 5 s, then verify "WatchSendHold" is still listed and `adb logcat -d -s BitkitWear | grep -c "Finished send with outcome"` prints 0: nothing was paid. Count in the log, not a dump: a Sent screen's confetti would keep a dump waiting past the 2 s it shows (README › The confetti) Hold "WatchSendHold" for 2 s as in README › Holding to pay - Wait up to 15 s until "WatchSendSent" is listed + Wait up to 15 s until `adb logcat -d -s BitkitWear` lists "Finished send with outcome 'Sent'", and verify it also lists "Showed the success celebration for 'sent'": the send went out and the confetti started. Read the log, not a dump: the Sent screen's confetti keeps a dump waiting past the 2 s it shows (README › The confetti) diff --git a/journeys/wear/quickpay-shared-daily-limit.xml b/journeys/wear/quickpay-shared-daily-limit.xml index cf546da31f..51c4e171ad 100644 --- a/journeys/wear/quickpay-shared-daily-limit.xml +++ b/journeys/wear/quickpay-shared-daily-limit.xml @@ -13,23 +13,22 @@ Precondition: journeys/wear/README.md › Phone and watch over the debug socket, with both apps built for the local ./spark stack from the start and one wallet on both, paired: after pair-receive-wallet.xml, or after pair-same-wallet.xml. A Spark balance of at least 20 000 sats, and no QuickPay payment made on either today. - QuickPay on Watch turned on at $5 and 5× in the phone's Watch sheet (the third action), so the watch's own daily - limit, $25, leaves the phone's, $5, as the one that refuses. Phone: Local Currency USD, on Home. Watch: on the Balance page with the loading ring stopped and a fiat value + Phone: Local Currency USD, on Home. Watch: on the Balance page with the loading ring stopped and a fiat value showing. Note N, the sats worth $3 at the dollar rate the phone shows (Settings › Local Currency). README › Phone settings on VSS, step 3, has the QuickPay sliders. Run `adb -s $WATCH logcat -c` and `adb -s $PHONE logcat -c` On the phone, open Settings ▸ QuickPay (tag "QuickpaySettings", past "QuickpayIntro-button" the first time) and turn QuickPay on (tag "QuickpayToggle") - Set the amount to $5 (tag "QuickpayAmountSlider") and the daily limit to 1× (tag "QuickpayDailyLimitSlider") by tapping the slider track above each stop's label; then in Settings ▸ Watch tap "PairedWatchQuickPay", turn on "PairedWatchQuickPayToggle" (PIN 1111 if asked), tap "PairedWatchQuickPayAmountStop-5" and "PairedWatchQuickPayLimitStop-5", close the sheet and return to the wallet overview + Set the amount to $5 (tag "QuickpayAmountSlider") and the daily limit to 1× (tag "QuickpayDailyLimitSlider") by tapping the slider track above each stop's label, then return to the wallet overview Wait up to 10 s until `adb -s $WATCH logcat -d -s BitkitWear` lists "Applied the settings the phone pushed" Run `../bitkit-docker/spark invoice N` and note the BOLT11 invoice it prints as <first> Run `adb -s $WATCH shell am start -a android.intent.action.VIEW -d "lightning:<first>" to.bitkit.dev` - Wait up to 20 s until "WatchSendSent" is listed on the watch, touching nothing, and verify `adb -s $WATCH logcat -d -s BitkitWear` lists "Skipped the hold to pay under QuickPay": the watch paid by QuickPay + Wait up to 20 s, touching nothing, until `adb -s $WATCH logcat -d -s BitkitWear` lists "Finished send with outcome 'Sent'", and verify it also lists "Skipped the hold to pay under QuickPay": the watch paid by QuickPay. Read the log, not a dump: the Sent screen's confetti keeps a dump waiting past the 2 s it shows (README › The confetti) Wait 5 s for the watch's count to reach the phone Run `../bitkit-docker/spark invoice N` and note the BOLT11 invoice it prints as <second> Run `adb -s $PHONE shell am start -a android.intent.action.VIEW -d "lightning:<second>" to.bitkit.dev` Wait up to 15 s until the phone shows the review with the swipe (tags "SendConfirm" and "GRAB"), and verify `adb -s $PHONE logcat -d -s APP` lists "Skipping QuickPay: daily spend '<about 300>' + '<about 300>' exceeds cap '500'": the day's limit counts the watch's payment, not an unreadable count (which shows as 10^18) - Swipe "GRAB" to pay, complete authorization if requested, and verify it ends on the sent sheet + Swipe "GRAB" to pay; if the "Are You Sure?" dialog then warns about sending over 50% of the balance, tap "Yes, Send" (tag "DialogConfirm"). Complete authorization if requested, and verify it ends on the sent sheet diff --git a/journeys/wear/quickpay-skips-hold.xml b/journeys/wear/quickpay-skips-hold.xml index 276b0b0273..4a952c4883 100644 --- a/journeys/wear/quickpay-skips-hold.xml +++ b/journeys/wear/quickpay-skips-hold.xml @@ -1,7 +1,6 @@ - With QuickPay on in the phone's settings and QuickPay on Watch on there too, an invoice under the watch's QuickPay - amount is paid without the review + With QuickPay on in the phone's settings, an invoice under the phone's QuickPay amount is paid without the review and without the hold: the link goes straight to sending and the same "Sent" check, and the flow closes by itself. Emulator and physical watch. @@ -9,9 +8,8 @@ never the public test phrase alone, restored on the watch on the local ./spark stack (README › Local ./spark stack) and funded there with at least 2 000 sats before any phone setting changed (README › Private settings wallet, step 5). Then Phone settings on VSS, see README › Phone settings on VSS, with Default Unit Bitcoin, - Denomination Modern, Local Currency USD, QuickPay on at $1 and the daily limit at 5× on the phone, QuickPay on - Watch on at $1 and 5× (README › Phone settings on VSS, step 3: the watch's QuickPay is off until the phone turns - it on, docs/wear.md › QuickPay), and the phone app closed. Watch: the app open on the Balance page and the loading ring stopped. The amounts below are in sats + Denomination Modern, Local Currency USD, QuickPay on at $1 and the daily limit at 5× on the phone, and the phone + app closed. Watch: the app open on the Balance page and the loading ring stopped. The amounts below are in sats and the fiat value in dollars, which is what those units give. The watch reads the phone's settings from the hosted staging VSS whatever Spark network it is on. 200 sats are under $1 while a bitcoin costs less than $500 000. @@ -24,9 +22,11 @@ Swipe right three times to the Balance page Wait up to 1 minute until "WatchHomeBalanceSecondary" reads a fiat value: QuickPay needs the rates Run `../bitkit-docker/spark invoice 200` and note the BOLT11 invoice it prints as <invoice> + Run `adb logcat -c` Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` - Wait up to 20 s until "WatchSendSent" is listed, touching nothing - Verify "WatchSendResultAmount" reads "200" + Run `adb shell 'for i in $(seq 200); do logcat -d -s BitkitWear | grep -q "Showed the success celebration" && break; sleep 0.1; done; screencap -p /sdcard/sent.png'`, which waits on the watch up to about 20 s for the celebration's log line and takes a screenshot as soon as it appears, since the screen closes 2 s after it shows and its confetti keeps a dump waiting past that (README › The confetti), touching nothing + Run `adb logcat -d -s BitkitWear | grep -oE "Finished send with outcome '[^']*'|Showed the success celebration for '[^']*'"` and verify it prints "Finished send with outcome 'Sent'" and "Showed the success celebration for 'sent'": the send went out and the confetti started + Run `adb pull /sdcard/sent.png && adb shell rm /sdcard/sent.png` and verify from sent.png, the screenshot the step above took, that it shows the check, "Sent" and "200" Verify `adb logcat -d -s BitkitWear` lists "Skipped the hold to pay under QuickPay" Wait up to 6 s until "WatchHomeBalance" is listed: the flow closed by itself diff --git a/journeys/wear/quickpay-watch-limit.xml b/journeys/wear/quickpay-watch-limit.xml deleted file mode 100644 index 1d39b9056c..0000000000 --- a/journeys/wear/quickpay-watch-limit.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - The watch's QuickPay is set on the phone (docs/wear.md › Pairing › Watch limits): off until QuickPay on Watch is - turned on in the phone's Watch sheet, then payments up to the watch's own amount skip the hold, and one above it, - though under the phone's own QuickPay amount, is held. Turning it on asks for the phone's PIN while payments - need it, and lowering a limit never asks; journeys/settings/watch-quickpay-pin.xml walks the rest of that rule and - Back. Two emulators over the debug socket. - - Both apps are open on one wallet and the watch pays, which is unsafe on a wallet you keep (#2152): run this only - on the local ./spark stack with throwaway funds, never on hosted regtest (journeys/wear/README.md › Two apps on - one wallet). - - Precondition: journeys/wear/README.md › Phone and watch over the debug socket, with both apps built for the - local ./spark stack from the start and one wallet on both, paired (after pair-receive-wallet.xml, so the phone - has PIN 1111) with Require PIN for payments on (Settings › Security, tag "EnablePinForPayments") and no biometrics - enrolled, a Spark balance of at least 5 000 sats and no QuickPay payment on either today. Phone: QuickPay on - at $5 and 5× (README › Phone settings on VSS, step 3), QuickPay on Watch off, Local Currency USD, in Settings › - General. Watch: on the Balance page with the loading ring stopped and a fiat value showing. Note S, the sats - worth about $0.50, and L, the sats worth about $2, at the dollar rate the phone shows. - - - Run `adb -s $WATCH logcat -c`, then on the phone tap "PairedWatchSettings" and then "PairedWatchQuickPay" - Tap "PairedWatchQuickPayToggle" and wait up to 5 s until the PIN pad is listed, reading "Please enter your PIN code to confirm this QuickPay change."; a switch that turns on without it fails this step. Enter 1111 and verify the PIN pad is gone and the switch reads on - Tap "PairedWatchQuickPayAmountStop-1" and verify, for 3 s, that no PIN pad is listed, and that a text starting with "Payments up to $1 on your watch" is listed: lowering saves without the PIN - Wait up to 10 s until `adb -s $WATCH logcat -d -s BitkitWear` lists "Applied the settings the phone pushed" - Run `../bitkit-docker/spark invoice S` and then `adb -s $WATCH shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` with it - Wait up to 20 s until "WatchSendSent" is listed on the watch, touching nothing: under the watch's $1 it skipped the hold - Wait up to 10 s until "PairedWatchSpentToday" on the phone reads a non-zero amount, about $0.50 - Run `../bitkit-docker/spark invoice L` and open it on the watch as above - Wait up to 15 s until "WatchSendHold" is listed on the watch: $2 is above the watch's $1, though under the phone's $5 - Swipe the review away on the watch (README › Watch gestures) and verify nothing was paid: "WatchSendSent" is not listed - - diff --git a/journeys/wear/receive-paid-ambient.xml b/journeys/wear/receive-paid-ambient.xml index a840c75c44..4478794aa0 100644 --- a/journeys/wear/receive-paid-ambient.xml +++ b/journeys/wear/receive-paid-ambient.xml @@ -1,7 +1,7 @@ An invoice paid while the watch is in ambient mode shows the check without the amount, so the always-on screen - shows no amount; waking the watch shows the amount. Emulator and physical watch. + shows no amount; waking the watch shows the amount, with no confetti then either. Emulator and physical watch. Precondition: Restored wallet on the local ./spark stack, see journeys/wear/README.md › Local ./spark stack and › Restored wallet, on the Balance page with the loading ring stopped, and the always-on screen on (README › Watch @@ -14,11 +14,13 @@ Read the invoice from the log as in README › Reading the receive invoice and note it as <invoice> Run `adb shell input keyevent KEYCODE_SLEEP` Wait up to 5 s until "WatchReceiveHidden" is listed + Run `adb logcat -c` Run `../bitkit-docker/spark pay <invoice> 1000` from this repo's parent checkout - Wait up to 20 s until "WatchReceivePaid" is listed - Verify neither "WatchReceivePaidAmount" nor "WatchReceiveNew" is listed - Run `adb shell input keyevent KEYCODE_WAKEUP` - Wait up to 5 s until "WatchReceivePaidAmount" reads "1 000" + Run `adb shell 'for i in $(seq 20); do rm -f /sdcard/x.xml; uiautomator dump /sdcard/x.xml >/dev/null 2>&1; d=$(cat /sdcard/x.xml 2>/dev/null); case "$d" in *WatchReceivePaid*) break;; esac; done; echo "$d" | grep -oE "WatchReceivePaidAmount|WatchReceivePaid|WatchReceiveNew" | sort -u'`, which dumps up to 20 times (about 2 s a dump) until the check shows and looks in that same dump for the amount and the button, and verify it prints "WatchReceivePaid" alone: the always-on screen shows no amount + Run `adb logcat -d -s BitkitWear | grep "Showed the success celebration"` and verify it prints nothing: the always-on screen played no confetti (README › The confetti) + Run `adb shell input keyevent KEYCODE_WAKEUP`, wait 3 s, then verify "WatchReceivePaidAmount" is listed + Run `adb logcat -d -s BitkitWear | grep "Showed the success celebration"` again and verify it still prints nothing: waking plays no celebration + Verify "WatchReceivePaidAmount" reads "1 000" Verify "WatchReceiveNew" is listed diff --git a/journeys/wear/receive-paid.xml b/journeys/wear/receive-paid.xml index 550474df55..7f8738e160 100644 --- a/journeys/wear/receive-paid.xml +++ b/journeys/wear/receive-paid.xml @@ -16,9 +16,12 @@ Tap "WatchReceiveOpen" Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) Read the invoice from the log as in README › Reading the receive invoice and note it as <invoice> + Run `adb logcat -c` Run `../bitkit-docker/spark pay <invoice> 50000` from this repo's parent checkout - Wait up to 20 s until "WatchReceivePaid" is listed - Verify "WatchReceivePaidAmount" reads "50 000" + Run `for i in $(seq 30); do adb logcat -d -s BitkitWear | grep "Showed the success celebration" && break; sleep 1; done` and verify it prints one line, "Showed the success celebration for '<payment id>'": the confetti started (README › The confetti) + Wait 3 s for the confetti to end, then verify "WatchReceivePaid" is listed and "WatchReceivePaidAmount" reads "50 000" + Run `adb shell 'rm -f /sdcard/x.xml; uiautomator dump /sdcard/x.xml >/dev/null 2>&1; grep -oE "WatchReceivePaid|WatchConfetti" /sdcard/x.xml | sort -u'` and verify it prints "WatchReceivePaid" and not "WatchConfetti": the confetti is gone + Verify from a screenshot that the check is purple Verify the button below the check reads "New invoice" (tag "WatchReceiveNew") Tap the check (tag "WatchReceivePaid") and verify "WatchReceivePaid" is still listed 2 s later: the check is no button Tap New invoice (tag "WatchReceiveNew") diff --git a/journeys/wear/send-deeplink-bolt11.xml b/journeys/wear/send-deeplink-bolt11.xml index a4ffcedaf5..2952204f94 100644 --- a/journeys/wear/send-deeplink-bolt11.xml +++ b/journeys/wear/send-deeplink-bolt11.xml @@ -1,7 +1,8 @@ A `lightning:` link to a BOLT11 invoice opens the review with the amount; holding the pay button fills the ring - around the bezel and pays; the check shows "Sent" and the flow closes by itself after about 2 s. Emulator and + around the bezel and pays; the check shows "Sent" under purple confetti and the flow closes by itself after about + 2 s. Emulator and physical watch. Precondition: Restored wallet on the local ./spark stack with at least 2 000 sats (run receive-paid.xml first), @@ -9,16 +10,20 @@ stopped. README › Holding to pay has the hold gesture. - Run `../bitkit-docker/spark invoice 1000` and note the BOLT11 invoice it prints as <invoice> + From the bitkit-docker checkout, with `ALICE` set as in README › Hold invoices, run `$ALICE bolt11-receive 1000sat -d Coffee | jq -r .invoice` and note the BOLT11 invoice it prints as <invoice>: its description, "Coffee", is the note activity-list.xml checks Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` Wait up to 10 s until "WatchSendHold" is listed + Verify from a screenshot that the Hold to pay button is purple, not orange Verify "WatchSendAmount" reads "1 000" Verify "WatchSendAmountSymbol" reads "₿" + Run `adb logcat -c` Hold "WatchSendHold" for 2 s as in README › Holding to pay - Wait up to 15 s until "WatchSendSent" is listed - Verify "WatchSendResultAmount" reads "1 000" + Run `adb shell 'for i in $(seq 100); do logcat -d -s BitkitWear | grep -q "Showed the success celebration" && break; sleep 0.1; done; screencap -p /sdcard/sent.png'`, which waits on the watch for the celebration's log line and takes a screenshot as soon as it appears, since the Sent screen closes 2 s after it shows (README › The confetti) + Run `adb logcat -d -s BitkitWear | grep -oE "Finished send with outcome '[^']*'|Showed the success celebration for '[^']*'"` and verify it prints "Finished send with outcome 'Sent'" and "Showed the success celebration for 'sent'": the send went out and the confetti started + Run `adb pull /sdcard/sent.png && adb shell rm /sdcard/sent.png` and verify from sent.png, the screenshot the step above took, that it shows the purple check, "Sent" and "1 000" Wait 4 s Verify the Balance page: "WatchHomeBalance" is listed Verify "WatchSendSent" is not listed + Run `adb logcat -d -s BitkitWear | grep -c "Showed the success celebration"` and verify it prints "1": the send celebrated once diff --git a/journeys/wear/send-hold-invoice-settle.xml b/journeys/wear/send-hold-invoice-settle.xml index 16ca61923d..0e3eafeb50 100644 --- a/journeys/wear/send-hold-invoice-settle.xml +++ b/journeys/wear/send-hold-invoice-settle.xml @@ -6,14 +6,15 @@ Precondition: send-hold-invoice-pending.xml was run just before, on the same emulator or watch, and its payment is still pending: keep its <preimage> and <hash>. The app is still open on the Balance page. README - › Hold invoices has the claim command. The outcome shows for 2 s, so read the layout at least once a second - while waiting for it. The app stays on screen for the whole journey. + › Hold invoices has the claim command. The outcome shows for 2 s under confetti that keeps a dump + waiting past that, so it is read from the log and a screenshot (README › The confetti). The app stays on screen for the whole journey. Run `adb logcat -c` Claim the payment as in README › Hold invoices, with <preimage> and <hash> - Wait up to 20 s until "WatchOutcomeSent" is listed - Verify "WatchOutcomeSent" has the content-desc "Sent, ₿ 1 000" + Run `adb shell 'for i in $(seq 200); do logcat -d -s BitkitWear | grep -q "Showed the success celebration" && break; sleep 0.1; done; screencap -p /sdcard/outcome.png'`, which waits on the watch up to about 20 s for the celebration's log line and takes a screenshot as soon as it appears, since the check shows for 2 s and its confetti keeps a dump waiting past that (README › The confetti) + Run `adb logcat -d -s BitkitWear | grep -oE "Resolved watched payment '[^']*' as '[^']*'|Showed the success celebration for '[^']*'"` and verify it prints "Resolved watched payment '<id>' as 'COMPLETED'" and "Showed the success celebration for '<id>'", with the same <id>: the payment was found sent and its check celebrated + Run `adb pull /sdcard/outcome.png && adb shell rm /sdcard/outcome.png` and verify from outcome.png, the screenshot the step above took, that it shows the purple check and "1 000". The screen reader's line, "Sent, ₿ 1 000", is SendOutcomeOverlayTest's to check: no dump catches the check while the confetti falls Wait 3 s Verify "WatchOutcomeSent" is not listed Verify "WatchHomeBalance" is listed diff --git a/journeys/wear/send-outcome-after-restart.xml b/journeys/wear/send-outcome-after-restart.xml index 1e38761b89..a6d4016d01 100644 --- a/journeys/wear/send-outcome-after-restart.xml +++ b/journeys/wear/send-outcome-after-restart.xml @@ -17,8 +17,9 @@ Run `adb shell am kill to.bitkit.dev` Verify `adb shell pidof to.bitkit.dev` prints nothing: the process ended before the outcome was shown Run `adb shell am start -n to.bitkit.dev/to.bitkit.wear.ui.MainActivity` - Wait up to 15 s until "WatchOutcomeSent" is listed, reading the layout at least once a second - Verify "WatchOutcomeSent" has the content-desc "Sent, ₿ 1 000" + Run `adb shell 'for i in $(seq 150); do logcat -d -s BitkitWear | grep -q "Showed the success celebration" && break; sleep 0.1; done; screencap -p /sdcard/outcome.png'`, which waits on the watch up to about 15 s for the celebration's log line and takes a screenshot as soon as it appears, since the check shows for 2 s and its confetti keeps a dump waiting past that (README › The confetti) + Run `adb logcat -d -s BitkitWear | grep -oE "Resolved watched payment '[^']*' as '[^']*'|Showed the success celebration for '[^']*'"` and verify it prints "Resolved watched payment '<id>' as 'COMPLETED'" and "Showed the success celebration for '<id>'", with the same <id>: the payment was found sent and its check celebrated + Run `adb pull /sdcard/outcome.png && adb shell rm /sdcard/outcome.png` and verify from outcome.png, the screenshot the step above took, that it shows the purple check and "1 000". The screen reader's line, "Sent, ₿ 1 000", is SendOutcomeOverlayTest's to check: no dump catches the check while the confetti falls Wait 3 s Verify "WatchOutcomeSent" is not listed Verify `adb logcat -d -s BitkitWear | grep -c "Resolved watched payment"` prints 1: it was not found a second time diff --git a/journeys/wear/send-paid-reopen.xml b/journeys/wear/send-paid-reopen.xml index c6286a8118..900533ad79 100644 --- a/journeys/wear/send-paid-reopen.xml +++ b/journeys/wear/send-paid-reopen.xml @@ -8,8 +8,9 @@ <invoice>. The app is still open on the Balance page. README › Hold invoices has the claim command. + Run `adb logcat -c` Claim the payment as in README › Hold invoices, with <preimage> and <hash> - Wait up to 20 s until "WatchOutcomeSent" is listed, reading the layout at least once a second + Wait up to 20 s until `adb logcat -d -s BitkitWear` lists "Showed the success celebration", and verify it also lists "Resolved watched payment '<id>' as 'COMPLETED'": the check of the sent payment showed. Read the log, not a dump: the check shows for 2 s and its confetti keeps a dump waiting past that (README › The confetti) Wait up to 5 s until "WatchHomeBalance" is listed Note the text of "WatchHomeBalance" as <paid balance> Run `adb shell am start -a android.intent.action.VIEW -d "lightning:<invoice>" to.bitkit.dev` diff --git a/journeys/wear/tile-balance.xml b/journeys/wear/tile-balance.xml index 61c8817e8e..660ce292b9 100644 --- a/journeys/wear/tile-balance.xml +++ b/journeys/wear/tile-balance.xml @@ -13,7 +13,7 @@ Note the text of "WatchHomeBalance" as <balance> Add the tile as in README › Tiles Show the tile as in README › Tiles and wait 3 s - Verify from a screenshot that the tile shows "₿ <balance>" and an orange QR edge button below it + Verify from a screenshot that the tile shows "₿ <balance>" and a purple QR edge button below it Tap the QR edge button at the point the screenshot shows Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr" (README, top) Swipe to dismiss from the left edge: `adb shell input swipe 20 227 400 227 300` diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index 11ab67dd98..80bb872103 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -95,17 +95,16 @@ - + - - - + - - - diff --git a/wear/src/main/res/drawable/ic_received.xml b/wear/src/main/res/drawable/ic_received.xml new file mode 100644 index 0000000000..b9a852e1d8 --- /dev/null +++ b/wear/src/main/res/drawable/ic_received.xml @@ -0,0 +1,14 @@ + + + + diff --git a/wear/src/main/res/drawable/ic_sent.xml b/wear/src/main/res/drawable/ic_sent.xml new file mode 100644 index 0000000000..02b516e207 --- /dev/null +++ b/wear/src/main/res/drawable/ic_sent.xml @@ -0,0 +1,14 @@ + + + + diff --git a/wear/src/main/res/drawable/ic_south_west.xml b/wear/src/main/res/drawable/ic_south_west.xml deleted file mode 100644 index 348f5b5909..0000000000 --- a/wear/src/main/res/drawable/ic_south_west.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - diff --git a/wear/src/main/res/drawable/ic_x.xml b/wear/src/main/res/drawable/ic_x.xml new file mode 100644 index 0000000000..40c28ca482 --- /dev/null +++ b/wear/src/main/res/drawable/ic_x.xml @@ -0,0 +1,15 @@ + + + + diff --git a/wear/src/main/res/drawable/tile_preview.xml b/wear/src/main/res/drawable/tile_preview.xml index edbbb97dde..b4b285afc1 100644 --- a/wear/src/main/res/drawable/tile_preview.xml +++ b/wear/src/main/res/drawable/tile_preview.xml @@ -12,7 +12,7 @@ android:fillColor="#FFFFFFFF" android:pathData="M56,82h80a7,7 0,0 1,0 14h-80a7,7 0,0 1,0 -14z" /> فتح إعدادات NFC طلب دفع Bitkit استعادة - ابدأ من الهاتف متطابقة جارٍ الاتصال… تم الإقران diff --git a/wear/src/main/res/values-b+es+419/strings.xml b/wear/src/main/res/values-b+es+419/strings.xml index f276708aa1..180b9be055 100644 --- a/wear/src/main/res/values-b+es+419/strings.xml +++ b/wear/src/main/res/values-b+es+419/strings.xml @@ -20,7 +20,6 @@ Abrir ajustes de NFC Solicitud de pago de Bitkit Restaurar - Ve al teléfono Coinciden Conectando… Vinculado diff --git a/wear/src/main/res/values-ca/strings.xml b/wear/src/main/res/values-ca/strings.xml index 738d8c83bb..8ac04d4585 100644 --- a/wear/src/main/res/values-ca/strings.xml +++ b/wear/src/main/res/values-ca/strings.xml @@ -20,7 +20,6 @@ Obre la configuració de l\'NFC Sol·licitud de pagament de Bitkit Restaurar - Comença al telèfon Coincideixen Connectant… Vinculat diff --git a/wear/src/main/res/values-cs/strings.xml b/wear/src/main/res/values-cs/strings.xml index bce28c5a40..bb88c6b1be 100644 --- a/wear/src/main/res/values-cs/strings.xml +++ b/wear/src/main/res/values-cs/strings.xml @@ -20,7 +20,6 @@ Otevřít nastavení NFC Žádost o platbu Bitkit Obnovit - Začněte v telefonu Shodují se Připojování… Spárováno diff --git a/wear/src/main/res/values-de/strings.xml b/wear/src/main/res/values-de/strings.xml index 3d0afaf39c..c8f7ce29b0 100644 --- a/wear/src/main/res/values-de/strings.xml +++ b/wear/src/main/res/values-de/strings.xml @@ -20,7 +20,6 @@ NFC-Einstellungen öffnen Bitkit-Zahlungsanforderung Wiederherstellen - Am Telefon starten Stimmt Verbinden… Gekoppelt diff --git a/wear/src/main/res/values-el/strings.xml b/wear/src/main/res/values-el/strings.xml index c4cea4fa61..5b4459e062 100644 --- a/wear/src/main/res/values-el/strings.xml +++ b/wear/src/main/res/values-el/strings.xml @@ -20,7 +20,6 @@ Άνοιγμα ρυθμίσεων NFC Αίτημα πληρωμής Bitkit Επαναφορά - Ξεκίνα στο τηλέφωνο Ταιριάζουν Σύνδεση… Συζεύχθηκε diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml index 73217668c6..eea8769a27 100644 --- a/wear/src/main/res/values-es-rES/strings.xml +++ b/wear/src/main/res/values-es-rES/strings.xml @@ -20,7 +20,6 @@ Abrir ajustes de NFC Solicitud de pago de Bitkit Restaurar - Ve al teléfono Coinciden Conectando… Vinculado diff --git a/wear/src/main/res/values-es/strings.xml b/wear/src/main/res/values-es/strings.xml index 73217668c6..eea8769a27 100644 --- a/wear/src/main/res/values-es/strings.xml +++ b/wear/src/main/res/values-es/strings.xml @@ -20,7 +20,6 @@ Abrir ajustes de NFC Solicitud de pago de Bitkit Restaurar - Ve al teléfono Coinciden Conectando… Vinculado diff --git a/wear/src/main/res/values-fr/strings.xml b/wear/src/main/res/values-fr/strings.xml index a309ba24a3..bd2ec61f56 100644 --- a/wear/src/main/res/values-fr/strings.xml +++ b/wear/src/main/res/values-fr/strings.xml @@ -20,7 +20,6 @@ Ouvrir les réglages NFC Demande de paiement Bitkit Restaurer - Depuis le téléphone Identiques Connexion… Associée diff --git a/wear/src/main/res/values-it/strings.xml b/wear/src/main/res/values-it/strings.xml index 27a9807479..b3b51d524a 100644 --- a/wear/src/main/res/values-it/strings.xml +++ b/wear/src/main/res/values-it/strings.xml @@ -20,7 +20,6 @@ Apri impostazioni NFC Richiesta di pagamento Bitkit Ripristina - Avvia dal telefono Uguali Connessione… Associato diff --git a/wear/src/main/res/values-nl/strings.xml b/wear/src/main/res/values-nl/strings.xml index 3cd6b0a687..f53767f7f7 100644 --- a/wear/src/main/res/values-nl/strings.xml +++ b/wear/src/main/res/values-nl/strings.xml @@ -20,7 +20,6 @@ NFC-instellingen openen Bitkit-betaalverzoek Herstellen - Start op telefoon Gelijk Verbinden… Gekoppeld diff --git a/wear/src/main/res/values-pl/strings.xml b/wear/src/main/res/values-pl/strings.xml index a1b46d6554..26e01597bb 100644 --- a/wear/src/main/res/values-pl/strings.xml +++ b/wear/src/main/res/values-pl/strings.xml @@ -20,7 +20,6 @@ Otwórz ustawienia NFC Żądanie płatności Bitkit Odzyskaj - Zacznij na telefonie Zgodne Łączenie… Sparowano diff --git a/wear/src/main/res/values-pt-rBR/strings.xml b/wear/src/main/res/values-pt-rBR/strings.xml index aa9519e61f..94e3d83d91 100644 --- a/wear/src/main/res/values-pt-rBR/strings.xml +++ b/wear/src/main/res/values-pt-rBR/strings.xml @@ -20,7 +20,6 @@ Abrir configurações de NFC Solicitação de pagamento Bitkit Restaurar - Inicie no celular Coincidem Conectando… Pareado diff --git a/wear/src/main/res/values-pt/strings.xml b/wear/src/main/res/values-pt/strings.xml index 30583dc617..1ceb62f9ef 100644 --- a/wear/src/main/res/values-pt/strings.xml +++ b/wear/src/main/res/values-pt/strings.xml @@ -20,7 +20,6 @@ Abrir definições de NFC Pedido de pagamento Bitkit Restaurar - Inicie no telemóvel Coincidem A ligar… Emparelhado diff --git a/wear/src/main/res/values-ru/strings.xml b/wear/src/main/res/values-ru/strings.xml index 75b051a8e4..eb48f6391e 100644 --- a/wear/src/main/res/values-ru/strings.xml +++ b/wear/src/main/res/values-ru/strings.xml @@ -20,7 +20,6 @@ Открыть настройки NFC Запрос на оплату Bitkit Восстановить - Начните на телефоне Совпадают Подключение… Сопряжено diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index b2656b1986..c71831fa70 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -20,7 +20,6 @@ Open NFC settings Bitkit payment request Restore - Start on phone Match Connecting… Paired diff --git a/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt index ed7b57bce0..2b0b4d7337 100644 --- a/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt +++ b/wear/src/test/java/to/bitkit/wear/data/QuickPaySpendStoreTest.kt @@ -33,15 +33,14 @@ class FakeQuickPaySpendStore : QuickPaySpendStore { dayKey: String, cents: Long, capCents: Long, - ownCapCents: Long, peerCents: suspend (String) -> Long, ): String? { failure?.let { throw it } - if (cents <= 0 || capCents <= 0 || ownCapCents <= 0) return null + if (cents <= 0 || capCents <= 0) return null val isNewDay = day.let { it == null || dayKey > it } val counted = if (isNewDay) dayKey else checkNotNull(day) val spent = if (isNewDay) 0L else spentCents - if (cents > capCents - spent - peerCents(counted) || cents > ownCapCents - spent) return null + if (cents > capCents - spent - peerCents(counted)) return null if (isNewDay) day = dayKey spentCents = spent + cents this.spent.value = QuickPaySpend(counted, spentCents) @@ -181,27 +180,6 @@ class QuickPaySpendStoreTest : BaseUnitTest() { close() } - @Test - fun `the watch's own daily cap holds its own spend, whatever room the wallet's cap leaves`() = test { - val sut = open().first - - assertNotNull(sut.reserve(TODAY, cents = 300, capCents = 1_000, ownCapCents = 500)) - assertNull(sut.reserve(TODAY, cents = 201, capCents = 1_000, ownCapCents = 500)) - assertNotNull(sut.reserve(TODAY, cents = 200, capCents = 1_000, ownCapCents = 500)) - - assertEquals(QuickPaySpend(TODAY, 500), sut.spent.first()) - close() - } - - @Test - fun `the wallet's cap counts the phone's spend on top of the watch's own cap`() = test { - val sut = open().first - - assertNull(sut.reserve(TODAY, cents = 300, capCents = 1_000, ownCapCents = 500) { 800 }) - assertNotNull(sut.reserve(TODAY, cents = 200, capCents = 1_000, ownCapCents = 500) { 800 }) - close() - } - @Test fun `the phone's spend is asked for the day last counted when the watch's date went back`() = test { val sut = open().first diff --git a/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt b/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt index 7298ef1f77..79683d44b7 100644 --- a/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt +++ b/wear/src/test/java/to/bitkit/wear/data/SettingsStoreTest.kt @@ -12,7 +12,7 @@ import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.PhoneSettings import to.bitkit.wear.models.PrimaryDisplay import to.bitkit.wear.models.QuickPayLimits -import to.bitkit.wear.models.WatchQuickPayLimits +import to.bitkit.wear.models.USD import to.bitkit.wear.security.FakeDeviceLock import to.bitkit.wear.security.FakeSeedKey import to.bitkit.wear.security.KeystoreSeedStore @@ -32,12 +32,7 @@ import kotlin.test.assertTrue */ class SettingsStoreTest : BaseUnitTest() { private companion object { - val QUICK_PAY = QuickPayLimits( - isEnabled = true, - amountUsd = 10, - dailyMultiplier = 3, - watch = WatchQuickPayLimits(isEnabled = true, amountUsd = 1, dailyMultiplier = 5), - ) + val QUICK_PAY = QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3) val PHONE_SETTINGS = PhoneSettings(PrimaryDisplay.FIAT, BitcoinDisplayUnit.CLASSIC, "EUR", QUICK_PAY) } @@ -142,28 +137,33 @@ class SettingsStoreTest : BaseUnitTest() { } @Test - fun `settings without the watch's own quickpay turn it off, the phone's stays`() = test { + fun `the wearer's unit swap lasts until the phone's setting changes`() = test { val sut = open() sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) + sut.setPrimaryDisplay(PrimaryDisplay.BITCOIN) - sut.applyPhoneSettings(PHONE_SETTINGS.copy(quickPay = QUICK_PAY.copy(watch = null)), syncedAtMs = 6_000L) + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 6_000L) + assertEquals(PrimaryDisplay.BITCOIN, sut.data.first().primaryDisplay) - assertEquals(QUICK_PAY.copy(watch = null), sut.data.first().quickPay) + sut.applyPhoneSettings(PHONE_SETTINGS.copy(primaryDisplay = PrimaryDisplay.BITCOIN), syncedAtMs = 7_000L) + sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 8_000L) + assertEquals(PrimaryDisplay.FIAT, sut.data.first().primaryDisplay) close() } @Test - fun `the wearer's unit swap lasts until the phone's setting changes`() = test { + fun `the currency is the phone's alone, kept by the wearer's unit swap and changed only by an import`() = test { val sut = open() + assertEquals(USD, sut.data.first().selectedCurrency) sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 5_000L) - sut.setPrimaryDisplay(PrimaryDisplay.BITCOIN) - sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 6_000L) - assertEquals(PrimaryDisplay.BITCOIN, sut.data.first().primaryDisplay) + sut.setPrimaryDisplay(PrimaryDisplay.BITCOIN) + sut.setPrimaryDisplay(PrimaryDisplay.FIAT) + assertEquals("EUR", sut.data.first().selectedCurrency) - sut.applyPhoneSettings(PHONE_SETTINGS.copy(primaryDisplay = PrimaryDisplay.BITCOIN), syncedAtMs = 7_000L) - sut.applyPhoneSettings(PHONE_SETTINGS, syncedAtMs = 8_000L) - assertEquals(PrimaryDisplay.FIAT, sut.data.first().primaryDisplay) + val pushed = PHONE_SETTINGS.copy(selectedCurrency = "CHF") + sut.applyPushedSettings(pushed, syncedAtMs = 6_000L, changedAtMs = 6_000L) + assertEquals("CHF", sut.data.first().selectedCurrency) close() } diff --git a/wear/src/test/java/to/bitkit/wear/link/PhoneLinkRepoTest.kt b/wear/src/test/java/to/bitkit/wear/link/PhoneLinkRepoTest.kt index 4738786c9b..c9a27fd97e 100644 --- a/wear/src/test/java/to/bitkit/wear/link/PhoneLinkRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/link/PhoneLinkRepoTest.kt @@ -4,7 +4,6 @@ import androidx.datastore.preferences.core.emptyPreferences import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.flow.first -import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runCurrent @@ -20,16 +19,13 @@ import org.mockito.kotlin.whenever import to.bitkit.wear.data.FakeOwnInvoiceStore import to.bitkit.wear.data.FakeQuickPaySpendStore import to.bitkit.wear.data.FakeUncertainSendStore -import to.bitkit.wear.data.HandoffStore import to.bitkit.wear.data.PhoneStateSink import to.bitkit.wear.data.PhoneStateSource -import to.bitkit.wear.data.SendMonitor import to.bitkit.wear.data.UncertainSend import to.bitkit.wear.models.BitcoinDisplayUnit import to.bitkit.wear.models.PhoneSettings import to.bitkit.wear.models.PrimaryDisplay import to.bitkit.wear.models.QuickPayLimits -import to.bitkit.wear.models.WatchQuickPayLimits import to.bitkit.wear.repositories.PhoneLinkRepo import to.bitkit.wear.repositories.WalletRepo import to.bitkit.wear.repositories.WatchPairingStatus @@ -52,8 +48,6 @@ import to.bitkit.wearlink.OpenSend import to.bitkit.wearlink.PairedLink import to.bitkit.wearlink.PairingState import to.bitkit.wearlink.PairingThrottle -import to.bitkit.wearlink.PayResult -import to.bitkit.wearlink.PayResultDoc import to.bitkit.wearlink.PeerInvoice import to.bitkit.wearlink.PeerStateListener import to.bitkit.wearlink.PhoneLink @@ -87,8 +81,6 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { const val NOW = 1_800_000_000_000L const val MNEMONIC = "abandon ability able about" val HASH = "ab".repeat(32) - val REQUEST_ID = "cd".repeat(16) - const val INVOICE = "lnbcrt10u1pinvoice" const val PASSPHRASE = "pass" val bip39 = FakeBip39() @@ -109,8 +101,6 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { private val ownInvoices = FakeOwnInvoiceStore() private val spend = FakeQuickPaySpendStore() private val uncertainSends = FakeUncertainSendStore() - private val handoffs = HandoffStore { NOW } - private val sendMonitor = SendMonitor() /** What the phone's side holds of the watch's guard documents. */ private val phonePeer = object : PeerStateListener { @@ -167,8 +157,6 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { uncertainSendStore = uncertainSends, appId = APP_ID, nowMs = { NOW }, - handoffs = handoffs, - sendMonitor = sendMonitor, ) } @@ -324,7 +312,7 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) pair().getOrThrow() - phoneLink.remove(isErase = true) + phoneLink.remove() runCurrent() inOrder(walletRepo) { @@ -343,7 +331,7 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { pair().getOrThrow() whenever { walletRepo.noteEraseByPhone() }.thenReturn(Result.failure(SeedStoreError.Failed())) - phoneLink.remove(isErase = true) + phoneLink.remove() runCurrent() verify(walletRepo, never()).eraseByPhone() @@ -360,12 +348,12 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { } @Test - fun `the phone's unpair keeps the wallet and lets the backup import hold again`() = test { + fun `the phone's revoke, as on a wipe, keeps the wallet and lets the backup import hold again`() = test { setUp() seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) pair().getOrThrow() - phoneLink.remove(isErase = false) + phoneLink.forget() runCurrent() verify(walletRepo, never()).eraseByPhone() @@ -433,20 +421,20 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { } @Test - fun `a new pairing and an unpair each clear what a phone said for the guards`() = test { + fun `a new pairing and a revoke each clear what a phone said for the guards`() = test { setUp() seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) pair().getOrThrow() verify(sink).clearPeerState() - phoneLink.remove(isErase = false) + phoneLink.forget() runCurrent() verify(sink, times(2)).clearPeerState() } @Test - fun `a clear of what a phone said that fails does not stop a new pairing or an unpair`() = test { + fun `a clear of what a phone said that fails does not stop a new pairing or a revoke`() = test { setUp() seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) whenever { sink.clearPeerState() }.thenThrow(IllegalStateException("disk")) @@ -454,7 +442,7 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { pair().getOrThrow() assertNotNull(store.load()) - phoneLink.remove(isErase = false) + phoneLink.forget() runCurrent() assertNull(store.load()) @@ -569,112 +557,4 @@ class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertTrue(pair().isSuccess) assertNotNull(store.load()) } - - // region watch limits and the payment handoff - - @Test - fun `the watch's own quickpay limits the phone pushed go to the sink`() = test { - setUp() - seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) - pair().getOrThrow() - - val settings = SettingsDoc( - primaryDisplay = "fiat", - isQuickPayEnabled = true, - quickPayAmount = 10, - quickPayDailyLimitMultiplier = 3, - changedAtMs = 500, - isWatchQuickPayEnabled = true, - watchQuickPayAmount = 1, - watchQuickPayDailyLimitMultiplier = 5, - ) - phoneLink.publishSettings(settings) - runCurrent() - - val expected = PhoneSettings( - primaryDisplay = PrimaryDisplay.FIAT, - displayUnit = null, - selectedCurrency = null, - quickPay = QuickPayLimits(true, 10, 3, WatchQuickPayLimits(true, 1, 5)), - ) - verify(sink).applySettings(expected, PhoneStateSource.Push(500), NOW) - } - - private fun TestScope.payResults(): MutableList { - val results = mutableListOf() - backgroundScope.launch { phoneLink.payResults.collect { results += it } } - runCurrent() - return results - } - - @Test - fun `a handed-off bolt11 invoice with an amount is kept for its link and answered received`() = test { - setUp() - seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) - pair().getOrThrow() - val results = payResults() - - phoneLink.requestPay(REQUEST_ID, INVOICE) - runCurrent() - - assertEquals(listOf(PayResultDoc(REQUEST_ID, PayResult.Received)), results) - assertEquals(INVOICE, handoffs.take(REQUEST_ID)) - } - - @Test - fun `a handed-off request during a send is answered busy and not kept`() = test { - setUp() - seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) - pair().getOrThrow() - val results = payResults() - sendMonitor.begin() - - phoneLink.requestPay(REQUEST_ID, INVOICE) - runCurrent() - - assertEquals(listOf(PayResult.Busy), results.map { it.result }) - assertNull(handoffs.take(REQUEST_ID)) - } - - @Test - fun `a handed-off request that is no bolt11 invoice with an amount is refused`() = test { - setUp() - seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) - pair().getOrThrow() - val results = payResults() - val refused = listOf( - "bitcoin:bcrt1qexample", - "lnbcrt1pamountless", - "lightning:lnurl1dp68gurn8ghj7example", - "user@example.com", - ) - - refused.forEachIndexed { index, input -> - val id = "e$index".repeat(16) - phoneLink.requestPay(id, input) - runCurrent() - assertNull(handoffs.take(id), input) - } - - assertEquals(refused.map { PayResult.Refused }, results.map { it.result }) - } - - @Test - fun `a request the app dropped later is answered then, busy for a send and refused otherwise`() = test { - setUp() - seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE) - pair().getOrThrow() - val results = payResults() - phoneLink.requestPay(REQUEST_ID, INVOICE) - runCurrent() - - handoffs.onDropped(REQUEST_ID, isBusy = true) - runCurrent() - handoffs.onDropped(REQUEST_ID, isBusy = false) - runCurrent() - - assertEquals(listOf(PayResult.Received, PayResult.Busy, PayResult.Refused), results.map { it.result }) - } - - // endregion } diff --git a/wear/src/test/java/to/bitkit/wear/models/PhoneBackupContractTest.kt b/wear/src/test/java/to/bitkit/wear/models/PhoneBackupContractTest.kt index 929ecc2c45..bbc1004c22 100644 --- a/wear/src/test/java/to/bitkit/wear/models/PhoneBackupContractTest.kt +++ b/wear/src/test/java/to/bitkit/wear/models/PhoneBackupContractTest.kt @@ -11,9 +11,8 @@ import to.bitkit.wear.repositories.SettingsSyncRepo import kotlin.test.assertEquals /** - * `phone-backup-contract.json` holds what the watch needs the phone to keep writing: the backup's key, the nine - * settings in the phone's own encoding (six the phone uses itself and the watch's three QuickPay limits), and where - * each network's backups live. The phone's `WatchBackupContractTest` + * `phone-backup-contract.json` holds what the watch needs the phone to keep writing: the backup's key, the six + * settings in the phone's own encoding, and where each network's backups live. The phone's `WatchBackupContractTest` * compares the same file with what the phone app really writes and uses, so a renamed field or a moved server fails * a test instead of silently turning QuickPay off on the watch. */ @@ -29,19 +28,14 @@ class PhoneBackupContractTest { } @Test - fun `the watch reads all nine settings as the phone writes them`() { + fun `the watch reads all six settings as the phone writes them`() { val backup = contract.getValue("settingsBackup").toString().toByteArray() val expected = PhoneSettings( PrimaryDisplay.FIAT, BitcoinDisplayUnit.CLASSIC, "EUR", - QuickPayLimits( - isEnabled = true, - amountUsd = 10, - dailyMultiplier = 3, - watch = WatchQuickPayLimits(isEnabled = true, amountUsd = 1, dailyMultiplier = 5), - ), + QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3), ) assertEquals(expected, PhoneSettingsParser.parse(backup)) } diff --git a/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt b/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt index a70b5ca338..5e3d168ddf 100644 --- a/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt +++ b/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt @@ -46,6 +46,17 @@ class PhoneSettingsParserTest { assertEquals(3_000L, settings.quickPay?.dailyCapCents) } + @Test + fun `the watch's own quickpay keys of an earlier build are ignored, and the phone's quickpay holds`() { + val settings = parse( + """{"version":1,"settings":{"isQuickPayEnabled":true,"quickPayAmount":5,""" + + """"quickPayDailyLimitMultiplier":5,"isWatchQuickPayEnabled":true,"watchQuickPayAmount":20,""" + + """"watchQuickPayDailyLimitMultiplier":2}}""", + ) + + assertEquals(QuickPayLimits(isEnabled = true, amountUsd = 5, dailyMultiplier = 5), settings.quickPay) + } + @Test fun `enums written by ios are read too`() { val settings = parse( @@ -155,7 +166,7 @@ class PhoneSettingsParserTest { @Test fun `pushed settings are held to the same rules as a backup`() { - val settings = PhoneSettingsParser.fromPush("fiat", "CLASSIC", "EUR", true, 10, 3, false, 0, 0) + val settings = PhoneSettingsParser.fromPush("fiat", "CLASSIC", "EUR", true, 10, 3) assertEquals(PrimaryDisplay.FIAT, settings.primaryDisplay) assertEquals(BitcoinDisplayUnit.CLASSIC, settings.displayUnit) @@ -165,75 +176,12 @@ class PhoneSettingsParserTest { @Test fun `pushed values the phone cannot have are dropped, and QuickPay outside its sliders is off`() { - val settings = PhoneSettingsParser.fromPush("sideways", null, "euro", true, 51, 3, true, 5, 5) + val settings = PhoneSettingsParser.fromPush("sideways", null, "euro", true, 51, 3) assertEquals(null, settings.primaryDisplay) assertEquals(null, settings.displayUnit) assertEquals(null, settings.selectedCurrency) assertEquals(null, settings.quickPay) - assertEquals(null, PhoneSettingsParser.fromPush(null, null, null, true, 10, 0, true, 5, 5).quickPay) - } - - // region the watch's own quickpay - - @Test - fun `the watch's own quickpay is read with the phone's`() { - val settings = parse(watchQuickPay("true", "1", "5")) - - val watch = WatchQuickPayLimits(isEnabled = true, amountUsd = 1, dailyMultiplier = 5) - assertEquals(watch, settings.quickPay?.watch) - assertEquals(watch, settings.quickPay?.watchLimits) - assertEquals(100L, watch.thresholdCents) - assertEquals(500L, watch.dailyCapCents) - } - - @Test - fun `a backup without the watch's values, as from an older phone or bitkit-ios, leaves watch quickpay off`() { - val settings = parse(ANDROID_BACKUP) - - assertNull(settings.quickPay?.watch) - assertNull(settings.quickPay?.watchLimits) - } - - @Test - fun `watch quickpay with a missing, mistyped or out of range value is off, the phone's stays`() { - for ((isEnabled, amount, multiplier) in listOf( - Triple("\"true\"", "1", "5"), - Triple("true", "0", "5"), - Triple("true", "51", "5"), - Triple("true", "1", "0"), - Triple("true", "1", "\"5\""), - Triple("null", "1", "5"), - )) { - val settings = parse(watchQuickPay(isEnabled, amount, multiplier)) - assertNull(settings.quickPay?.watch, "$isEnabled $amount $multiplier") - assertEquals(QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3), settings.quickPay) - } - } - - @Test - fun `watch quickpay counts only while the phone's own is on`() { - val watch = WatchQuickPayLimits(isEnabled = true, amountUsd = 1, dailyMultiplier = 5) - - assertNull(QuickPayLimits(isEnabled = false, amountUsd = 10, dailyMultiplier = 3, watch = watch).watchLimits) - assertNull(QuickPayLimits(true, 10, 3, watch.copy(isEnabled = false)).watchLimits) - } - - @Test - fun `pushed watch limits are held to the phone's sliders`() { - fun push(amount: Int, multiplier: Int) = - PhoneSettingsParser.fromPush(null, null, null, true, 10, 3, true, amount, multiplier).quickPay?.watch - - assertEquals(WatchQuickPayLimits(isEnabled = true, amountUsd = 50, dailyMultiplier = 50), push(50, 50)) - assertNull(push(0, 0)) - assertNull(push(51, 5)) - assertNull(push(5, 51)) + assertEquals(null, PhoneSettingsParser.fromPush(null, null, null, true, 10, 0).quickPay) } - - private fun watchQuickPay(isEnabled: String, amount: String, multiplier: String) = - """{"version":1,"settings":{"isQuickPayEnabled":true,"quickPayAmount":10,"quickPayDailyLimitMultiplier":3,""" + - """"isWatchQuickPayEnabled":$isEnabled,"watchQuickPayAmount":$amount,""" + - """"watchQuickPayDailyLimitMultiplier":$multiplier}}""" - - // endregion } diff --git a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt index 77ebd55add..85a42c9255 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/PaymentsRepoTest.kt @@ -1762,6 +1762,21 @@ class PaymentsRepoTest : BaseUnitTest() { assertEquals(SparkFixtures.TIMESTAMP, payments[0].timestampSecs) } + @Test + fun `a payment's note is its invoice's description, and none when it is blank or missing`() = test { + whenever(sparkService.listPayments(20u)).thenReturn( + listOf( + payment("described", PaymentStatus.COMPLETED, description = " Coffee "), + payment("blank", PaymentStatus.COMPLETED, description = " "), + payment("plain", PaymentStatus.COMPLETED), + ), + ) + + val payments = sut.recentPayments().getOrThrow() + + assertEquals(listOf("Coffee", null, null), payments.map { it.message }) + } + @Test fun `recent payments fail while spark is not connected`() = test { whenever(sparkService.listPayments(anyOrNull())).doSuspendableAnswer { throw SparkError.NotConnected() } diff --git a/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt index 07fc672f41..3e3bba5e63 100644 --- a/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt +++ b/wear/src/test/java/to/bitkit/wear/repositories/QuickPayRepoTest.kt @@ -19,7 +19,6 @@ import to.bitkit.wear.data.FakeQuickPaySpendStore import to.bitkit.wear.data.SettingsStore import to.bitkit.wear.data.WatchSettings import to.bitkit.wear.models.QuickPayLimits -import to.bitkit.wear.models.WatchQuickPayLimits import to.bitkit.wear.models.rate import to.bitkit.wear.test.BaseUnitTest import to.bitkit.wearlink.QuickPayDoc @@ -41,8 +40,7 @@ class QuickPayRepoTest : BaseUnitTest() { /** 2026-11-28T12:00:00Z */ const val NOW = 1_795_867_200_000L const val FIVE_DOLLARS = 5_000uL - val WATCH = WatchQuickPayLimits(isEnabled = true, amountUsd = 5, dailyMultiplier = 3) - val LIMITS = QuickPayLimits(isEnabled = true, amountUsd = 5, dailyMultiplier = 3, watch = WATCH) + val LIMITS = QuickPayLimits(isEnabled = true, amountUsd = 5, dailyMultiplier = 3) } private val settingsStore = mock() @@ -100,8 +98,6 @@ class QuickPayRepoTest : BaseUnitTest() { rates.update { emptyList() } settings.update { it.copy(quickPay = LIMITS.copy(isEnabled = false)) } sut.awaitRate() - settings.update { it.copy(quickPay = LIMITS.copy(watch = WATCH.copy(isEnabled = false))) } - sut.awaitRate() settings.update { WatchSettings() } sut.awaitRate() whenever(settingsStore.data).thenReturn(flow { throw IOException("disk") }) @@ -132,7 +128,7 @@ class QuickPayRepoTest : BaseUnitTest() { fun `the last sat of an amount that rounded up is worth more than the phone's amount and holds`() = test { // 1 dollar is 1 030.9 sats, rounded up to 1 031, which are worth 1.00007 dollars. rates.update { listOf(rate("97000")) } - settings.update { it.copy(quickPay = LIMITS.copy(watch = WATCH.copy(amountUsd = 1))) } + settings.update { it.copy(quickPay = LIMITS.copy(amountUsd = 1)) } assertNull(sut.reserve(1_031uL)) assertEquals(0L, spend.spentCents) @@ -319,72 +315,4 @@ class QuickPayRepoTest : BaseUnitTest() { assertNull(sut.reserve(1uL)) assertEquals(0L, spend.spentCents) } - - // region the watch's own limits - - @Test - fun `watch quickpay is off until the phone turned it on for the watch`() = test { - settings.update { it.copy(quickPay = LIMITS.copy(watch = null)) } - assertNull(sut.reserve(1uL)) - - settings.update { it.copy(quickPay = LIMITS.copy(watch = WATCH.copy(isEnabled = false))) } - assertNull(sut.reserve(1uL)) - assertEquals(0L, spend.spentCents) - } - - @Test - fun `watch quickpay holds only while the phone's own quickpay is on`() = test { - settings.update { it.copy(quickPay = LIMITS.copy(isEnabled = false)) } - - assertNull(sut.reserve(1uL)) - } - - @Test - fun `one payment is held to the watch's own amount, below the phone's`() = test { - settings.update { it.copy(quickPay = LIMITS.copy(watch = WATCH.copy(amountUsd = 1))) } - - assertNull(sut.reserve(1_001uL)) - assertNotNull(sut.reserve(1_000uL)) - } - - @Test - fun `one payment is held to the phone's amount when the watch's own is above it`() = test { - settings.update { it.copy(quickPay = LIMITS.copy(amountUsd = 1, dailyMultiplier = 50)) } - - assertNull(sut.reserve(FIVE_DOLLARS)) - assertNull(sut.reserve(1_001uL)) - assertNotNull(sut.reserve(1_000uL)) - } - - @Test - fun `the last sat that rounded up above the phone's lower amount holds`() = test { - // 1 dollar is 1 030.9 sats, rounded up to 1 031, which are worth 1.00007 dollars. - rates.update { listOf(rate("97000")) } - settings.update { it.copy(quickPay = LIMITS.copy(amountUsd = 1, dailyMultiplier = 50)) } - - assertNull(sut.reserve(1_031uL)) - assertNotNull(sut.reserve(1_030uL)) - } - - @Test - fun `the watch's payments stop at the watch's own daily limit`() = test { - settings.update { it.copy(quickPay = LIMITS.copy(watch = WATCH.copy(amountUsd = 1, dailyMultiplier = 2))) } - - repeat(2) { assertNotNull(sut.reserve(1_000uL), "payment $it") } - assertNull(sut.reserve(1uL)) - assertEquals(200L, spend.spentCents) - } - - @Test - fun `the phone's daily limit still bounds the watch and the phone together`() = test { - settings.update { it.copy(quickPay = LIMITS.copy(watch = WATCH.copy(dailyMultiplier = 50))) } - phone.quickPay = QuickPayDoc("2026-11-28", 1_400) - - // 1 010 sats are 101 cents, one more than the wallet's day leaves. - assertNull(sut.reserve(1_010uL)) - assertNotNull(sut.reserve(1_000uL)) - assertNull(sut.reserve(1uL)) - } - - // endregion } diff --git a/wear/src/test/java/to/bitkit/wear/services/SparkFixtures.kt b/wear/src/test/java/to/bitkit/wear/services/SparkFixtures.kt index cbb1fcab16..ec48a8b66c 100644 --- a/wear/src/test/java/to/bitkit/wear/services/SparkFixtures.kt +++ b/wear/src/test/java/to/bitkit/wear/services/SparkFixtures.kt @@ -99,6 +99,7 @@ object SparkFixtures { amountSats: Long = 1_000, feeSats: Long = 3, timestamp: ULong = TIMESTAMP, + description: String? = null, ) = Payment( id = id, paymentType = type, @@ -109,7 +110,7 @@ object SparkFixtures { method = PaymentMethod.LIGHTNING, details = paymentHash?.let { PaymentDetails.Lightning( - description = null, + description = description, invoice = "lnbcrt1invoice", destinationPubkey = PROVIDER_NODE, htlcDetails = SparkHtlcDetails(it, null, TIMESTAMP + EXPIRY, SparkHtlcStatus.WAITING_FOR_PREIMAGE), diff --git a/wear/src/test/java/to/bitkit/wear/ui/LaunchGateTest.kt b/wear/src/test/java/to/bitkit/wear/ui/LaunchGateTest.kt index a5fa1f6398..bb701336e5 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/LaunchGateTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/LaunchGateTest.kt @@ -1,27 +1,16 @@ package to.bitkit.wear.ui -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.launch -import kotlinx.coroutines.test.UnconfinedTestDispatcher -import kotlinx.coroutines.test.runTest import org.junit.Test -import to.bitkit.wear.data.HandoffStore import to.bitkit.wear.data.SendMonitor import to.bitkit.wear.nfc.NfcTapFilter -import to.bitkit.wearlink.HandoffInbox -import to.bitkit.wearlink.PayRequestDoc -import to.bitkit.wearlink.PayResult -import to.bitkit.wearlink.PayResultDoc import kotlin.test.assertEquals import kotlin.test.assertNull /** What a link or a tapped tag may open, decided for the process and not for one activity. */ -@OptIn(ExperimentalCoroutinesApi::class) class LaunchGateTest { private var time = 0L private val sendMonitor = SendMonitor() - private val handoffs = HandoffStore { time } - private val sut = LaunchGate(NfcTapFilter { time }, sendMonitor, handoffs) + private val sut = LaunchGate(NfcTapFilter { time }, sendMonitor) @Test fun `a link and the tile's request pass`() { @@ -100,88 +89,8 @@ class LaunchGateTest { assertEquals(LaunchRequest.TagRefused, sut.admit(LaunchRequest.Receive, isTap = true)) } - @Test - fun `a handed-off request opens its send once, never under quickpay`() { - handoffs.put(PayRequestDoc(ID, INVOICE)) - - val admitted = sut.admit(LaunchRequest.Handoff(ID)) - - assertEquals(LaunchRequest.Send("lightning:$INVOICE", handoffId = ID), admitted) - assertEquals(true, (admitted as? LaunchRequest.Send)?.isHandoff) - assertNull(sut.admit(LaunchRequest.Handoff(ID))) - } - - @Test - fun `a handoff link with an id nothing arrived under opens nothing`() { - assertNull(sut.admit(LaunchRequest.Handoff(ID))) - } - - @Test - fun `a handed-off request is not opened a minute after it arrived`() { - handoffs.put(PayRequestDoc(ID, INVOICE)) - time += HandoffInbox.WINDOW_MS + 1 - - assertNull(sut.admit(LaunchRequest.Handoff(ID))) - } - - @Test - fun `a handed-off request during a send is dropped and reported busy`() = runTest { - val dropped = mutableListOf() - backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { handoffs.dropped.collect { dropped += it } } - handoffs.put(PayRequestDoc(ID, INVOICE)) - sendMonitor.begin() - - assertNull(sut.admit(LaunchRequest.Handoff(ID))) - - assertEquals(listOf(PayResultDoc(ID, PayResult.Busy)), dropped) - sendMonitor.end() - assertNull(sut.admit(LaunchRequest.Handoff(ID))) - } - - @Test - fun `a handed-off request that is no bolt11 invoice with an amount opens nothing and is refused`() = runTest { - val dropped = mutableListOf() - backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { handoffs.dropped.collect { dropped += it } } - handoffs.put(PayRequestDoc(ID, "bitcoin:bcrt1qexample")) - handoffs.put(PayRequestDoc(OTHER_ID, "lnbcrt1pamountless")) - - assertNull(sut.admit(LaunchRequest.Handoff(ID))) - assertNull(sut.admit(LaunchRequest.Handoff(OTHER_ID))) - - assertEquals( - listOf(PayResultDoc(ID, PayResult.Refused), PayResultDoc(OTHER_ID, PayResult.Refused)), - dropped, - ) - } - - @Test - fun `a handed-off request the screens drop is reported, busy for a send and refused otherwise`() = runTest { - val dropped = mutableListOf() - backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { handoffs.dropped.collect { dropped += it } } - val handoff = LaunchRequest.Send("lightning:$INVOICE", handoffId = ID) - - sut.onDrop(handoff, isBusy = true) - sut.onDrop(handoff, isBusy = false) - - assertEquals(listOf(PayResultDoc(ID, PayResult.Busy), PayResultDoc(ID, PayResult.Refused)), dropped) - } - - @Test - fun `a dropped request the phone did not hand over is reported to nobody`() = runTest { - val dropped = mutableListOf() - backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { handoffs.dropped.collect { dropped += it } } - - sut.onDrop(SEND, isBusy = true) - sut.onDrop(LaunchRequest.Receive, isBusy = false) - - assertEquals(emptyList(), dropped) - } - private companion object { val SEND = LaunchRequest.Send("lightning:lnbcrt1invoice") val OTHER = LaunchRequest.Send("lightning:lnbcrt1other") - val ID = "ab".repeat(16) - val OTHER_ID = "cd".repeat(16) - const val INVOICE = "lnbcrt10u1pinvoice" } } diff --git a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt index 7ebfb9a94b..cf79d0a270 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt @@ -145,58 +145,4 @@ class LaunchRequestTest { assertNull(LaunchRequest.from(Intent.ACTION_VIEW, "bitkitwear://other", open = null)) assertNull(LaunchRequest.from(Intent.ACTION_MAIN, "bitkitwear://pair", open = null)) } - - @Test - fun `the phone's handoff link names its request by id alone`() { - val id = "ab".repeat(16) - - assertEquals(LaunchRequest.Handoff(id), view("bitkitwear://pay?id=$id")) - assertEquals(LaunchRequest.Handoff(id), view("bitkitwear://pay?x=1&id=$id")) - assertNull(view("bitkitwear://pay?id=nope")) - assertNull(view("bitkitwear://pay?id=${id.uppercase()}")) - assertNull(view("bitkitwear://pay")) - assertNull(LaunchRequest.from(Intent.ACTION_MAIN, "bitkitwear://pay?id=$id", open = null)) - } - - @Test - fun `a handed-off bolt11 invoice with an amount is a send that never goes out under quickpay`() { - val id = "ab".repeat(16) - val expected = LaunchRequest.Send("lightning:lnbcrt10u1px", handoffId = id) - - assertEquals(expected, LaunchRequest.handedOff(id, "lnbcrt10u1px")) - assertEquals(expected, LaunchRequest.handedOff(id, "lightning:lnbcrt10u1px")) - assertEquals(true, expected.isHandoff) - assertEquals(false, LaunchRequest.Send("lightning:lnbcrt10u1px").isHandoff) - listOf("lnbc2500u1px", "lntb1m1px", "lntbs15n1px", "LNBCRT20P1PX", "LIGHTNING:LNBC11PX").forEach { - assertEquals(true, LaunchRequest.handedOff(id, it)?.isHandoff, it) - } - } - - @Test - fun `a handed-off input that is no bolt11 invoice with an amount is refused`() { - val id = "ab".repeat(16) - - listOf( - "lnbcrt1pamountless", - "lightning:lnbc1pamountless", - "lnbcrt0u1px", - "lnbcrt10u1", - "lnbcrt10x1px", - "lnsb10u1px", - "lnurl1dp68gurn8ghj7example", - "lightning:lnurl1dp68gurn8ghj7example", - "lightning:user@example.com", - "user@example.com", - "lno1qgsqvgnwgcg35z6ee2h3yczraddm72xrfua9uve2rlrm9deu7xyfzr", - "lightning://lnbcrt10u1px", - "lightning:", - "bitcoin:bcrt1qexample?lightning=lnbcrt10u1px", - "lnurlp://example.com/pay", - "spark:sprt1example", - "bitkitwear://pay?id=$id", - " ", - ).forEach { assertNull(LaunchRequest.handedOff(id, it), it) } - } - - private fun view(data: String) = LaunchRequest.from(Intent.ACTION_VIEW, data, open = null) } diff --git a/wear/src/test/java/to/bitkit/wear/ui/components/CelebrationTest.kt b/wear/src/test/java/to/bitkit/wear/ui/components/CelebrationTest.kt new file mode 100644 index 0000000000..dd2c6fcb9a --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/components/CelebrationTest.kt @@ -0,0 +1,110 @@ +package to.bitkit.wear.ui.components + +import androidx.activity.ComponentActivity +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.junit4.StateRestorationTester +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * When a success is first shown and celebrated: once, as it is first shown awake, and never again on waking, on being + * shown again or on a new screen. + */ +@Config(sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class CelebrationTest { + @get:Rule + val composeRule = createAndroidComposeRule() + + private var key by mutableStateOf("payment-0") + private var isAmbient by mutableStateOf(false) + private var celebration: Celebration? = null + + private fun setContent() = composeRule.setContent { celebration = rememberCelebration(key, isAmbient) } + + private fun isCelebrated(): Boolean { + composeRule.waitForIdle() + return checkNotNull(celebration).isCelebrated + } + + @Test + fun `a success first shown awake is celebrated until the watch goes ambient, and not again on waking`() { + setContent() + assertTrue(isCelebrated()) + + isAmbient = true + assertFalse(isCelebrated()) + + isAmbient = false + assertFalse(isCelebrated()) + } + + @Test + fun `a success first shown in ambient mode is never celebrated`() { + isAmbient = true + setContent() + assertFalse(isCelebrated()) + + isAmbient = false + assertFalse(isCelebrated()) + } + + @Test + fun `no success is no celebration, and the next success is celebrated`() { + key = null + setContent() + assertFalse(isCelebrated()) + + key = "payment-0" + assertTrue(isCelebrated()) + key = null + assertFalse(isCelebrated()) + key = "payment-1" + assertTrue(isCelebrated()) + } + + @Test + fun `a success cut short awake and shown again is not celebrated again`() { + setContent() + assertTrue(isCelebrated()) + + key = null + assertFalse(isCelebrated()) + key = "payment-0" + assertFalse(isCelebrated()) + assertFalse(checkNotNull(celebration).isFirstShown) + } + + @Test + fun `a success is first shown once, in ambient mode too`() { + isAmbient = true + var firstShows = 0 + composeRule.setContent { if (rememberCelebration(key, isAmbient).isFirstShown) firstShows++ } + composeRule.waitForIdle() + assertEquals(1, firstShows) + + isAmbient = false + composeRule.waitForIdle() + assertEquals(1, firstShows) + } + + @Test + fun `a success is neither celebrated nor first shown again when the screen is made again`() { + val restoration = StateRestorationTester(composeRule) + restoration.setContent { celebration = rememberCelebration(key, isAmbient) } + assertTrue(isCelebrated()) + + restoration.emulateSavedInstanceStateRestore() + + assertEquals(Celebration(isFirstShown = false, isCelebrated = false), celebration) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/components/RecordingHapticFeedback.kt b/wear/src/test/java/to/bitkit/wear/ui/components/RecordingHapticFeedback.kt new file mode 100644 index 0000000000..f25db86268 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/components/RecordingHapticFeedback.kt @@ -0,0 +1,13 @@ +package to.bitkit.wear.ui.components + +import androidx.compose.ui.hapticfeedback.HapticFeedback +import androidx.compose.ui.hapticfeedback.HapticFeedbackType + +/** A haptic that plays nothing and keeps each one asked for, in order. */ +internal class RecordingHapticFeedback : HapticFeedback { + val played = mutableListOf() + + override fun performHapticFeedback(hapticFeedbackType: HapticFeedbackType) { + played += hapticFeedbackType + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/components/SendOutcomeOverlayTest.kt b/wear/src/test/java/to/bitkit/wear/ui/components/SendOutcomeOverlayTest.kt index 63416e26c8..032a8bc7a1 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/components/SendOutcomeOverlayTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/components/SendOutcomeOverlayTest.kt @@ -1,6 +1,13 @@ package to.bitkit.wear.ui.components import androidx.activity.ComponentActivity +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.assert @@ -14,6 +21,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import to.bitkit.wear.ui.ShownOutcome import to.bitkit.wear.ui.screens.home.DisplayAmount +import kotlin.test.assertEquals /** * The outcome overlay as a screen reader gets it: one line with the status and the amount, which is also its pane @@ -24,6 +32,10 @@ import to.bitkit.wear.ui.screens.home.DisplayAmount class SendOutcomeOverlayTest { private companion object { val AMOUNT = DisplayAmount(symbol = "₿", text = "1 000") + + /** A few frames, enough for a change of state to show, well within the confetti's 2 s. */ + const val FRAMES_MS = 100L + fun isPane(title: String) = SemanticsMatcher.expectValue(SemanticsProperties.PaneTitle, title) val isLiveRegion = SemanticsMatcher.keyIsDefined(SemanticsProperties.LiveRegion) } @@ -31,6 +43,11 @@ class SendOutcomeOverlayTest { @get:Rule val composeRule = createAndroidComposeRule() + private fun advanceFrames() { + Snapshot.sendApplyNotifications() + composeRule.mainClock.advanceTimeBy(FRAMES_MS) + } + @Test fun `a sent outcome is a pane titled with its status and amount`() { composeRule.setContent { WearPreview { OutcomeContent(ShownOutcome("id", isSent = true, AMOUNT)) } } @@ -52,6 +69,85 @@ class SendOutcomeOverlayTest { .assert(isPane("Payment failed, ₿ 1 000")) } + @Test + fun `a sent outcome shown for the first time lets the confetti fall, and a failed one has none`() { + composeRule.mainClock.autoAdvance = false + var outcome by mutableStateOf(ShownOutcome("id", isSent = true, AMOUNT)) + composeRule.setContent { WearPreview { OutcomeContent(outcome, isCelebrated = outcome.isSent) } } + advanceFrames() + composeRule.onNodeWithTag("WatchConfetti").assertExists() + + outcome = ShownOutcome("id-1", isSent = false, AMOUNT) + advanceFrames() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + } + + @Test + fun `an outcome that is not celebrated, as one shown again after ambient mode, has no confetti`() { + composeRule.mainClock.autoAdvance = false + composeRule.setContent { WearPreview { OutcomeContent(ShownOutcome("id", isSent = true, AMOUNT)) } } + advanceFrames() + + composeRule.onNodeWithTag("WatchOutcomeSent").assertExists() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + } + + @Test + fun `an outcome hidden by ambient mode or cut short plays neither its haptic nor its confetti again`() { + composeRule.mainClock.autoAdvance = false + val haptic = RecordingHapticFeedback() + val sent = ShownOutcome("id", isSent = true, AMOUNT) + var outcome by mutableStateOf(sent) + var isAmbient by mutableStateOf(false) + composeRule.setContent { + WearPreview { + CompositionLocalProvider(LocalHapticFeedback provides haptic) { + OutcomeOverlay(outcome = outcome, isAmbient = isAmbient) + } + } + } + advanceFrames() + composeRule.onNodeWithTag("WatchConfetti").assertExists() + assertEquals(listOf(HapticFeedbackType.Confirm), haptic.played) + + isAmbient = true + advanceFrames() + composeRule.onNodeWithTag("WatchOutcomeSent").assertDoesNotExist() + isAmbient = false + advanceFrames() + composeRule.onNodeWithTag("WatchOutcomeSent").assertExists() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + + // As when the lock screen or leaving the app cuts it short, and it shows again after. + outcome = null + advanceFrames() + outcome = sent + advanceFrames() + composeRule.onNodeWithTag("WatchOutcomeSent").assertExists() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + assertEquals(listOf(HapticFeedbackType.Confirm), haptic.played) + } + + @Test + fun `the next outcome plays its own haptic and confetti`() { + composeRule.mainClock.autoAdvance = false + val haptic = RecordingHapticFeedback() + var outcome by mutableStateOf(ShownOutcome("id", isSent = false, AMOUNT)) + composeRule.setContent { + WearPreview { + CompositionLocalProvider(LocalHapticFeedback provides haptic) { + OutcomeOverlay(outcome = outcome, isAmbient = false) + } + } + } + advanceFrames() + outcome = ShownOutcome("id-1", isSent = true, AMOUNT) + advanceFrames() + + composeRule.onNodeWithTag("WatchConfetti").assertExists() + assertEquals(listOf(HapticFeedbackType.Reject, HapticFeedbackType.Confirm), haptic.played) + } + @Test fun `the outcome is one node, with nothing of its own beneath for a screen reader to step through`() { composeRule.setContent { WearPreview { OutcomeContent(ShownOutcome("id", isSent = true, AMOUNT)) } } diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityDetailContentTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityDetailContentTest.kt new file mode 100644 index 0000000000..6457732367 --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityDetailContentTest.kt @@ -0,0 +1,101 @@ +package to.bitkit.wear.ui.screens.activity + +import androidx.activity.ComponentActivity +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onRoot +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.swipeUp +import androidx.compose.ui.unit.dp +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.wear.models.BitcoinDisplayUnit +import to.bitkit.wear.models.WatchPayment +import to.bitkit.wear.ui.components.WearPreview +import kotlin.test.assertTrue + +/** + * A payment's detail: in the middle of the screen when it fits, its note hidden in ambient mode, and a status that + * every round screen reaches. + */ +@Config(sdk = [34], qualifiers = "w227dp-h227dp-round") +@RunWith(RobolectricTestRunner::class) +class ActivityDetailContentTest { + private companion object { + val NOTED = PreviewPayment.copy(feeSats = 250uL, message = "Coffee and two croissants at the corner bakery") + val SHORT = PreviewPayment.copy(isSent = false, feeSats = 0uL) + + /** How far the middle of a centered detail may sit from the middle of the screen. */ + val CENTER_TOLERANCE = 6.dp + } + + @get:Rule + val composeRule = createAndroidComposeRule() + + private var isAmbient by mutableStateOf(false) + + @Test + fun `a sent payment with a fee and a note scrolls to its status`() = assertStatusReached() + + @Test + @Config(sdk = [34], qualifiers = "w192dp-h192dp-round") + fun `a sent payment with a fee and a note scrolls to its status on the smallest round screen`() = + assertStatusReached() + + @Test + fun `a payment that fits sits in the middle of the screen`() = assertCentered() + + @Test + @Config(sdk = [34], qualifiers = "w192dp-h192dp-round") + fun `a payment that fits sits in the middle of the smallest round screen`() = assertCentered() + + @Test + fun `the note shows awake and hides in ambient mode, with the amount`() { + setContent() + composeRule.onNodeWithTag("WatchActivityDetailMessage").assertTextEquals(NOTED.message.orEmpty()) + + isAmbient = true + composeRule.onNodeWithTag("WatchActivityDetailMessage").assertDoesNotExist() + composeRule.onNodeWithTag("WatchActivityDetailAmount", useUnmergedTree = true).assertDoesNotExist() + composeRule.onNodeWithTag("WatchActivityDetailStatus").assertIsDisplayed() + } + + private fun assertStatusReached() { + setContent() + composeRule.onNodeWithTag("WatchActivityDetailAmount", useUnmergedTree = true).assertIsDisplayed() + + composeRule.onRoot().performTouchInput { swipeUp() } + + composeRule.onNodeWithTag("WatchActivityDetailStatus").assertIsDisplayed() + composeRule.onNodeWithTag("WatchActivityDetailTime").assertIsDisplayed() + } + + private fun assertCentered() { + setContent(SHORT) + composeRule.waitForIdle() + + val screen = composeRule.onRoot().getUnclippedBoundsInRoot() + val top = composeRule.onNodeWithTag("WatchActivityDetailAmount", useUnmergedTree = true) + .getUnclippedBoundsInRoot().top + val bottom = composeRule.onNodeWithTag("WatchActivityDetailStatus").getUnclippedBoundsInRoot().bottom + val offset = (top + bottom) / 2 - (screen.top + screen.bottom) / 2 + assertTrue(offset < CENTER_TOLERANCE && -offset < CENTER_TOLERANCE, "content middle is $offset off center") + } + + private fun setContent(payment: WatchPayment = NOTED) { + composeRule.setContent { + WearPreview { + ActivityDetailContent(payment = payment, unit = BitcoinDisplayUnit.MODERN, isAmbient = isAmbient) + } + } + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityTimeTextTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityTimeTextTest.kt new file mode 100644 index 0000000000..b50f8dcceb --- /dev/null +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/activity/ActivityTimeTextTest.kt @@ -0,0 +1,36 @@ +package to.bitkit.wear.ui.screens.activity + +import org.junit.Test +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.util.Locale +import kotlin.test.assertEquals + +/** The activity list writes its times as the phone's does: the time today, the day this year, the year before. */ +class ActivityTimeTextTest { + private fun text(timestamp: ZonedDateTime, is24Hour: Boolean = false) = + activityTimeText(timestamp.toEpochSecond(), NOW.toEpochSecond(), is24Hour, Locale.US, ZoneOffset.UTC) + + @Test + fun `a payment of today shows its time alone, in 12 or 24 hours`() { + val payment = NOW.withHour(9).withMinute(5) + + assertEquals("9:05 AM", text(payment)) + assertEquals("09:05", text(payment, is24Hour = true)) + } + + @Test + fun `a payment earlier this year shows its day and time`() { + assertEquals("March 3, 6:40 PM", text(ZonedDateTime.of(2026, 3, 3, 18, 40, 0, 0, ZoneOffset.UTC))) + assertEquals("November 28, 23:59", text(NOW.minusDays(1).withHour(23).withMinute(59), is24Hour = true)) + } + + @Test + fun `a payment of an earlier year shows the year too`() { + assertEquals("December 31 2025, 11:00 PM", text(ZonedDateTime.of(2025, 12, 31, 23, 0, 0, 0, ZoneOffset.UTC))) + } + + private companion object { + val NOW: ZonedDateTime = ZonedDateTime.of(2026, 11, 29, 14, 30, 0, 0, ZoneOffset.UTC) + } +} diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt index d7bbe720c1..f47bce42b9 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt @@ -1,6 +1,13 @@ package to.bitkit.wear.ui.screens.receive import androidx.activity.ComponentActivity +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.semantics.SemanticsActions import androidx.compose.ui.semantics.getOrNull import androidx.compose.ui.test.SemanticsMatcher @@ -8,6 +15,7 @@ import androidx.compose.ui.test.assert import androidx.compose.ui.test.assertContentDescriptionEquals import androidx.compose.ui.test.assertHasNoClickAction import androidx.compose.ui.test.click +import androidx.compose.ui.test.junit4.StateRestorationTester import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithTag @@ -22,6 +30,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowSystemClock import to.bitkit.wear.ui.components.NfcHintState +import to.bitkit.wear.ui.components.RecordingHapticFeedback import to.bitkit.wear.ui.components.WearPreview import to.bitkit.wear.ui.screens.home.DisplayAmount import kotlin.test.assertEquals @@ -33,10 +42,20 @@ import kotlin.time.toJavaDuration @Config(sdk = [34], qualifiers = "w227dp-h227dp-round") @RunWith(RobolectricTestRunner::class) class ReceiveQrContentTest { + private companion object { + /** A few frames, enough for a change of state to show, well within the confetti's 2 s. */ + const val FRAMES_MS = 100L + } + @get:Rule val composeRule = createAndroidComposeRule() - private val paid = ReceiveUiState(paidAmount = DisplayAmount(symbol = "₿", text = "50 000")) + private fun advanceFrames() { + Snapshot.sendApplyNotifications() + composeRule.mainClock.advanceTimeBy(FRAMES_MS) + } + + private val paid = ReceiveUiState(paidId = "payment-0", paidAmount = DisplayAmount(symbol = "₿", text = "50 000")) private val shown = ReceiveUiState(qrContent = "LNBCRT1TEST") private var shows = 0 private var refreshes = 0 @@ -88,6 +107,95 @@ class ReceiveQrContentTest { composeRule.onNodeWithTag("WatchReceiveHidden").assertDoesNotExist() } + @Test + fun `a paid invoice celebrates once, and waking from ambient mode does not play it again`() { + composeRule.mainClock.autoAdvance = false + var isAmbient by mutableStateOf(false) + setContent(paid, isAmbient = { isAmbient }) + advanceFrames() + composeRule.onNodeWithTag("WatchConfetti").assertExists() + + isAmbient = true + advanceFrames() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + + isAmbient = false + advanceFrames() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + composeRule.onNodeWithTag("WatchReceivePaidAmount", useUnmergedTree = true).assertExists() + } + + @Test + fun `an invoice paid in ambient mode has no confetti, then or on waking`() { + composeRule.mainClock.autoAdvance = false + var isAmbient by mutableStateOf(true) + setContent(paid, isAmbient = { isAmbient }) + advanceFrames() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + + isAmbient = false + advanceFrames() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + composeRule.onNodeWithTag("WatchReceivePaid").assertExists() + } + + @Test + fun `the next paid invoice is celebrated too`() { + composeRule.mainClock.autoAdvance = false + var uiState by mutableStateOf(paid) + composeRule.setContent { + WearPreview { ReceiveQrContent(uiState = uiState, isAmbient = false, onRefreshClick = {}) } + } + composeRule.mainClock.advanceTimeBy(2_100) + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + + uiState = shown + advanceFrames() + uiState = paid.copy(paidId = "payment-1") + advanceFrames() + + composeRule.onNodeWithTag("WatchConfetti").assertExists() + } + + @Test + fun `a paid invoice plays its haptic once, and not again when the screen is made again`() { + val haptic = RecordingHapticFeedback() + val restoration = StateRestorationTester(composeRule) + restoration.setContent { + WearPreview { + CompositionLocalProvider(LocalHapticFeedback provides haptic) { + ReceiveQrContent(uiState = paid, isAmbient = false, onRefreshClick = {}) + } + } + } + composeRule.waitForIdle() + assertEquals(listOf(HapticFeedbackType.LongPress), haptic.played) + + restoration.emulateSavedInstanceStateRestore() + composeRule.waitForIdle() + + assertEquals(listOf(HapticFeedbackType.LongPress), haptic.played) + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + } + + @Test + fun `an invoice paid in ambient mode plays its haptic, and waking does not play it again`() { + val haptic = RecordingHapticFeedback() + var isAmbient by mutableStateOf(true) + composeRule.setContent { + WearPreview { + CompositionLocalProvider(LocalHapticFeedback provides haptic) { + ReceiveQrContent(uiState = paid, isAmbient = isAmbient, onRefreshClick = {}) + } + } + } + composeRule.waitForIdle() + isAmbient = false + composeRule.waitForIdle() + + assertEquals(listOf(HapticFeedbackType.LongPress), haptic.played) + } + @Test fun `a tap anywhere on the resting screen shows the qr again`() { setContent(shown, isAmbient = false, isResting = true) @@ -204,12 +312,19 @@ class ReceiveQrContentTest { isAmbient: Boolean, isResting: Boolean = false, nfcHint: NfcHintState = NfcHintState.Hidden, + ) = setContent(uiState, isAmbient = { isAmbient }, isResting = isResting, nfcHint = nfcHint) + + private fun setContent( + uiState: ReceiveUiState, + isAmbient: () -> Boolean, + isResting: Boolean = false, + nfcHint: NfcHintState = NfcHintState.Hidden, ) { composeRule.setContent { WearPreview { ReceiveQrContent( uiState = uiState, - isAmbient = isAmbient, + isAmbient = isAmbient(), onRefreshClick = { refreshes++ }, isResting = isResting, nfcHint = nfcHint, diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendResultTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendResultTest.kt index aa31acec2f..5aaf9241fd 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendResultTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendResultTest.kt @@ -1,15 +1,20 @@ package to.bitkit.wear.ui.screens.send import androidx.activity.ComponentActivity +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.assert import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.junit4.StateRestorationTester import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithTag import org.junit.Rule @@ -17,6 +22,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import to.bitkit.wear.ui.components.RecordingHapticFeedback import to.bitkit.wear.ui.components.WearPreview import to.bitkit.wear.ui.screens.home.DisplayAmount import kotlin.test.assertEquals @@ -27,11 +33,19 @@ import kotlin.test.assertEquals class SendResultTest { private companion object { val AMOUNT = DisplayAmount(symbol = "₿", text = "1 000") + + /** A few frames, enough for a change of state to show, well within the confetti's 2 s. */ + const val FRAMES_MS = 100L } @get:Rule val composeRule = createAndroidComposeRule() + private fun advanceFrames() { + Snapshot.sendApplyNotifications() + composeRule.mainClock.advanceTimeBy(FRAMES_MS) + } + @Test fun `a pending result shows its amount`() { setResult(SendStep.Done(SendResult.Pending, AMOUNT), isAmbient = false) @@ -74,6 +88,88 @@ class SendResultTest { composeRule.onNodeWithTag("WatchSendResultAmount").assertDoesNotExist() } + @Test + fun `a sent result pops its check in under confetti that falls once and is gone within 2 s`() { + composeRule.mainClock.autoAdvance = false + setResult(SendStep.Done(SendResult.Sent, AMOUNT), isAmbient = false) + composeRule.mainClock.advanceTimeByFrame() + + composeRule.onNodeWithTag("WatchSendSent").assertIsDisplayed() + composeRule.onNodeWithTag("WatchConfetti").assertExists() + + composeRule.mainClock.advanceTimeBy(2_100) + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + composeRule.onNodeWithTag("WatchSendSent").assertIsDisplayed() + } + + @Test + fun `a sent result celebrates once, and waking from ambient mode does not play it again`() { + composeRule.mainClock.autoAdvance = false + var isAmbient by mutableStateOf(false) + setResult(SendStep.Done(SendResult.Sent, AMOUNT), isAmbient = { isAmbient }) + advanceFrames() + composeRule.onNodeWithTag("WatchConfetti").assertExists() + + isAmbient = true + advanceFrames() + composeRule.onNodeWithTag("WatchSendHidden").assertExists() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + + isAmbient = false + advanceFrames() + composeRule.onNodeWithTag("WatchSendSent").assertExists() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + } + + @Test + fun `a payment sent while in ambient mode has no confetti on waking`() { + composeRule.mainClock.autoAdvance = false + var isAmbient by mutableStateOf(true) + setResult(SendStep.Done(SendResult.Sent, AMOUNT), isAmbient = { isAmbient }) + advanceFrames() + + isAmbient = false + advanceFrames() + composeRule.onNodeWithTag("WatchSendSent").assertExists() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + } + + @Test + fun `a sent result plays its haptic once, and not again when the screen is made again`() { + val haptic = RecordingHapticFeedback() + val restoration = StateRestorationTester(composeRule) + restoration.setContent { + WearPreview { + CompositionLocalProvider(LocalHapticFeedback provides haptic) { + Content( + uiState = SendUiState(step = SendStep.Done(SendResult.Sent, AMOUNT)), + isAmbient = false, + onAmountChange = {}, + onAmountConfirm = {}, + onHoldComplete = {}, + onCloseClick = {}, + ) + } + } + } + composeRule.waitForIdle() + assertEquals(listOf(HapticFeedbackType.Confirm), haptic.played) + + restoration.emulateSavedInstanceStateRestore() + composeRule.waitForIdle() + + assertEquals(listOf(HapticFeedbackType.Confirm), haptic.played) + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + } + + @Test + fun `only a sent result has confetti`() { + setResult(SendStep.Done(SendResult.Pending, AMOUNT), isAmbient = false) + + composeRule.onNodeWithTag("WatchSendPending").assertIsDisplayed() + composeRule.onNodeWithTag("WatchConfetti").assertDoesNotExist() + } + @Test fun `a pending result that turns sent or failed changes the one live line, which a screen reader is told of`() { val isLive = SemanticsMatcher.expectValue(SemanticsProperties.LiveRegion, LiveRegionMode.Polite) @@ -116,12 +212,14 @@ class SendResultTest { composeRule.onNodeWithTag("WatchSendWaiting").assertDoesNotExist() } - private fun setResult(step: SendStep, isAmbient: Boolean) { + private fun setResult(step: SendStep, isAmbient: Boolean) = setResult(step, isAmbient = { isAmbient }) + + private fun setResult(step: SendStep, isAmbient: () -> Boolean) { composeRule.setContent { WearPreview { Content( uiState = SendUiState(step = step), - isAmbient = isAmbient, + isAmbient = isAmbient(), onAmountChange = {}, onAmountConfirm = {}, onHoldComplete = {}, diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt index 7b6dfe439f..ce361f69c1 100644 --- a/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt +++ b/wear/src/test/java/to/bitkit/wear/ui/screens/send/SendViewModelTest.kt @@ -186,25 +186,6 @@ class SendViewModelTest : BaseUnitTest() { verify(paymentsRepo, times(1)).send(prepared) } - @Test - fun `a request the phone handed over is reviewed and held, never paid under quickpay`() = test { - val prepared = prepared() - stubInvoice(prepared) - whenever(paymentsRepo.skipConfirmation(any(), any())).thenReturn(true) - whenever(paymentsRepo.send(prepared)).thenReturn(Result.success(payment(PaymentState.Completed))) - - val sut = createSut(SavedStateHandle(mapOf(Routes.SEND_INPUT to INPUT, Routes.SEND_HANDOFF to true))) - - assertIs(sut.uiState.value.step) - assertTrue(sut.uiState.value.isHoldEnabled) - verify(paymentsRepo, never()).skipConfirmation(any(), any()) - verify(paymentsRepo, never()).send(any()) - - sut.onHoldComplete() - - verify(paymentsRepo, times(1)).send(prepared) - } - @Test fun `quickpay still applies to a link that opened the app and waited a moment for the wallet`() = test { for (status in listOf(WalletStatus.Idle, WalletStatus.Paused, WalletStatus.Connecting)) { diff --git a/wear/src/test/resources/phone-backup-contract.json b/wear/src/test/resources/phone-backup-contract.json index 58f9cbfb15..e7d438d82d 100644 --- a/wear/src/test/resources/phone-backup-contract.json +++ b/wear/src/test/resources/phone-backup-contract.json @@ -8,10 +8,7 @@ "selectedCurrency": "EUR", "isQuickPayEnabled": true, "quickPayAmount": 10, - "quickPayDailyLimitMultiplier": 3, - "isWatchQuickPayEnabled": true, - "watchQuickPayAmount": 1, - "watchQuickPayDailyLimitMultiplier": 5 + "quickPayDailyLimitMultiplier": 3 } }, "networks": { diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkDocs.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkDocs.kt index 3efccfa967..e34093c6e3 100644 --- a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkDocs.kt +++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkDocs.kt @@ -1,7 +1,15 @@ package to.bitkit.wearlink import kotlinx.coroutines.flow.Flow +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.nullable +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.json.Json /** The state documents of a pairing. Each has one writer and is a full snapshot, so applying one twice is harmless. */ @@ -26,9 +34,7 @@ data class ControlDoc(val state: State) { /** * Phone to watch: the phone's settings the watch adopts, as the phone's settings backup names them, and when the - * phone last changed them, by the phone's clock in epoch milliseconds. The three `watch…` values are the watch's own - * QuickPay limits, set on the phone; a phone that predates them sends none, and their defaults leave QuickPay off on - * the watch. + * phone last changed them, by the phone's clock in epoch milliseconds. */ @Serializable data class SettingsDoc( @@ -39,36 +45,8 @@ data class SettingsDoc( val quickPayAmount: Int = 0, val quickPayDailyLimitMultiplier: Int = 0, val changedAtMs: Long = 0, - val isWatchQuickPayEnabled: Boolean = false, - val watchQuickPayAmount: Int = 0, - val watchQuickPayDailyLimitMultiplier: Int = 0, ) -/** - * Phone to watch, a one-shot message: a payment request the phone's user handed to the watch, [input] as the phone - * read it, to be reviewed and held to pay there, never paid under QuickPay. [id] is random per request and names it - * in the answer and in the link that brings the watch app up. - */ -@Serializable -data class PayRequestDoc(val id: String, val input: String) { - override fun toString(): String = "PayRequestDoc(id=$id)" -} - -/** Watch to phone, a one-shot message: what the watch did with the request [id]. Not the payment's outcome. */ -@Serializable -data class PayResultDoc(val id: String, val result: PayResult) - -enum class PayResult { - /** Kept for the link that brings the watch app up on the request's review. */ - Received, - - /** A send is under way on the watch, so the request was dropped. */ - Busy, - - /** Not a request the watch takes, one it already took, or one it kept and then could not show. */ - Refused, -} - /** Watch to phone: what the watch has applied, and whether it still holds the pairing. */ @Serializable data class StatusDoc( @@ -89,8 +67,28 @@ data class StatusDoc( } } -/** A removal the phone asked for and the watch has not acknowledged. */ -enum class Removal { Unpair, Erase } +/** + * A removal the phone asked for and the watch has not acknowledged: the phone only ever asks for an erase. A record + * reads a removal this build does not know, as the `Unpair` of an earlier build, as none, so that the rest of the + * record and its store are kept, and the watch's wallet is not erased for a request that did not ask for it. + */ +enum class Removal { Erase } + +@OptIn(ExperimentalSerializationApi::class) +private object LenientRemovalSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("to.bitkit.wearlink.Removal", PrimitiveKind.STRING).nullable + + override fun serialize(encoder: Encoder, value: Removal?) { + if (value == null) encoder.encodeNull() else encoder.encodeString(value.name) + } + + override fun deserialize(decoder: Decoder): Removal? { + if (!decoder.decodeNotNullMark()) return decoder.decodeNull() + val name = decoder.decodeString() + return Removal.entries.firstOrNull { it.name == name } + } +} /** * One device's note of its pairing. It holds nothing secret: the keys are in the key store, under [pairingId]. @@ -111,6 +109,7 @@ data class LinkRecord( val isPeerLockSet: Boolean = false, val sendCounter: Long = 0, val received: Map = emptyMap(), + @Serializable(with = LenientRemovalSerializer::class) val removal: Removal? = null, val settingsSent: Long = 0, val settingsApplied: Long = 0, diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt index fd38e2d1ff..f49a2f7e91 100644 --- a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt +++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt @@ -96,15 +96,6 @@ abstract class LinkEndpoint internal constructor( return sealed.counter } - /** - * Seals [body] as the one-shot message [name] and sends it once, never stored by the carrier. Fails with - * [LinkError.Unreachable] when the peer cannot be reached now. - */ - protected suspend fun sendOnce(record: LinkRecord, name: String, body: ByteArray) { - val path = LinkPaths.state(record.pairingId, name) - transport.send(record.peerNodeId, path, channel(record.pairingId).seal(path, body).envelope) - } - /** * Replaces the record with the one of a pairing that just finished, dropping the keys of the one before and * whatever an earlier pairing's peer said for the guards. @@ -181,11 +172,6 @@ class PhoneLink( private val onWatchPaired: () -> Unit = {}, nowMs: () -> Long, ) : LinkEndpoint(LinkRole.Phone, transport, keys, store, peer, nowMs) { - private companion object { - /** How many answers to handed-off requests wait for a collector that is slow to take them. */ - const val PAY_RESULT_BUFFER = 16 - } - /** Notes the finished pairing with [link], replacing any earlier watch, and tells the watch it stands. */ suspend fun onPaired(link: PairedLink): LinkRecord = locked { val record = replace(link, nowMs()) @@ -207,38 +193,20 @@ class PhoneLink( } } - private val _payResults = MutableSharedFlow(extraBufferCapacity = PAY_RESULT_BUFFER) - - /** What the watch answered to the payment requests handed to it, as they arrive. */ - val payResults: Flow = _payResults.asSharedFlow() - - /** - * Hands the payment request [input] to the paired watch as the one-shot message [LinkPaths.PAY_REQUEST], under - * [id]. Fails with [LinkError.NotPaired] without a pairing or while a removal waits, and with - * [LinkError.Unreachable] when the watch cannot be reached now; nothing is stored for later. - */ - suspend fun requestPay(id: String, input: String): Unit = locked { - val record = store.load()?.takeIf { it.removal == null } ?: throw LinkError.NotPaired() - sendOnce(record, LinkPaths.PAY_REQUEST, encode(PayRequestDoc(id, input))) - } - - /** Opens [uri] on the paired watch, as the link to a handed-off request. */ - suspend fun openOnWatch(uri: String) { - val record = store.load()?.takeIf { it.removal == null } ?: throw LinkError.NotPaired() - transport.open(record.peerNodeId, uri) - } - /** - * Asks the watch to forget the phone, and with [isErase] to delete its wallet too. The record stays, marked, - * until the watch acknowledges or [forget] drops it: an erase is best effort, since a watch that never - * reconnects never reads it. + * Asks the watch to forget the phone and to delete its wallet: the phone's only removal that waits for the + * watch. The record stays, marked, until the watch acknowledges or [forget] drops it: an erase is best effort, + * since a watch that never reconnects never reads it. An erase that could not be stored for the watch is + * unmarked again and fails, so the phone never waits for a watch that was told nothing. */ - suspend fun remove(isErase: Boolean): Unit = locked { + suspend fun remove(): Unit = locked { val record = store.load() ?: throw LinkError.NotPaired() - val state = if (isErase) ControlDoc.State.Erase else ControlDoc.State.Revoked - val removal = if (isErase) Removal.Erase else Removal.Unpair - store.update { if (it?.pairingId == record.pairingId) it.copy(removal = removal) else it } - publish(record, LinkPaths.CONTROL, encode(ControlDoc(state))) + store.update { if (it?.pairingId == record.pairingId) it.copy(removal = Removal.Erase) else it } + val erase = encode(ControlDoc(ControlDoc.State.Erase)) + runSuspendCatching { publish(record, LinkPaths.CONTROL, erase) }.onFailure { error -> + store.update { if (it?.pairingId == record.pairingId) it.copy(removal = record.removal) else it } + throw error + } } /** @@ -255,10 +223,6 @@ class PhoneLink( } override suspend fun apply(record: LinkRecord, name: String, body: ByteArray, counter: Long) { - if (name == LinkPaths.PAY_RESULT) { - _payResults.tryEmit(decode(body)) - return - } if (name != LinkPaths.STATUS) throw LinkError.Rejected("unknown document") val status = decode(body) if (status.state != StatusDoc.State.Paired) { @@ -301,13 +265,6 @@ interface WatchLinkListener : PeerStateListener { * app publishes from elsewhere, not from inside the call. */ fun onPhonePaired() - - /** - * The phone's user handed [request] to the watch, already authenticated as the paired phone's and new. The app - * keeps it for the link that brings it up on the review, or says why not; the answer goes back to the phone. - * Called while the link handles a packet, so it only decides and stores, and never waits on the screen. - */ - suspend fun onPayRequest(request: PayRequestDoc): PayResult = PayResult.Refused } /** What the watch reports about itself in its status. */ @@ -329,16 +286,6 @@ class WatchLink( record } - /** - * Tells the phone what became of the handed-off request [id] after the watch first answered it, as when the - * watch's app dropped it: busy for a send under way, refused where it could not show it. Nothing is sent - * without a pairing, or when the phone is away. - */ - suspend fun answerPay(id: String, result: PayResult): Unit = locked { - val record = store.load() ?: return@locked - runSuspendCatching { sendOnce(record, LinkPaths.PAY_RESULT, encode(PayResultDoc(id, result))) } - } - /** The wearer's unpair, also before the wallet is removed from the watch: tells the phone, then forgets it. */ suspend fun unpair(): Unit = locked { val record = store.load() ?: return@locked @@ -356,11 +303,6 @@ class WatchLink( } if (updated != null) publishStatus(updated, StatusDoc.State.Paired) } - LinkPaths.PAY_REQUEST -> { - val request = decode(body) - val result = if (request.isWellFormed()) listener.onPayRequest(request) else PayResult.Refused - runSuspendCatching { sendOnce(record, LinkPaths.PAY_RESULT, encode(PayResultDoc(request.id, result))) } - } LinkPaths.CONTROL -> when (decode(body).state) { ControlDoc.State.Paired -> { store.update { if (it?.pairingId == record.pairingId) it.copy(lastSeenMs = nowMs()) else it } diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkHandoff.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkHandoff.kt deleted file mode 100644 index c159450614..0000000000 --- a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkHandoff.kt +++ /dev/null @@ -1,62 +0,0 @@ -package to.bitkit.wearlink - -/** - * A payment request handed from the phone to the watch. The phone sends it authenticated over the link - * ([PayRequestDoc]), and then opens [LinkPaths.payUri] on the watch, since only an activity may bring the watch app - * to the front. The link carries the id alone, so whoever sends it opens nothing: the watch app takes the request - * from [HandoffInbox] by that id, once, and only within [HandoffInbox.WINDOW_MS] of its arrival. A handed-off - * request always ends on the review and the hold to pay, never under QuickPay. `docs/wear.md`, Pairing › Payment - * handoff. - */ -object LinkHandoff { - /** The characters of a request id: 16 random bytes in lowercase hex. */ - const val ID_CHARS = 32 - - /** Above any payment request the phone hands over; a longer input is refused. */ - const val MAX_INPUT_CHARS = 8 * 1024 - - private val ID = Regex("^[0-9a-f]{$ID_CHARS}$") - - fun isId(id: String): Boolean = ID.matches(id) -} - -/** Whether the request has an id the phone makes and an input of a size a payment request has. */ -fun PayRequestDoc.isWellFormed(): Boolean = - LinkHandoff.isId(id) && input.isNotBlank() && input.length <= LinkHandoff.MAX_INPUT_CHARS - -/** - * The handed-off requests the watch received and has not opened yet, in memory only. Each is taken once, by its id, - * and only within [WINDOW_MS] of when it arrived, by the watch's clock; no rule compares the two devices' clocks. The - * last [MAX_IDS] ids stay known after they were taken or dropped, so a request that arrives again under one of them - * is refused. - */ -class HandoffInbox(private val nowMs: () -> Long) { - companion object { - /** How long after it arrived a handed-off request can still be opened on the watch. */ - const val WINDOW_MS = 60_000L - - /** How many request ids the watch remembers. */ - const val MAX_IDS = 20 - } - - private class Entry(val input: String, val arrivedAtMs: Long) - - private val lock = Any() - private val pending = LinkedHashMap() - private val seen = ArrayDeque() - - /** Keeps [request] for the link that opens it. False when its id was seen already, so it is not kept again. */ - fun put(request: PayRequestDoc): Boolean = synchronized(lock) { - if (request.id in seen) return false - seen.addLast(request.id) - while (seen.size > MAX_IDS) pending.remove(seen.removeFirst()) - pending[request.id] = Entry(request.input, nowMs()) - true - } - - /** The input of the request [id], once, while it is within [WINDOW_MS] of its arrival; null otherwise. */ - fun take(id: String): String? = synchronized(lock) { - val entry = pending.remove(id) ?: return null - entry.input.takeIf { nowMs() - entry.arrivedAtMs in 0..WINDOW_MS } - } -} diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt index b0a65129ba..4a7eee0cf2 100644 --- a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt +++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt @@ -78,24 +78,10 @@ object LinkPaths { /** The link the watch app opens its Pair screen for. */ const val PAIR_URI = "bitkitwear://pair" - /** - * The link the watch app opens a handed-off payment request for, by its id alone: the request itself only ever - * arrives authenticated, as [PAY_REQUEST], so any app may send the link and it opens nothing without one. - */ - const val PAY_URI = "bitkitwear://pay" - const val PAY_ID = "id" - const val CONTROL = "p2w/control" const val SETTINGS = "p2w/settings" const val STATUS = "w2p/status" - /** The one-shot messages of a payment handed from the phone to the watch, never stored by the carrier. */ - const val PAY_REQUEST = "p2w/pay" - const val PAY_RESULT = "w2p/pay" - - /** The link that opens the handed-off request [id] on the watch. */ - fun payUri(id: String): String = "$PAY_URI?$PAY_ID=$id" - /** The name of the guard document of [kind] (see [LinkGuards]) that [writer] writes. */ fun guard(writer: LinkRole, kind: String): String = (if (writer == LinkRole.Phone) "p2w" else "w2p") + "/$kind" diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkDocsTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkDocsTest.kt new file mode 100644 index 0000000000..e97f21cd05 --- /dev/null +++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkDocsTest.kt @@ -0,0 +1,34 @@ +package to.bitkit.wearlink + +import kotlin.test.Test +import kotlin.test.assertEquals + +class LinkDocsTest { + @Test + fun `a settings push with the watch's own quickpay keys of an earlier build reads as one without them`() { + val raw = """{"primaryDisplay":"BITCOIN","displayUnit":"MODERN","selectedCurrency":"EUR",""" + + """"isQuickPayEnabled":true,"quickPayAmount":5,"quickPayDailyLimitMultiplier":5,"changedAtMs":100,""" + + """"isWatchQuickPayEnabled":true,"watchQuickPayAmount":20,"watchQuickPayDailyLimitMultiplier":2}""" + + val settings = linkJson.decodeFromString(raw) + + assertEquals(SettingsDoc("BITCOIN", "MODERN", "EUR", true, 5, 5, changedAtMs = 100), settings) + } + + @Test + fun `a record with the unpair removal of an earlier build reads as one without a removal`() { + val record = LinkRecord("pairing", "peer", "node", "Watch", pairedAtMs = 1, removal = Removal.Erase) + val raw = linkJson.encodeToString(record).replace("\"Erase\"", "\"Unpair\"") + + assertEquals(record.copy(removal = null), linkJson.decodeFromString(raw)) + } + + @Test + fun `a record keeps its erase removal and its lack of one`() { + val record = LinkRecord("pairing", "peer", "node", "Watch", pairedAtMs = 1, removal = Removal.Erase) + + assertEquals(record, linkJson.decodeFromString(linkJson.encodeToString(record))) + val none = record.copy(removal = null) + assertEquals(none, linkJson.decodeFromString(linkJson.encodeToString(none))) + } +} diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkEndpointsTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkEndpointsTest.kt index 50b0c9b976..aac0244dac 100644 --- a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkEndpointsTest.kt +++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkEndpointsTest.kt @@ -8,6 +8,7 @@ import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotNull @@ -183,27 +184,11 @@ class LinkEndpointsTest { assertEquals(listOf(500L, 501L), harness.appliedSettings.map { it.changedAtMs }) } - @Test - fun `unpair from the phone ends the pairing on both sides and keeps the watch's wallet`() = runTest { - val harness = paired() - - harness.phoneLink.remove(isErase = false) - assertEquals(Removal.Unpair, assertNotNull(harness.phoneStore.load()).removal) - runCurrent() - - assertNull(harness.watchStore.load()) - assertNull(harness.phoneStore.load()) - assertTrue(harness.watchKeys.keys.isEmpty()) - assertTrue(harness.phoneKeys.keys.isEmpty()) - assertEquals(1, harness.unpairs) - assertEquals(0, harness.erases) - } - @Test fun `erase from the phone is acknowledged before the wallet goes, then the keys`() = runTest { val harness = paired() - harness.phoneLink.remove(isErase = true) + harness.phoneLink.remove() runCurrent() assertEquals(1, harness.erases) @@ -217,12 +202,25 @@ class LinkEndpointsTest { assertTrue(harness.phoneKeys.keys.isEmpty()) } + @Test + fun `an erase that cannot be stored for the watch fails and leaves the watch paired and unmarked`() = runTest { + val harness = paired() + harness.network.isStateWriteFailing = true + + assertFailsWith { harness.phoneLink.remove() } + runCurrent() + + assertNull(assertNotNull(harness.phoneStore.load()).removal) + assertNotNull(harness.watchStore.load()) + assertEquals(0, harness.erases) + } + @Test fun `an erase reaches a watch that was away, after the phone stopped waiting`() = runTest { val harness = paired() harness.network.isConnected = false - harness.phoneLink.remove(isErase = true) + harness.phoneLink.remove() runCurrent() assertEquals(Removal.Erase, assertNotNull(harness.phoneStore.load()).removal) harness.phoneLink.forget() @@ -240,7 +238,7 @@ class LinkEndpointsTest { fun `an erase that failed is run again when the command is delivered again`() = runTest { val harness = paired() harness.eraseFailure = IllegalStateException("disk") - harness.phoneLink.remove(isErase = true) + harness.phoneLink.remove() runCurrent() assertEquals(0, harness.erases) assertNotNull(harness.watchStore.load()) @@ -258,7 +256,7 @@ class LinkEndpointsTest { val harness = paired() val statuses = harness.statePackets(LinkPaths.STATUS).size - harness.phoneLink.remove(isErase = true) + harness.phoneLink.remove() runCurrent() assertEquals(1, harness.eraseNotes) @@ -274,7 +272,7 @@ class LinkEndpointsTest { val harness = paired() val statuses = harness.statePackets(LinkPaths.STATUS).size harness.noteFailure = IllegalStateException("crash") - harness.phoneLink.remove(isErase = true) + harness.phoneLink.remove() runCurrent() assertEquals(0, harness.erases) @@ -299,7 +297,7 @@ class LinkEndpointsTest { val harness = paired() val statuses = harness.statePackets(LinkPaths.STATUS).size harness.crashAfterNote = IllegalStateException("crash") - harness.phoneLink.remove(isErase = true) + harness.phoneLink.remove() runCurrent() assertTrue(harness.eraseNotes > 0) assertEquals(statuses, harness.statePackets(LinkPaths.STATUS).size) @@ -318,7 +316,7 @@ class LinkEndpointsTest { @Test fun `an erase command of an earlier pairing does nothing`() = runTest { val harness = paired() - harness.phoneLink.remove(isErase = true) + harness.phoneLink.remove() runCurrent() val oldErase = harness.statePackets(LinkPaths.CONTROL).last() assertEquals(1, harness.erases) @@ -390,7 +388,7 @@ class LinkEndpointsTest { fun `nothing is published once a removal waits`() = runTest { val harness = paired() harness.network.isConnected = false - harness.phoneLink.remove(isErase = false) + harness.phoneLink.remove() val sent = harness.network.sent.size harness.phoneLink.publishSettings(quickPayOn) diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHandoffTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHandoffTest.kt deleted file mode 100644 index bb3f2375e8..0000000000 --- a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHandoffTest.kt +++ /dev/null @@ -1,265 +0,0 @@ -package to.bitkit.wearlink - -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.async -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.launch -import kotlinx.coroutines.test.TestScope -import kotlinx.coroutines.test.UnconfinedTestDispatcher -import kotlinx.coroutines.test.runCurrent -import kotlinx.coroutines.test.runTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertFalse -import kotlin.test.assertNull -import kotlin.test.assertTrue - -@OptIn(ExperimentalCoroutinesApi::class) -class LinkHandoffTest { - private companion object { - val ID = "ab".repeat(16) - val OTHER_ID = "cd".repeat(16) - const val INVOICE = "lnbcrt10u1pexample" - - fun idOf(index: Int) = index.toString(16).padStart(LinkHandoff.ID_CHARS, '0') - } - - private suspend fun TestScope.paired(harness: LinkHarness = LinkHarness(backgroundScope)): LinkHarness { - val watchSession = harness.watchPairing() - val phoneSession = harness.phonePairing() - val watch = async { watchSession.run() } - val phone = async { phoneSession.run() } - phoneSession.state.first { it is PairingState.Code } - watchSession.state.first { it is PairingState.Code } - watchSession.confirmShown() - phoneSession.confirmShown(isAuthenticated = true) - harness.phoneLink.onPaired(phone.await()) - harness.watchLink.onPaired(watch.await()) - runCurrent() - return harness - } - - private fun TestScope.results(harness: LinkHarness): MutableList { - val results = mutableListOf() - backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { - harness.phoneLink.payResults.collect { results += it } - } - return results - } - - // region watch limits in the settings - - @Test - fun `the watch limits reach the watch with the settings`() = runTest { - val harness = paired() - val settings = SettingsDoc( - isQuickPayEnabled = true, - quickPayAmount = 5, - quickPayDailyLimitMultiplier = 5, - isWatchQuickPayEnabled = true, - watchQuickPayAmount = 1, - watchQuickPayDailyLimitMultiplier = 3, - ) - - harness.phoneLink.publishSettings(settings) - runCurrent() - - val applied = harness.appliedSettings.single() - assertTrue(applied.isWatchQuickPayEnabled) - assertEquals(1, applied.watchQuickPayAmount) - assertEquals(3, applied.watchQuickPayDailyLimitMultiplier) - } - - @Test - fun `settings from a phone that predates the watch limits leave watch quickpay off`() { - val older = """{"isQuickPayEnabled":true,"quickPayAmount":5,"quickPayDailyLimitMultiplier":5,"changedAtMs":1}""" - - val settings = linkJson.decodeFromString(SettingsDoc.serializer(), older) - - assertFalse(settings.isWatchQuickPayEnabled) - assertEquals(0, settings.watchQuickPayAmount) - assertEquals(0, settings.watchQuickPayDailyLimitMultiplier) - } - - // endregion - - // region the request over the link - - @Test - fun `a handed-off request reaches the watch and its answer the phone`() = runTest { - val harness = paired() - val results = results(harness) - - harness.phoneLink.requestPay(ID, INVOICE) - runCurrent() - - assertEquals(listOf(PayRequestDoc(ID, INVOICE)), harness.payRequests) - assertEquals(listOf(PayResultDoc(ID, PayResult.Received)), results) - } - - @Test - fun `the request and its answer are one-shot messages, encrypted, never stored by the carrier`() = runTest { - val harness = paired() - val before = harness.network.sent.size - - harness.phoneLink.requestPay(ID, INVOICE) - runCurrent() - - val handoff = harness.network.sent.drop(before) - assertEquals(2, handoff.size) - assertTrue(handoff.none { it.isState }) - assertTrue(handoff.none { it.payload.decodeToString().contains(INVOICE) }) - assertTrue(handoff[0].path.endsWith(LinkPaths.PAY_REQUEST)) - assertTrue(handoff[1].path.endsWith(LinkPaths.PAY_RESULT)) - } - - @Test - fun `a watch that is busy answers busy`() = runTest { - val harness = paired() - harness.payAnswer = { PayResult.Busy } - val results = results(harness) - - harness.phoneLink.requestPay(ID, INVOICE) - runCurrent() - - assertEquals(listOf(PayResultDoc(ID, PayResult.Busy)), results) - } - - @Test - fun `a request with a malformed id or input is refused without reaching the app`() = runTest { - val harness = paired() - val results = results(harness) - - harness.phoneLink.requestPay("not-an-id", INVOICE) - harness.phoneLink.requestPay(ID, " ") - runCurrent() - - assertTrue(harness.payRequests.isEmpty()) - assertEquals(listOf(PayResult.Refused, PayResult.Refused), results.map { it.result }) - } - - @Test - fun `a replayed request is not taken again`() = runTest { - val harness = paired() - harness.phoneLink.requestPay(ID, INVOICE) - runCurrent() - val request = harness.network.sent.last { it.path.endsWith(LinkPaths.PAY_REQUEST) } - - harness.network.replay(request) - runCurrent() - - assertEquals(1, harness.payRequests.size) - assertTrue(harness.watchErrors.any { it is LinkError.Rejected }) - } - - @Test - fun `an unreachable watch fails the request at once and nothing waits for later`() = runTest { - val harness = paired() - harness.network.isConnected = false - - assertFailsWith { harness.phoneLink.requestPay(ID, INVOICE) } - harness.network.reconnect() - runCurrent() - - assertTrue(harness.payRequests.isEmpty()) - } - - @Test - fun `no request is sent without a pairing or while a removal waits`() = runTest { - val harness = paired() - harness.phoneLink.remove(isErase = false) - - assertFailsWith { harness.phoneLink.requestPay(ID, INVOICE) } - assertFailsWith { LinkHarness(backgroundScope).phoneLink.requestPay(ID, INVOICE) } - } - - @Test - fun `the watch tells the phone later that it dropped a request it had taken`() = runTest { - val harness = paired() - val results = results(harness) - harness.phoneLink.requestPay(ID, INVOICE) - runCurrent() - - harness.watchLink.answerPay(ID, PayResult.Busy) - runCurrent() - - assertEquals(listOf(PayResult.Received, PayResult.Busy), results.map { it.result }) - } - - @Test - fun `the phone opens the request's link on the paired watch`() = runTest { - val harness = paired() - - harness.phoneLink.openOnWatch(LinkPaths.payUri(ID)) - - assertEquals("bitkitwear://pay?id=$ID", harness.network.opened.last()) - } - - @Test - fun `a request prints no input`() { - assertFalse(PayRequestDoc(ID, INVOICE).toString().contains(INVOICE)) - } - - // endregion - - // region the watch's inbox - - @Test - fun `a request is taken once`() { - val inbox = HandoffInbox { 0 } - inbox.put(PayRequestDoc(ID, INVOICE)) - - assertEquals(INVOICE, inbox.take(ID)) - assertNull(inbox.take(ID)) - } - - @Test - fun `a request is not taken after its window`() { - var now = 0L - val inbox = HandoffInbox { now } - inbox.put(PayRequestDoc(ID, INVOICE)) - - now = HandoffInbox.WINDOW_MS + 1 - - assertNull(inbox.take(ID)) - } - - @Test - fun `a request is taken at the end of its window`() { - var now = 0L - val inbox = HandoffInbox { now } - inbox.put(PayRequestDoc(ID, INVOICE)) - - now = HandoffInbox.WINDOW_MS - - assertEquals(INVOICE, inbox.take(ID)) - } - - @Test - fun `an id seen before is not kept again, also after it was taken`() { - val inbox = HandoffInbox { 0 } - assertTrue(inbox.put(PayRequestDoc(ID, INVOICE))) - inbox.take(ID) - - assertFalse(inbox.put(PayRequestDoc(ID, "lnbcrt1other"))) - assertNull(inbox.take(ID)) - } - - @Test - fun `only the last ids are kept, and an old one opens nothing`() { - val inbox = HandoffInbox { 0 } - inbox.put(PayRequestDoc(OTHER_ID, INVOICE)) - repeat(HandoffInbox.MAX_IDS) { inbox.put(PayRequestDoc(idOf(it), INVOICE)) } - - assertNull(inbox.take(OTHER_ID)) - assertEquals(INVOICE, inbox.take(idOf(1))) - } - - @Test - fun `an unknown id opens nothing`() { - assertNull(HandoffInbox { 0 }.take(ID)) - } - - // endregion -} diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt index 84223ca101..fcc2b93e13 100644 --- a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt +++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt @@ -81,10 +81,6 @@ class LinkHarness(scope: CoroutineScope) { /** How often the phone heard, from a pairing's first status, that the watch noted it. */ var watchPaired = 0 - /** The payment requests the watch was handed, and what it answers to them. */ - val payRequests = mutableListOf() - var payAnswer: (PayRequestDoc) -> PayResult = { PayResult.Received } - /** What each side holds of the other's guard documents. */ val phonePeer = RecordingPeer() val watchPeer = RecordingPeer() @@ -135,11 +131,6 @@ class LinkHarness(scope: CoroutineScope) { override fun onPhonePaired() { phonePaired++ } - - override suspend fun onPayRequest(request: PayRequestDoc): PayResult { - payRequests += request - return payAnswer(request) - } }, info = { WatchInfo("1.0 (1)", isLockSet = true) }, nowMs = { now }, diff --git a/wearlink/src/testFixtures/kotlin/to/bitkit/wearlink/testing/Fakes.kt b/wearlink/src/testFixtures/kotlin/to/bitkit/wearlink/testing/Fakes.kt index ff72a34901..e0e8cea27a 100644 --- a/wearlink/src/testFixtures/kotlin/to/bitkit/wearlink/testing/Fakes.kt +++ b/wearlink/src/testFixtures/kotlin/to/bitkit/wearlink/testing/Fakes.kt @@ -35,6 +35,9 @@ class FakeLinkNetwork(private val scope: CoroutineScope) { var hasWatchApp = true var isWatchNearby = true + /** While true, storing a state document fails, as a Data Layer write that throws does. */ + var isStateWriteFailing = false + /** Sees every packet on its way and returns what is delivered instead, or null to drop it. */ var intercept: (Sent) -> ByteArray? = { it.payload } @@ -77,6 +80,7 @@ class FakeLinkNetwork(private val scope: CoroutineScope) { } override suspend fun putState(path: String, payload: ByteArray) { + if (isStateWriteFailing) throw LinkError.Unreachable() states[path] = payload if (isConnected) deliver(path, payload, isState = true) }