diff --git a/app/src/main/java/to/bitkit/data/SettingsStore.kt b/app/src/main/java/to/bitkit/data/SettingsStore.kt index 5c092a5e0b..fbf896117e 100644 --- a/app/src/main/java/to/bitkit/data/SettingsStore.kt +++ b/app/src/main/java/to/bitkit/data/SettingsStore.kt @@ -242,6 +242,16 @@ 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, val isBiometricEnabled: Boolean = false, val isPinForPaymentsEnabled: 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 b14cedfaae..1811b0bd3e 100644 --- a/app/src/main/java/to/bitkit/data/WatchLinkStore.kt +++ b/app/src/main/java/to/bitkit/data/WatchLinkStore.kt @@ -47,19 +47,28 @@ interface WatchGuardState { /** * The phone's note of its paired watch, this install's random id for pairings, the count of seed transfers that - * were started and not finished, and what the watch last said for the shared guards ([WatchGuardState]). It belongs - * to the install and is in no backup: the link keys are in the Keystore and cannot be restored, so a restored phone - * pairs again. Nothing here is secret. + * were started and not finished, what the watch last said for the shared guards ([WatchGuardState]) and the watches + * already offered to pair. It belongs to the install and is in no backup: the link keys are in the Keystore and + * cannot be restored, so a restored phone pairs again. Nothing here is secret. */ @Singleton class WatchLinkStore internal constructor( private val store: DataStore, ) : LinkRecordStore, WatchGuardState { + companion object { + /** How many watches offered to pair are remembered; the oldest is forgotten first. */ + const val PAIR_PROMPTS_KEPT = 10 + } + @Inject constructor(@ApplicationContext context: Context) : this(context.watchLinkDataStore) 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? = @@ -106,6 +115,21 @@ class WatchLinkStore internal constructor( store.updateData { it.copy(watchInvoices = emptyMap(), watchQuickPay = null, watchSends = emptyList()) } } + /** The node ids of the watches the prompt to pair was shown for, oldest first. */ + suspend fun pairPromptNodeIds(): List = store.data.first().pairPromptNodeIds + + /** Notes that the prompt to pair was shown for the watch [nodeId], so it is not shown for it again. */ + suspend fun notePairPrompt(nodeId: String) { + store.updateData { + it.copy(pairPromptNodeIds = (it.pairPromptNodeIds - nodeId + nodeId).takeLast(PAIR_PROMPTS_KEPT)) + } + } + + /** Forgets the watches the prompt to pair was shown for, as when the phone's wallet is wiped. */ + suspend fun clearPairPrompts() { + store.updateData { it.copy(pairPromptNodeIds = emptyList()) } + } + private suspend fun paired(): WatchLinkData? = store.data.first().takeIf { it.record != null } /** This install's id for pairings, made at first use. */ @@ -125,4 +149,5 @@ data class WatchLinkData( val watchInvoices: Map = emptyMap(), val watchQuickPay: QuickPayDoc? = null, val watchSends: List = emptyList(), + val pairPromptNodeIds: List = emptyList(), ) diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index 4f0525c74d..85845593bf 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -989,7 +989,10 @@ class QuickPayAuthorization( val useBiometrics: Boolean, ) -/** One QuickPay setting the user asked to change, with its new value. */ +/** + * 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. + */ sealed interface QuickPayChange { fun isRaise(settings: SettingsData): Boolean fun applyTo(settings: SettingsData): SettingsData @@ -1008,6 +1011,21 @@ 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 b0c5161c48..d8ca2a092a 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt @@ -17,20 +17,28 @@ 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 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 @@ -46,15 +54,20 @@ 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 @@ -65,9 +78,11 @@ 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 @@ -84,6 +99,7 @@ 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 @@ -121,6 +137,12 @@ class WatchLinkRepo internal constructor( private const val READ_BUFFER_BYTES = 8 * 1024 + /** 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 @@ -221,6 +243,14 @@ 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() @@ -229,6 +259,7 @@ class WatchLinkRepo internal constructor( private var session: PhonePairing? = null private var isEnding = false private var isRestartPending = false + private var restartNodeId: String? = null init { transport.attach(::onPacket) @@ -238,6 +269,10 @@ class WatchLinkRepo internal constructor( scope.launch { publishOnChange({ it.openSparkSends() }) { link.publishSends(it) } } } + /** Emits when a watch may have connected, left or got Bitkit; ends quietly without the wearable service. */ + val watchChanges: Flow = transport.nodeChanges + .catch { Logger.warn("Failed to follow the connected watches", it, context = TAG) } + /** The watches connected to this phone, with whether each has Bitkit and is reached directly. */ suspend fun watches(): Result> = withContext(ioDispatcher) { runSuspendCatching { transport.nodes() } @@ -245,21 +280,23 @@ class WatchLinkRepo internal constructor( } /** - * Starts a pairing with the connected watch that has Bitkit and is reached directly, never through the cloud. - * One pairing runs at a time; its progress and its end show in [pairing]. While a cancelled one is still ending, + * Starts a pairing with the connected watch that has Bitkit and is reached directly, never through the cloud: + * the watch [nodeId] when given, as the one the prompt to pair offered, otherwise the first such watch. One + * pairing runs at a time; its progress and its end show in [pairing]. While a cancelled one is still ending, * the new one starts as soon as it has, and the cancelled one's end is not shown. */ - fun startPairing(): Unit = synchronized(lock) { + fun startPairing(nodeId: String? = null): Unit = synchronized(lock) { if (job != null && !isEnding) return _pairing.update { WatchPairingStatus.Running(PairingState.Connecting) } if (job != null) { isRestartPending = true + restartNodeId = nodeId return } var status: WatchPairingStatus = WatchPairingStatus.Idle // Started only once it is noted, so a cancel always finds it, also before it found the watch. val pairing = scope.launch(start = CoroutineStart.LAZY) { - val result = runSuspendCatching { pair() } + val result = runSuspendCatching { pair(nodeId) } result.onFailure { Logger.warn("Failed to pair with the watch", it, context = TAG) } status = result.fold( onSuccess = { WatchPairingStatus.Paired }, @@ -272,8 +309,9 @@ class WatchLinkRepo internal constructor( pairing.start() } - private suspend fun pair() = coroutineScope { - val node = transport.nodes().firstOrNull { it.hasApp && it.isNearby } ?: throw WatchLinkError.NoWatch() + private suspend fun pair(nodeId: String?) = coroutineScope { + val node = transport.nodes().firstOrNull { it.hasApp && it.isNearby && (nodeId == null || it.id == nodeId) } + ?: throw WatchLinkError.NoWatch() val pairing = synchronized(lock) { ensureActive() PhonePairing(transport, link.pairingPackets, node, PairingEnv()).also { session = it } @@ -286,6 +324,9 @@ class WatchLinkRepo internal constructor( } finally { progress.cancel() } + // A watch once paired is not offered to pair again, also after it was unpaired. + runSuspendCatching { store.notePairPrompt(node.id) } + .onFailure { Logger.warn("Failed to note the paired watch as offered", it, context = TAG) } } private fun showProgress(pairing: PhonePairing, state: PairingState) = synchronized(lock) { @@ -301,7 +342,7 @@ class WatchLinkRepo internal constructor( return@synchronized } isRestartPending = false - startPairing() + startPairing(restartNodeId) } /** @@ -315,6 +356,94 @@ class WatchLinkRepo internal constructor( synchronized(lock) { if (!isEnding) session?.confirm(code, isChecked) } } + /** + * The connected watch to offer to pair: one with Bitkit, reached directly, while no watch is paired or being + * removed, that was neither offered before ([notePairPrompt]) nor paired with this phone. Null otherwise, also + * when the watches cannot be listed. + */ + suspend fun watchToOfferPairing(): LinkNode? = withContext(ioDispatcher) { + runSuspendCatching { + if (store.load() != null) return@runSuspendCatching null + val offered = store.pairPromptNodeIds() + transport.nodes().firstOrNull { it.hasApp && it.isNearby && it.id !in offered } + }.onFailure { Logger.warn("Failed to look for a watch to pair", it, context = TAG) }.getOrNull() + } + + /** Notes that the watch [nodeId] was offered to pair, so [watchToOfferPairing] never offers it again. */ + suspend fun notePairPrompt(nodeId: String) = withContext(ioDispatcher) { store.notePairPrompt(nodeId) } + + /** Forgets the watches offered to pair, so a wiped phone offers them again with its next wallet. */ + suspend fun clearPairPrompts(): Result = withContext(ioDispatcher) { + runSuspendCatching { store.clearPairPrompts() } + } + + /** The first connected watch that has no Bitkit, or null, also when the watches cannot be listed. */ + suspend fun watchWithoutApp(): LinkNode? = watches().getOrNull()?.firstOrNull { !it.hasApp } + + /** + * Opens Bitkit's Play listing on the watch [nodeId] (`market://details?id=`), which the watch + * build shares with the phone's. + */ + suspend fun installOnWatch(nodeId: String): Result = withContext(ioDispatcher) { + runSuspendCatching { transport.open(nodeId, "$MARKET_URI$appId") } + .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. @@ -388,8 +517,14 @@ 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() @@ -452,6 +587,13 @@ 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/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 0b0f1eae6d..5c537648f1 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -250,6 +250,8 @@ import to.bitkit.ui.sheets.UpdateSheet import to.bitkit.ui.sheets.UsdtIntroSheet import to.bitkit.ui.sheets.WidgetsSheet import to.bitkit.ui.sheets.hardware.HardwareSheet +import to.bitkit.ui.sheets.watch.WatchInstallSheet +import to.bitkit.ui.sheets.watch.WatchPairSheet import to.bitkit.ui.sheets.watch.WatchSheet import to.bitkit.ui.theme.Colors import to.bitkit.ui.utils.AutoReadClipboardHandler @@ -732,7 +734,7 @@ fun ContentView( viewModel = hiltViewModel(), onDismiss = { appViewModel.hideSheet() }, ) - Sheet.Watch -> WatchSheet(appViewModel) + is Sheet.Watch -> WatchSheet(appViewModel, pairNodeId = sheet.pairNodeId) Sheet.ConnectionClosed -> ConnectionClosedSheet( onDismiss = { appViewModel.hideSheet() }, ) @@ -833,6 +835,15 @@ fun ContentView( onDismiss = { appViewModel.dismissTimedSheet() }, ) + TimedSheetType.WATCH_INSTALL -> WatchInstallSheet( + onDismiss = { appViewModel.dismissTimedSheet() }, + ) + + TimedSheetType.WATCH_PAIR -> WatchPairSheet( + onPair = appViewModel::pairPromptedWatch, + onLater = { appViewModel.dismissTimedSheet() }, + ) + TimedSheetType.HIGH_BALANCE -> { HighBalanceWarningSheet( understoodClick = { appViewModel.dismissTimedSheet() }, diff --git a/app/src/main/java/to/bitkit/ui/components/SheetHost.kt b/app/src/main/java/to/bitkit/ui/components/SheetHost.kt index f504e7b5b0..097bd36a34 100644 --- a/app/src/main/java/to/bitkit/ui/components/SheetHost.kt +++ b/app/src/main/java/to/bitkit/ui/components/SheetHost.kt @@ -100,8 +100,11 @@ sealed interface Sheet { data object ConnectionClosed : Sheet data object TransferUnavailable : Sheet - /** The Wear OS watch: pairing it, its state, unpairing and erasing it. */ - data object Watch : Sheet + /** + * The Wear OS watch: pairing it, its state, unpairing and erasing it. With [pairNodeId] the sheet opens on a + * pairing with that connected watch, as from the prompt to pair it. + */ + data class Watch(val pairNodeId: String? = null) : Sheet data class BTCPayConnection( val setup: SamRockSetupRequest, val isConnecting: Boolean = false, @@ -127,7 +130,9 @@ enum class TimedSheetType(val priority: Int) { NOTIFICATIONS(priority = 3), NFC(priority = 2), QUICK_PAY(priority = 2), - HIGH_BALANCE(priority = 1) + HIGH_BALANCE(priority = 1), + WATCH_PAIR(priority = 1), + WATCH_INSTALL(priority = 0), } @OptIn(ExperimentalMaterial3Api::class) 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 new file mode 100644 index 0000000000..690fac4230 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/PayOnWatch.kt @@ -0,0 +1,97 @@ +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 new file mode 100644 index 0000000000..ab5d368469 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/PayOnWatchViewModel.kt @@ -0,0 +1,59 @@ +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 509a556446..9913cc5b26 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,6 +147,7 @@ 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) } @@ -225,6 +226,7 @@ fun SendConfirmScreen( syncNodeVariant = syncNodeVariant, initialShowDetails = uiState.isInitialSubscriptionPayment && !uiState.shouldAutomaticallyPay, autoPayContent = autoPayContent, + payOnWatchContent = payOnWatchContent, onBack = onBack, onEvent = onEvent, onClickAddTag = onClickAddTag, @@ -306,6 +308,7 @@ 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 = {}, @@ -363,6 +366,7 @@ 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() }, @@ -421,6 +425,7 @@ 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 = {}, @@ -545,6 +550,11 @@ 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( @@ -1009,6 +1019,25 @@ 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/settings/SettingsScreen.kt b/app/src/main/java/to/bitkit/ui/settings/SettingsScreen.kt index e4a5b0f3ef..4d1de2f478 100644 --- a/app/src/main/java/to/bitkit/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/SettingsScreen.kt @@ -184,7 +184,7 @@ fun SettingsScreen( } } SettingsEvent.HardwareWalletsClick -> navController.navigateTo(Routes.HardwareWalletsSettings) - SettingsEvent.WatchClick -> app.showSheet(Sheet.Watch) + SettingsEvent.WatchClick -> app.showSheet(Sheet.Watch()) SettingsEvent.BackupWalletClick -> app.showSheet(Sheet.Backup()) SettingsEvent.DataBackupsClick -> navController.navigateTo(Routes.BackupSettings) SettingsEvent.ResetWalletClick -> 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 df8dfbe392..f24e612906 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -41,6 +41,7 @@ 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 @@ -70,6 +71,7 @@ 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 @@ -606,6 +608,11 @@ 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 new file mode 100644 index 0000000000..00a6b53bc4 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchInstallSheet.kt @@ -0,0 +1,68 @@ +package to.bitkit.ui.sheets.watch + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.tooling.preview.Preview +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import to.bitkit.R +import to.bitkit.ui.components.BottomSheetPreview +import to.bitkit.ui.components.SheetIntro +import to.bitkit.ui.shared.modifiers.sheetHeight +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent + +/** + * The timed sheet that offers once to install Bitkit on a connected watch that has none. Install closes it only once + * the listing opened on the watch; Later and any other dismissal close it for good. + */ +@Composable +fun WatchInstallSheet( + onDismiss: () -> Unit, + viewModel: WatchInstallViewModel = hiltViewModel(), +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + Content( + watchName = uiState.watchName, + onInstall = { viewModel.onInstallClick(onDismiss) }, + onLater = onDismiss, + ) +} + +@Composable +private fun Content( + watchName: String?, + modifier: Modifier = Modifier, + onInstall: () -> Unit = {}, + onLater: () -> Unit = {}, +) { + val name = watchName ?: stringResource(R.string.settings__watch__nav_title) + SheetIntro( + 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, + continueText = stringResource(R.string.settings__watch__install_button), + onContinue = onInstall, + cancelText = stringResource(R.string.common__later), + onCancel = onLater, + testTag = "WatchInstallSheet", + cancelTestTag = "WatchInstallLater", + continueTestTag = "WatchInstallConfirm", + modifier = modifier.sheetHeight(isModal = true) + ) +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + BottomSheetPreview { + Content(watchName = "Pixel Watch 3") + } + } +} diff --git a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchInstallViewModel.kt b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchInstallViewModel.kt new file mode 100644 index 0000000000..f74209b4c0 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchInstallViewModel.kt @@ -0,0 +1,76 @@ +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.async +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.R +import to.bitkit.models.Toast +import to.bitkit.repositories.WatchLinkRepo +import to.bitkit.ui.shared.toast.ToastEventBus +import javax.inject.Inject + +/** + * The prompt to install Bitkit on a connected watch that has none: it names the watch and opens Bitkit's Play + * listing on it (`docs/wear.md`, Pairing › Install prompt). Only created while the watch link is enabled. + */ +@HiltViewModel +class WatchInstallViewModel @Inject constructor( + @ApplicationContext private val context: Context, + private val watchLinkRepo: WatchLinkRepo, +) : ViewModel() { + private val _uiState = MutableStateFlow(WatchInstallUiState()) + val uiState: StateFlow = _uiState.asStateFlow() + + private val lookup = viewModelScope.async { + watchLinkRepo.watchWithoutApp().also { watch -> _uiState.update { it.copy(watchName = watch?.name) } } + } + + /** + * Opens the Play listing on the watch once the look for it has returned, says so, and then calls [onOpen], which + * closes the prompt for good. When no watch without Bitkit is connected any more, or the listing cannot be + * opened, it says the watch is not reachable and the prompt stays, so it is not marked seen for nothing. A tap + * while one is under way does nothing. + */ + fun onInstallClick(onOpen: () -> Unit) { + if (_uiState.value.isInstalling) return + _uiState.update { it.copy(isInstalling = true) } + viewModelScope.launch { + val result = lookup.await()?.let { watchLinkRepo.installOnWatch(it.id) } + sendWatchInstallToast(context, isOpened = result?.isSuccess == true) + _uiState.update { it.copy(isInstalling = false) } + if (result?.isSuccess == true) onOpen() + } + } +} + +/** Says what became of opening Bitkit's Play listing on the watch: to continue there, or that it is not reachable. */ +internal suspend fun sendWatchInstallToast(context: Context, isOpened: Boolean) { + if (isOpened) { + ToastEventBus.send( + type = Toast.ToastType.INFO, + title = context.getString(R.string.settings__watch__install_opened), + ) + return + } + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.common__error), + description = context.getString(R.string.settings__watch__error_unreachable), + ) +} + +/** + * [watchName] is the connected watch without Bitkit, or null while it is looked for or gone. [isInstalling] while + * the listing is being opened on it. + */ +@Immutable +data class WatchInstallUiState(val watchName: String? = null, val isInstalling: Boolean = false) 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 new file mode 100644 index 0000000000..c80f389213 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchPairSheet.kt @@ -0,0 +1,50 @@ +package to.bitkit.ui.sheets.watch + +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.tooling.preview.Preview +import to.bitkit.R +import to.bitkit.ui.components.BottomSheetPreview +import to.bitkit.ui.components.SheetIntro +import to.bitkit.ui.shared.modifiers.sheetHeight +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent + +/** + * The timed sheet that offers to pair a connected watch that has Bitkit. Pair opens the Watch sheet on a pairing, + * which shows the code on both screens and asks for the PIN before it sends a wallet; Later closes it. + */ +@Composable +fun WatchPairSheet( + onPair: () -> Unit, + onLater: () -> Unit, + modifier: Modifier = Modifier, +) { + SheetIntro( + 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, + continueText = stringResource(R.string.settings__watch__pair_confirm), + onContinue = onPair, + cancelText = stringResource(R.string.common__later), + onCancel = onLater, + testTag = "PairedWatchPrompt", + cancelTestTag = "PairedWatchPromptLater", + continueTestTag = "PairedWatchPromptPair", + modifier = modifier.sheetHeight(isModal = true) + ) +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + BottomSheetPreview { + WatchPairSheet(onPair = {}, onLater = {}) + } + } +} 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 new file mode 100644 index 0000000000..701f157ea6 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchQuickPayViewModel.kt @@ -0,0 +1,109 @@ +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 75b98112f8..7c2d8d35f4 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,10 +12,13 @@ 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 @@ -30,18 +33,27 @@ 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.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 @@ -51,6 +63,7 @@ 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. */ @@ -61,18 +74,23 @@ private val REFRESH_INTERVAL = 3.seconds * 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. - * A pairing under way is cancelled when the sheet closes, unless the wallet is already on its way. + * 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. */ @Composable 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() } + LaunchedEffect(viewModel) { viewModel.onSheetOpen(pairNodeId) } val lifecycleOwner = LocalLifecycleOwner.current LaunchedEffect(viewModel, isWaitingForWatch, lifecycleOwner) { if (!isWaitingForWatch) return@LaunchedEffect @@ -88,19 +106,35 @@ 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 { - Content( - uiState = uiState, - onPairClick = viewModel::onPairClick, - onPairClose = viewModel::onPairClose, - onPairConfirm = viewModel::onPairConfirm, - onUnpairClick = viewModel::onUnpairClick, - onEraseClick = viewModel::onEraseClick, - onStopWaitingClick = viewModel::onStopWaitingClick, - onDialogConfirm = viewModel::onDialogConfirm, - onDialogDismiss = viewModel::onDialogDismiss, - onDismiss = { app.hideSheet() }, - ) + 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() }, + ) + } if (uiState.isAuthShown) { AuthCheckView( appViewModel = app, @@ -119,7 +153,9 @@ fun WatchSheet( private fun Content( uiState: WatchSheetUiState, modifier: Modifier = Modifier, + quickPay: WatchQuickPayUiState = WatchQuickPayUiState(), onPairClick: () -> Unit = {}, + onInstallClick: () -> Unit = {}, onPairClose: () -> Unit = {}, onPairConfirm: () -> Unit = {}, onUnpairClick: () -> Unit = {}, @@ -127,10 +163,16 @@ private fun Content( onStopWaitingClick: () -> Unit = {}, onDialogConfirm: () -> Unit = {}, onDialogDismiss: () -> Unit = {}, + onQuickPayClick: () -> Unit = {}, + onQuickPayBack: () -> Unit = {}, + onQuickPayToggle: () -> Unit = {}, + onQuickPayAmountChange: (Int) -> Unit = {}, + onQuickPayLimitChange: (Int) -> Unit = {}, onDismiss: () -> Unit = {}, ) { val pairing = uiState.pairing val paired = uiState.paired + val isQuickPayShown = uiState.isQuickPayShown && pairing == null Column( modifier = modifier .sheetHeight(SheetSize.LARGE) @@ -141,20 +183,39 @@ private fun Content( ) { SheetTopBar( titleText = stringResource( - if (pairing == null) R.string.settings__watch__nav_title else R.string.settings__watch__pair_title, + when { + isQuickPayShown -> R.string.settings__watch__quickpay + 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, onPairClick = onPairClick) + else -> Unpaired( + uiState = uiState, + isQuickPayEnabled = quickPay.isEnabled, + onQuickPayClick = onQuickPayClick, + onPairClick = onPairClick, + onInstallClick = onInstallClick, + ) } VerticalSpacer(16.dp) } @@ -182,7 +243,10 @@ private fun Content( @Composable private fun ColumnScope.Unpaired( uiState: WatchSheetUiState, + isQuickPayEnabled: Boolean, + onQuickPayClick: () -> Unit, onPairClick: () -> Unit, + onInstallClick: () -> Unit, ) { val connected = uiState.connected val text = when { @@ -197,7 +261,19 @@ private fun ColumnScope.Unpaired( color = Colors.White64, modifier = Modifier.testTag("PairedWatchStatus") ) + VerticalSpacer(16.dp) + QuickPayRow(isEnabled = isQuickPayEnabled, onClick = onQuickPayClick) Illustration(R.drawable.phone) + if (connected != null && !connected.hasApp) { + PrimaryButton( + text = stringResource(R.string.settings__watch__install_on_watch), + onClick = onInstallClick, + modifier = Modifier + .fillMaxWidth() + .testTag("PairedWatchInstall") + ) + return + } PrimaryButton( text = stringResource(R.string.settings__watch__pair_button), onClick = onPairClick, @@ -211,6 +287,8 @@ private fun ColumnScope.Unpaired( @Composable private fun ColumnScope.Paired( watch: PairedWatch, + isQuickPayEnabled: Boolean, + onQuickPayClick: () -> Unit, onUnpairClick: () -> Unit, onEraseClick: () -> Unit, onStopWaitingClick: () -> Unit, @@ -268,6 +346,8 @@ 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( @@ -295,6 +375,100 @@ private fun ColumnScope.Paired( ) } +@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") + ) +} + +/** + * 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, @@ -492,3 +666,22 @@ 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 d45e507c77..8c5b91847e 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 @@ -1,14 +1,17 @@ package to.bitkit.ui.sheets.watch +import android.content.Context import androidx.annotation.StringRes 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.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import to.bitkit.R @@ -37,13 +40,16 @@ import javax.inject.Inject */ @HiltViewModel class WatchSheetViewModel @Inject constructor( + @ApplicationContext private val context: Context, private val watchLinkRepo: WatchLinkRepo, ) : ViewModel() { private val _uiState = MutableStateFlow(WatchSheetUiState()) val uiState: StateFlow = _uiState.asStateFlow() private var refreshJob: Job? = null + private var pairRequestJob: Job? = null private var isTransferLeft = false + private var takenPairNodeId: String? = null init { viewModelScope.launch { @@ -69,9 +75,14 @@ class WatchSheetViewModel @Inject constructor( /** * The sheet came up: looks for a connected watch from scratch, and shows a pairing that is still sending the * wallet from before the sheet was closed, or how that one failed meanwhile. One that paired shows as the - * paired watch. + * paired watch. With [pairNodeId], as from the prompt to pair, it then starts a pairing with that watch as Pair + * does, unless a transfer still shows or a watch is paired; the code on both screens and the check before a + * wallet is sent stay as they are. Each prompt's request is taken once, so a sheet composed again, as after the + * activity was recreated, starts nothing, and a sheet closed before the paired check ends starts nothing either. */ - fun onSheetOpen() { + fun onSheetOpen(pairNodeId: String? = null) { + val isPairRequested = pairNodeId != null && pairNodeId != takenPairNodeId + if (isPairRequested) takenPairNodeId = pairNodeId // Only a transfer outlives the sheet; whatever else still shows there was cancelled and is ending. val shown = when (val status = watchLinkRepo.pairing.value) { is WatchPairingStatus.Running if status.state == PairingState.Transferring -> step(status) @@ -79,8 +90,14 @@ class WatchSheetViewModel @Inject constructor( else -> null } isTransferLeft = false - _uiState.update { it.copy(isLoading = true, connected = null, pairing = shown, isAuthShown = false) } + _uiState.update { + it.copy(isLoading = true, connected = null, pairing = shown, isAuthShown = false, isQuickPayShown = false) + } lookForWatch() + if (!isPairRequested || shown != null) return + pairRequestJob = viewModelScope.launch { + if (watchLinkRepo.record.first() == null) startPairing(pairNodeId) + } } /** Looks for a connected watch again, as while the sheet waits for one, unless a look is still under way. */ @@ -96,16 +113,20 @@ class WatchSheetViewModel @Inject constructor( val watch = watches.firstOrNull { it.hasApp && it.isNearby } ?: watches.firstOrNull { it.hasApp } ?: watches.firstOrNull() - val connected = watch?.let { ConnectedWatch(it.name, hasApp = it.hasApp, isNearby = it.isNearby) } + val connected = watch?.let { + ConnectedWatch(it.name, hasApp = it.hasApp, isNearby = it.isNearby, id = it.id) + } _uiState.update { it.copy(isLoading = false, connected = connected) } } } /** Starts a pairing with the connected watch. */ - fun onPairClick() { + fun onPairClick() = startPairing(nodeId = null) + + private fun startPairing(nodeId: String?) { watchLinkRepo.cancelPairing() - _uiState.update { it.copy(pairing = WatchPairStep.Connecting, isAuthShown = false) } - watchLinkRepo.startPairing() + _uiState.update { it.copy(pairing = WatchPairStep.Connecting, isAuthShown = false, isQuickPayShown = false) } + watchLinkRepo.startPairing(nodeId) } /** @@ -146,9 +167,24 @@ class WatchSheetViewModel @Inject constructor( */ fun onSheetClose() { refreshJob?.cancel() + pairRequestJob?.cancel() isTransferLeft = _uiState.value.pairing == WatchPairStep.Sending if (!isTransferLeft) watchLinkRepo.cancelPairing() - _uiState.update { it.copy(pairing = null, isAuthShown = false, dialog = null) } + _uiState.update { it.copy(pairing = null, isAuthShown = false, dialog = null, isQuickPayShown = 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 + viewModelScope.launch { + val result = watchLinkRepo.installOnWatch(watch.id) + sendWatchInstallToast(context, isOpened = result.isSuccess) + } } fun onUnpairClick() = _uiState.update { it.copy(dialog = WatchRemoveDialog.Unpair) } @@ -225,6 +261,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. */ @Immutable data class WatchSheetUiState( @@ -235,11 +272,12 @@ data class WatchSheetUiState( val pairing: WatchPairStep? = null, val isAuthShown: Boolean = false, val dialog: WatchRemoveDialog? = null, + val isQuickPayShown: Boolean = false, ) /** A watch connected to this phone, with whether it has Bitkit and whether it is reached directly. */ @Immutable -data class ConnectedWatch(val name: String, val hasApp: Boolean, val isNearby: Boolean) { +data class ConnectedWatch(val name: String, val hasApp: Boolean, val isNearby: Boolean, val id: String = "") { val canPair: Boolean get() = hasApp && isNearby } diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index a340778cd9..b077233cf1 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -129,6 +129,7 @@ class WipeWalletUseCase @Inject constructor( step("reset cache") { cacheStore.reset() } step("clear watch-only accounts") { watchOnlyAccountRepo.clear() } step("reset widgets") { widgetsStore.reset() } + step("clear watch pair prompts") { watchLinkRepo.get().clearPairPrompts() } blocktankRepo.resetState() activityRepo.resetState() hwWalletRepo.resetState() diff --git a/app/src/main/java/to/bitkit/utils/timedsheets/sheets/WatchInstallTimedSheet.kt b/app/src/main/java/to/bitkit/utils/timedsheets/sheets/WatchInstallTimedSheet.kt new file mode 100644 index 0000000000..1edb73c569 --- /dev/null +++ b/app/src/main/java/to/bitkit/utils/timedsheets/sheets/WatchInstallTimedSheet.kt @@ -0,0 +1,46 @@ +package to.bitkit.utils.timedsheets.sheets + +import kotlinx.coroutines.flow.first +import to.bitkit.data.SettingsStore +import to.bitkit.env.Env +import to.bitkit.repositories.WalletRepo +import to.bitkit.repositories.WatchLinkRepo +import to.bitkit.ui.components.TimedSheetType +import to.bitkit.utils.Logger +import to.bitkit.utils.timedsheets.TimedSheetItem +import javax.inject.Inject +import javax.inject.Provider + +/** + * Offers once to install Bitkit on a connected Wear OS watch that has none, when the phone holds a wallet + * (`docs/wear.md`, Pairing › Install prompt). Only while the watch link is enabled, so never on mainnet; the link + * repository is not created otherwise. + */ +class WatchInstallTimedSheet @Inject constructor( + private val settingsStore: SettingsStore, + private val walletRepo: WalletRepo, + private val watchLinkRepo: Provider, +) : TimedSheetItem { + companion object { + private const val TAG = "WatchInstallTimedSheet" + } + + override val type = TimedSheetType.WATCH_INSTALL + override val priority = type.priority + + override suspend fun shouldShow(): Boolean { + if (!Env.isWatchLinkEnabled) return false + if (settingsStore.data.first().watchInstallPromptSeen) return false + if (!walletRepo.walletExists()) return false + return watchLinkRepo.get().watchWithoutApp() != null + } + + override suspend fun onShown() { + Logger.debug("Watch install sheet shown", context = TAG) + } + + override suspend fun onDismissed() { + settingsStore.update { it.copy(watchInstallPromptSeen = true) } + Logger.debug("Watch install sheet dismissed", context = TAG) + } +} diff --git a/app/src/main/java/to/bitkit/utils/timedsheets/sheets/WatchPairTimedSheet.kt b/app/src/main/java/to/bitkit/utils/timedsheets/sheets/WatchPairTimedSheet.kt new file mode 100644 index 0000000000..8d7abe8b8d --- /dev/null +++ b/app/src/main/java/to/bitkit/utils/timedsheets/sheets/WatchPairTimedSheet.kt @@ -0,0 +1,59 @@ +package to.bitkit.utils.timedsheets.sheets + +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow +import to.bitkit.env.Env +import to.bitkit.repositories.WalletRepo +import to.bitkit.repositories.WatchLinkRepo +import to.bitkit.ui.components.TimedSheetType +import to.bitkit.utils.Logger +import to.bitkit.utils.timedsheets.TimedSheetItem +import javax.inject.Inject +import javax.inject.Provider + +/** + * Offers to pair a connected Wear OS watch that has Bitkit, when the phone holds a wallet and no watch is paired + * (`docs/wear.md`, Pairing › Pair prompt). Later or any other dismissal notes that watch, so it is not offered + * again. Pair notes it only once the pairing succeeded, so a pairing that failed, as without a PIN, lets the prompt + * return on the next app start; unpairing does not offer it again. Only while the watch link is enabled, so never + * on mainnet; the link repository is not created otherwise. + */ +class WatchPairTimedSheet @Inject constructor( + private val walletRepo: WalletRepo, + private val watchLinkRepo: Provider, +) : TimedSheetItem { + companion object { + private const val TAG = "WatchPairTimedSheet" + } + + override val type = TimedSheetType.WATCH_PAIR + override val priority = type.priority + + private var offeredNodeId: String? = null + + override suspend fun shouldShow(): Boolean { + offeredNodeId = null + if (!Env.isWatchLinkEnabled) return false + if (!walletRepo.walletExists()) return false + offeredNodeId = watchLinkRepo.get().watchToOfferPairing()?.id + return offeredNodeId != null + } + + /** + * The user tapped Pair: hands over the watch the sheet offered, for the pairing to start with, and leaves it to + * the pairing to note it, so the dismissal that follows does not. + */ + fun takeOfferedNodeId(): String? = offeredNodeId.also { offeredNodeId = null } + + /** Emits when a watch may have connected, for the prompt to be checked then and not only when Home shows. */ + fun watchChanges(): Flow = if (Env.isWatchLinkEnabled) watchLinkRepo.get().watchChanges else emptyFlow() + + override suspend fun onShown() { + Logger.debug("Watch pair sheet shown", context = TAG) + } + + override suspend fun onDismissed() { + offeredNodeId?.let { watchLinkRepo.get().notePairPrompt(it) } + Logger.debug("Watch pair sheet dismissed", context = TAG) + } +} diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index f71e337fc3..570fc800bf 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -311,6 +311,8 @@ import to.bitkit.utils.timedsheets.sheets.NfcTimedSheet import to.bitkit.utils.timedsheets.sheets.NotificationsTimedSheet import to.bitkit.utils.timedsheets.sheets.QuickPayTimedSheet import to.bitkit.utils.timedsheets.sheets.UsdtTimedSheet +import to.bitkit.utils.timedsheets.sheets.WatchInstallTimedSheet +import to.bitkit.utils.timedsheets.sheets.WatchPairTimedSheet import java.math.BigDecimal import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicLong @@ -383,6 +385,8 @@ class AppViewModel @Inject constructor( private val usdtPreferences: UsdtPreferencesRepo, private val highBalanceSheet: HighBalanceTimedSheet, private val moveToSparkSheet: MoveToSparkTimedSheet, + private val watchPairSheet: WatchPairTimedSheet, + private val watchInstallSheet: WatchInstallTimedSheet, private val moveToSparkRepo: MoveToSparkRepo, private val closeChannelUseCase: CloseChannelUseCase, private val formatMoneyValue: FormatMoneyValue, @@ -735,6 +739,9 @@ class AppViewModel @Inject constructor( registerSheet(nfcSheet) registerSheet(quickPaySheet) registerSheet(highBalanceSheet) + // Registered after High balance at the same priority, so the wallet's own warning comes first. + registerSheet(watchPairSheet) + registerSheet(watchInstallSheet) } private var isCompletingMigration = false private var isCompletingRestoreHold = false @@ -920,6 +927,10 @@ class AppViewModel @Inject constructor( if (authenticated) timedSheetManager.reevaluate() } } + viewModelScope.launch { + // A watch with Bitkit that connects while Home shows gets its prompt then, not on the next Home visit. + watchPairSheet.watchChanges().collect { timedSheetManager.reevaluate() } + } viewModelScope.launch { combine( currentSheet, @@ -11056,6 +11067,12 @@ class AppViewModel @Inject constructor( fun dismissTimedSheet() = timedSheetManager.dismissCurrentSheet() + /** + * Pair on the prompt to pair a watch: opens the Watch sheet on a pairing with the watch the prompt offered, which + * is noted as offered only once that pairing succeeded. + */ + fun pairPromptedWatch() = showSheet(Sheet.Watch(pairNodeId = watchPairSheet.takeOfferedNodeId())) + @VisibleForTesting internal suspend fun checkCriticalAppUpdate(isDebug: Boolean = Env.isDebug) = withContext(bgDispatcher) { if (isDebug) return@withContext diff --git a/app/src/main/java/to/bitkit/watch/WatchDataLayerTransport.kt b/app/src/main/java/to/bitkit/watch/WatchDataLayerTransport.kt index 4a10465e61..50f44e45a7 100644 --- a/app/src/main/java/to/bitkit/watch/WatchDataLayerTransport.kt +++ b/app/src/main/java/to/bitkit/watch/WatchDataLayerTransport.kt @@ -10,6 +10,9 @@ import com.google.android.gms.wearable.CapabilityClient import com.google.android.gms.wearable.PutDataRequest import com.google.android.gms.wearable.Wearable import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.channels.awaitClose +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.suspendCancellableCoroutine import to.bitkit.wearlink.LinkError import to.bitkit.wearlink.LinkNode @@ -53,6 +56,12 @@ class WatchDataLayerTransport @Inject constructor( return nodeClient.connectedNodes.await().map { LinkNode(it.id, it.displayName, it.isNearby, it.id in withApp) } } + override val nodeChanges: Flow = callbackFlow { + val listener = CapabilityClient.OnCapabilityChangedListener { trySend(Unit) } + capabilityClient.addListener(listener, WATCH_CAPABILITY) + awaitClose { capabilityClient.removeListener(listener, WATCH_CAPABILITY) } + } + override suspend fun send(nodeId: String, path: String, payload: ByteArray) { runCatching { messageClient.sendMessage(nodeId, path, payload).await() } .getOrElse { throw LinkError.Unreachable(it) } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index c1f0ec4f52..099ad2db9d 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -908,6 +908,11 @@ تعذّر التحقق من العتاد الآمن لهذه الساعة، لذا لم تُرسَل محفظتك. حدّث Bitkit على هاتفك وساعتك. هذه الساعة تحتوي على محفظتك الكاملة ويمكنها الإنفاق منها. + تثبيت + ثبّت على الساعة + تابع على ساعتك. + لا يوجد Bitkit على {name} بعد. ثبّته للدفع من معصمك. + Bitkit على ساعتك تم التحقق من مفاتيح الساعة في StrongBox. تم التحقق من مفاتيح الساعة في العتاد الآمن. لم يتم التحقق من العتاد الآمن للساعة. @@ -921,10 +926,17 @@ إقران افتح Bitkit على ساعتك. تم إقران ساعتك. + Bitkit موجود على ساعتك. أقرنها بهذا الهاتف لاستخدام محفظتك عليها ومزامنة إعداداتها. + أقرن ساعتك جارٍ إرسال محفظتك إلى الساعة… لا توجد محفظة على هذه الساعة. الإقران يرسل إليها عبارة الاسترداد الخاصة بك، فتصبح حاملة لمحفظتك الكاملة. إقران الساعة أكّد الرمز على ساعتك. + QuickPay على الساعة + تدفع ساعتك بهذه الطريقة حتى ${limit} يوميًا. ومع هذا الهاتف تبقى ضمن حد QuickPay اليومي لهذا الهاتف. + QuickPay متوقف على هذا الهاتف، لذا فهو متوقف على ساعتك أيضًا. + المُنفق اليوم عبر QuickPay على ساعتك: ${spent} + المدفوعات حتى ${amount} على ساعتك لا تحتاج إلى الضغط المطوّل للدفع. لا يوجد رمز PIN على ساعتك، لذا اجعل هذا المبلغ منخفضًا. {name} جاهزة للإقران. الإعدادات ليست على الساعة بعد. إعدادات الساعة محدّثة. @@ -1231,6 +1243,11 @@ انتهاء صلاحية الفاتورة الحد الأقصى القابل للإنفاق أقل قليلاً بسبب الرصيد الاحتياطي المطلوب. الرصيد الاحتياطي + ادفع على الساعة + ساعتك مشغولة بدفعة أخرى. + تعذّر على ساعتك استلام هذه الدفعة. + أُرسل إلى ساعتك. اضغط مطولًا هناك للدفع. + تعذّر الوصول إلى ساعتك. ليس لدى جهة الاتصال هذه أي طريقة دفع يمكن لـ 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 cd413c39be..0c2467dbbd 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -929,6 +929,11 @@ No se pudo verificar el hardware seguro de este reloj, por lo que no se envió su billetera. Actualice Bitkit en su teléfono y en su reloj. Este reloj contiene su billetera completa y puede gastar sus fondos. + Instalar + Instalar en el reloj + Continúa en tu reloj. + {name} aún no tiene Bitkit. Instálalo para pagar desde tu muñeca. + Bitkit en tu reloj Claves del reloj verificadas en StrongBox. Claves del reloj verificadas en hardware seguro. Hardware seguro del reloj no verificado. @@ -942,10 +947,17 @@ Vincular Abra Bitkit en su reloj. Su reloj está vinculado. + Bitkit está en tu reloj. Vincúlalo con este teléfono para usar tu billetera ahí y mantener sus ajustes sincronizados. + Vincula tu reloj Enviando su billetera al reloj… 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. @@ -1262,6 +1274,11 @@ 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 2ba3dd584b..376f1f2f8a 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -923,6 +923,11 @@ No s\'ha pogut verificar el maquinari segur d\'aquest rellotge, de manera que la teva cartera no s\'ha enviat. Actualitza Bitkit al telèfon i al rellotge. Aquest rellotge conté la teva cartera completa i en pot gastar els fons. + Instal·la + Instal·la al rellotge + Continua al rellotge. + {name} encara no té Bitkit. Instal·la\'l per pagar des del canell. + Bitkit al teu rellotge Claus del rellotge verificades a StrongBox. Claus del rellotge verificades al maquinari segur. Maquinari segur del rellotge no verificat. @@ -936,10 +941,17 @@ Vincular Obre Bitkit al teu rellotge. El teu rellotge està vinculat. + Bitkit és al teu rellotge. Vincula\'l amb aquest telèfon per fer-hi servir la cartera i mantenir-ne la configuració sincronitzada. + Vincula el teu rellotge S\'està enviant la teva cartera al rellotge… 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. @@ -1256,6 +1268,11 @@ 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 da41b94409..5e9af241bc 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -928,6 +928,11 @@ Bezpečný hardware těchto hodinek se nepodařilo ověřit, proto vaše peněženka nebyla odeslána. Aktualizujte Bitkit v telefonu i v hodinkách. Tyto hodinky obsahují vaši celou peněženku a mohou z ní utrácet. + Instalovat + Instalovat na hodinky + Pokračujte na hodinkách. + {name} zatím nemá Bitkit. Nainstalujte ho a plaťte ze zápěstí. + Bitkit na vašich hodinkách Klíče hodinek ověřeny ve StrongBox. Klíče hodinek ověřeny v bezpečném hardwaru. Bezpečný hardware hodinek nebyl ověřen. @@ -941,10 +946,17 @@ Spárovat Otevřete Bitkit v hodinkách. Hodinky jsou spárovány. + Bitkit je na vašich hodinkách. Spárujte je s tímto telefonem, abyste na nich mohli používat peněženku a mít nastavení synchronizované. + Spárujte hodinky Odesílání peněženky do hodinek… 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í. @@ -1260,6 +1272,11 @@ 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 80b190f8c3..0d27bc288f 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -765,6 +765,11 @@ Die sichere Hardware dieser Uhr konnte nicht verifiziert werden, daher wurde dein Wallet nicht gesendet. Aktualisiere Bitkit auf deinem Telefon und deiner Uhr. Diese Uhr enthält dein vollständiges Wallet und kann daraus Zahlungen senden. + Installieren + Auf der Uhr installieren + Fahre auf deiner Uhr fort. + Auf {name} ist Bitkit noch nicht installiert. Installiere es, um vom Handgelenk aus zu zahlen. + Bitkit auf deiner Uhr Schlüssel der Uhr in StrongBox verifiziert. Schlüssel der Uhr in sicherer Hardware verifiziert. Sichere Hardware der Uhr nicht verifiziert. @@ -778,10 +783,17 @@ Koppeln Öffne Bitkit auf deiner Uhr. Deine Uhr ist gekoppelt. + Bitkit ist auf deiner Uhr. Kopple sie mit diesem Handy, um dort dein Wallet zu nutzen und ihre Einstellungen synchron zu halten. + Koppel deine Uhr Dein Wallet wird an die Uhr gesendet… 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. @@ -1095,6 +1107,11 @@ 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 12973abf61..3f684bc1c4 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -908,6 +908,11 @@ Το ασφαλές υλικό αυτού του ρολογιού δεν μπόρεσε να επαληθευτεί, οπότε το πορτοφόλι σου δεν στάλθηκε. Ενημέρωσε το Bitkit στο τηλέφωνο και στο ρολόι σου. Αυτό το ρολόι περιέχει ολόκληρο το πορτοφόλι σου και μπορεί να ξοδέψει από αυτό. + Εγκατάσταση + Εγκατάσταση στο ρολόι + Συνεχίστε στο ρολόι σας. + Το {name} δεν έχει ακόμη Bitkit. Εγκαταστήστε το για να πληρώνετε από τον καρπό σας. + Το Bitkit στο ρολόι σας Τα κλειδιά του ρολογιού επαληθεύτηκαν στο StrongBox. Τα κλειδιά του ρολογιού επαληθεύτηκαν σε ασφαλές υλικό. Το ασφαλές υλικό του ρολογιού δεν επαληθεύτηκε. @@ -921,10 +926,17 @@ Σύζευξη Άνοιξε το Bitkit στο ρολόι σου. Το ρολόι σου έχει συζευχθεί. + Το Bitkit είναι στο ρολόι σας. Κάντε σύζευξη με αυτό το τηλέφωνο για να χρησιμοποιείτε εκεί το πορτοφόλι σας και να συγχρονίζονται οι ρυθμίσεις του. + Σύζευξη του ρολογιού σας Αποστολή του πορτοφολιού σου στο ρολόι… Αυτό το ρολόι δεν έχει πορτοφόλι. Η σύζευξη του στέλνει τη φράση ανάκτησής σου, οπότε θα περιέχει ολόκληρο το πορτοφόλι σου. Σύζευξη ρολογιού Επιβεβαίωσε τον κωδικό στο ρολόι σου. + QuickPay στο ρολόι + Το ρολόι σας πληρώνει έτσι έως ${limit} την ημέρα. Μαζί με αυτό το τηλέφωνο μένει εντός του ημερήσιου ορίου QuickPay αυτού του τηλεφώνου. + Το QuickPay είναι απενεργοποιημένο σε αυτό το τηλέφωνο, άρα και στο ρολόι σας. + Δαπανήθηκαν σήμερα με QuickPay στο ρολόι σας: ${spent} + Οι πληρωμές έως ${amount} στο ρολόι σας δεν χρειάζονται παρατεταμένο πάτημα. Το ρολόι σας δεν έχει PIN, οπότε κρατήστε το ποσό χαμηλό. Το {name} είναι έτοιμο για σύζευξη. Οι ρυθμίσεις δεν είναι ακόμη στο ρολόι. Οι ρυθμίσεις του ρολογιού είναι ενημερωμένες. @@ -1236,6 +1248,11 @@ Λήξη τιμολογίου Το μέγιστο δαπανήσιμο ποσό είναι λίγο χαμηλότερο λόγω απαιτούμενου αποθεματικού υπολοίπου. Αποθεματικό υπόλοιπο + Πληρωμή στο ρολόι + Το ρολόι σας είναι απασχολημένο με άλλη πληρωμή. + Το ρολόι σας δεν μπόρεσε να δεχτεί αυτή την πληρωμή. + Στάλθηκε στο ρολόι σας. Πατήστε παρατεταμένα εκεί για πληρωμή. + Το ρολόι σας δεν είναι προσβάσιμο. Αυτή η επαφή δεν έχει τρόπο πληρωμής που μπορεί να χρησιμοποιήσει το Bitkit αυτή τη στιγμή. Δεν είναι δυνατή η πληρωμή αυτής της επαφής Μια προηγούμενη ανάληψη από το υπόλοιπο δαπανών σου διακανονίζεται ακόμη. Δοκίμασε ξανά μόλις ολοκληρωθεί. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index ea84475100..569abefc79 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -926,6 +926,11 @@ No se pudo verificar el hardware seguro de este reloj, por lo que no se envió tu cartera. Actualiza Bitkit en tu teléfono y en tu reloj. Este reloj contiene tu cartera completa y puede gastar tus fondos. + Instalar + Instalar en el reloj + Continúa en tu reloj. + {name} aún no tiene Bitkit. Instálalo para pagar desde tu muñeca. + Bitkit en tu reloj Claves del reloj verificadas en StrongBox. Claves del reloj verificadas en hardware seguro. Hardware seguro del reloj no verificado. @@ -939,10 +944,17 @@ Vincular Abre Bitkit en tu reloj. Tu reloj está vinculado. + Bitkit está en tu reloj. Vincúlalo con este teléfono para usar tu cartera en él y mantener sus ajustes sincronizados. + Vincula tu reloj Enviando tu cartera al reloj… 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. @@ -1257,6 +1269,11 @@ 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 b24fd0f4f0..004e097c11 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -762,6 +762,11 @@ No se pudo verificar el hardware seguro de este reloj, por lo que no se envió su cartera. Actualice Bitkit en su teléfono y en su reloj. Este reloj contiene su cartera completa y puede gastar sus fondos. + Instalar + Instalar en el reloj + Continúa en tu reloj. + {name} aún no tiene Bitkit. Instálalo para pagar desde tu muñeca. + Bitkit en tu reloj Claves del reloj verificadas en StrongBox. Claves del reloj verificadas en hardware seguro. Hardware seguro del reloj no verificado. @@ -775,10 +780,17 @@ Vincular Abra Bitkit en su reloj. Su reloj está vinculado. + Bitkit está en tu reloj. Vincúlalo con este teléfono para usar tu cartera ahí y mantener sus ajustes sincronizados. + Vincula tu reloj Enviando su cartera al reloj… 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. @@ -1093,6 +1105,11 @@ 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 032ffb21e3..4bb96d9303 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -765,6 +765,11 @@ Le matériel sécurisé de cette montre n\'a pas pu être vérifié, votre portefeuille n\'a donc pas été envoyé. Mettez à jour Bitkit sur votre téléphone et votre montre. Cette montre contient votre portefeuille complet et peut dépenser vos fonds. + Installer + Installer sur la montre + Continuez sur votre montre. + Bitkit n\'est pas encore installé sur {name}. Installez-le pour payer depuis votre poignet. + Bitkit sur votre montre Clés de la montre vérifiées dans StrongBox. Clés de la montre vérifiées dans le matériel sécurisé. Matériel sécurisé de la montre non vérifié. @@ -778,10 +783,17 @@ Associer Ouvrez Bitkit sur votre montre. Votre montre est associée. + Bitkit est sur votre montre. Associez-la à ce téléphone pour y utiliser votre portefeuille et garder ses réglages synchronisés. + Associez votre montre Envoi de votre portefeuille à la montre… 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. @@ -1096,6 +1108,11 @@ 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 e767df0977..3114685e44 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -925,6 +925,11 @@ Non è stato possibile verificare l\'hardware sicuro di questo orologio, quindi il tuo wallet non è stato inviato. Aggiorna Bitkit sul telefono e sull\'orologio. Questo orologio contiene il tuo wallet completo e può spenderne i fondi. + Installa + Installa sull\'orologio + Continua sull\'orologio. + {name} non ha ancora Bitkit. Installalo per pagare dal polso. + Bitkit sul tuo orologio Chiavi dell\'orologio verificate in StrongBox. Chiavi dell\'orologio verificate nell\'hardware sicuro. Hardware sicuro dell\'orologio non verificato. @@ -938,10 +943,17 @@ Associa Apri Bitkit sul tuo orologio. Il tuo orologio è associato. + Bitkit è sul tuo orologio. Associalo a questo telefono per usare lì il tuo wallet e mantenerne sincronizzate le impostazioni. + Associa il tuo orologio Invio del tuo wallet all\'orologio… 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. @@ -1258,6 +1270,11 @@ 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 3c85fff08d..5bb726f5ec 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -923,6 +923,11 @@ De veilige hardware van dit horloge kon niet worden geverifieerd, dus je wallet is niet verzonden. Werk Bitkit bij op je telefoon en je horloge. Dit horloge bevat je volledige wallet en kan ermee betalen. + Installeren + Op horloge installeren + Ga verder op je horloge. + {name} heeft nog geen Bitkit. Installeer het om vanaf je pols te betalen. + Bitkit op je horloge Sleutels van het horloge geverifieerd in StrongBox. Sleutels van het horloge geverifieerd in veilige hardware. Veilige hardware van het horloge niet geverifieerd. @@ -936,10 +941,17 @@ Koppelen Open Bitkit op je horloge. Je horloge is gekoppeld. + Bitkit staat op je horloge. Koppel het aan deze telefoon om daar je wallet te gebruiken en de instellingen gelijk te houden. + Koppel je horloge Je wallet naar het horloge verzenden… 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. @@ -1253,6 +1265,11 @@ 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 ef62f31260..553dbda4d5 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -766,6 +766,11 @@ Nie udało się zweryfikować bezpiecznego sprzętu tego zegarka, więc Twój portfel nie został wysłany. Zaktualizuj Bitkit na telefonie i zegarku. Ten zegarek przechowuje Twój pełny portfel i może wydawać z niego środki. + Zainstaluj + Zainstaluj na zegarku + Kontynuuj na zegarku. + {name} nie ma jeszcze Bitkit. Zainstaluj go, aby płacić z nadgarstka. + Bitkit na zegarku Klucze zegarka zweryfikowane w StrongBox. Klucze zegarka zweryfikowane w bezpiecznym sprzęcie. Bezpieczny sprzęt zegarka niezweryfikowany. @@ -779,10 +784,17 @@ Sparuj Otwórz Bitkit na zegarku. Twój zegarek jest sparowany. + Bitkit jest na Twoim zegarku. Sparuj go z tym telefonem, aby korzystać na nim z portfela i synchronizować jego ustawienia. + Sparuj zegarek Wysyłam Twój portfel do zegarka… 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. @@ -1098,6 +1110,11 @@ 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 e6c3bb4597..39c8818b00 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -930,6 +930,11 @@ Não foi possível verificar o hardware seguro deste relógio, então sua carteira não foi enviada. Atualize a Bitkit no telefone e no relógio. Este relógio contém sua carteira completa e pode gastar seus fundos. + Instalar + Instalar no relógio + Continue no seu relógio. + {name} ainda não tem o Bitkit. Instale para pagar pelo pulso. + Bitkit no seu relógio Chaves do relógio verificadas no StrongBox. Chaves do relógio verificadas em hardware seguro. Hardware seguro do relógio não verificado. @@ -943,10 +948,17 @@ Parear Abra a Bitkit no seu relógio. Seu relógio está pareado. + O Bitkit está no seu relógio. Pareie-o com este celular para usar sua carteira nele e manter as configurações sincronizadas. + Pareie seu relógio Enviando sua carteira para o relógio… 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. @@ -1262,6 +1274,11 @@ 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 a86f2e8e92..921ee16736 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -744,6 +744,11 @@ Não foi possível verificar o hardware seguro deste relógio, por isso a sua carteira não foi enviada. Atualize a Bitkit no telemóvel e no relógio. Este relógio contém a sua carteira completa e pode gastar os seus fundos. + Instalar + Instalar no relógio + Continue no relógio. + {name} ainda não tem a Bitkit. Instale-a para pagar a partir do pulso. + Bitkit no seu relógio Chaves do relógio verificadas no StrongBox. Chaves do relógio verificadas em hardware seguro. Hardware seguro do relógio não verificado. @@ -757,10 +762,17 @@ Emparelhar Abra a Bitkit no seu relógio. O seu relógio está emparelhado. + A Bitkit está no seu relógio. Emparelhe-o com este telemóvel para usar a sua carteira nele e manter as definições sincronizadas. + Emparelhe o seu relógio A enviar a sua carteira para o relógio… 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. @@ -962,6 +974,11 @@ 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 2c1f4ce0c1..ca5ba22a98 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -942,6 +942,11 @@ Не удалось проверить защищённый модуль этих часов, поэтому ваш кошелёк не был отправлен. Обновите Bitkit на телефоне и на часах. На этих часах хранится ваш кошелёк целиком, и с них можно тратить средства. + Установить + Установить На Часы + Продолжите на часах. + На {name} ещё нет Bitkit. Установите его, чтобы платить с запястья. + Bitkit На Ваших Часах Ключи часов проверены в StrongBox. Ключи часов проверены в защищённом модуле. Защищённый модуль часов не проверен. @@ -955,10 +960,17 @@ Сопрячь Откройте Bitkit на часах. Часы сопряжены. + Bitkit уже на ваших часах. Сопрягите их с этим телефоном, чтобы пользоваться на них кошельком и синхронизировать их настройки. + Сопрягите Часы Отправка кошелька на часы… На этих часах нет кошелька. При сопряжении на них отправляется ваша фраза восстановления, поэтому на них будет храниться ваш кошелёк целиком. Сопряжение Часов Подтвердите код на часах. + QuickPay На Часах + Так часы платят до ${limit} в день. Вместе с этим телефоном они остаются в пределах дневного лимита QuickPay этого телефона. + QuickPay выключен на этом телефоне, а значит, и на часах. + Потрачено сегодня через QuickPay на часах: ${spent} + Платежи до ${amount} на часах проходят без удержания. На часах нет PIN-кода, поэтому держите сумму небольшой. Устройство {name} готово к сопряжению. Настройки ещё не переданы на часы. Настройки часов актуальны. @@ -1275,6 +1287,11 @@ Срок действия инвойса Максимальная сумма для траты немного меньше из-за необходимого резервного баланса. Резервный баланс + Оплатить На Часах + Часы заняты другим платежом. + Часы не смогли принять этот платёж. + Отправлено на часы. Удерживайте там для оплаты. + Часы недоступны. У этого контакта сейчас нет способа оплаты, который может использовать Bitkit. Невозможно оплатить этому контакту Предыдущий вывод с вашего баланса расходов ещё проводится. Попробуйте ещё раз после его завершения. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 864c33d60c..efaee5867c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1266,6 +1266,11 @@ This watch\'s secure hardware could not be verified, so your wallet was not sent. Update Bitkit on your phone and your watch. This watch holds your full wallet and can spend from it. + Install + Install on Watch + Continue on your watch. + {name} has no Bitkit yet. Install it to pay from your wrist. + Bitkit on Your Watch Watch keys verified in StrongBox. Watch keys verified in secure hardware. Watch secure hardware not verified. @@ -1279,10 +1284,17 @@ Pair Open Bitkit on your watch. Your watch is paired. + Bitkit is on your watch. Pair it with this phone to use your wallet there and keep its settings in sync. + Pair Your Watch Sending your wallet to the watch… 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. @@ -1825,6 +1837,11 @@ 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/models/BackupJsonTest.kt b/app/src/test/java/to/bitkit/models/BackupJsonTest.kt index 6b757dc4ab..3bbf06ee2d 100644 --- a/app/src/test/java/to/bitkit/models/BackupJsonTest.kt +++ b/app/src/test/java/to/bitkit/models/BackupJsonTest.kt @@ -69,6 +69,30 @@ class BackupJsonTest { assertEquals(SettingsData().quickPayAmount, settings.quickPayAmount) } + @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() + + assertEquals(false, settings.isWatchQuickPayEnabled) + assertEquals(defaults.watchQuickPayAmount, settings.watchQuickPayAmount) + assertEquals(defaults.watchQuickPayDailyLimitMultiplier, settings.watchQuickPayDailyLimitMultiplier) + assertEquals(false, settings.watchInstallPromptSeen) + } + + @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 + + assertEquals(true, settings.isQuickPayEnabled) + assertEquals(true, settings.isWatchQuickPayEnabled) + assertEquals(1, settings.watchQuickPayAmount) + assertEquals(3, settings.watchQuickPayDailyLimitMultiplier) + } + @Test fun `rejects a settings envelope without settings`() { assertFails { decodeSettingsBackup("""{"version":1,"createdAt":1}""") } diff --git a/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt b/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt index 52817bf0f9..598b89791f 100644 --- a/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt +++ b/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt @@ -15,8 +15,9 @@ 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, six - * settings as this app encodes them, 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, 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` * 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. */ @@ -34,7 +35,7 @@ class WatchBackupContractTest { } @Test - fun `the settings backup holds the six settings the watch reads, in the form it reads`() { + fun `the settings backup holds the nine settings the watch reads, in the form it reads`() { val expected = contract.getValue("settingsBackup").jsonObject val expectedSettings = expected.getValue("settings").jsonObject val settings = SettingsData( @@ -44,6 +45,9 @@ class WatchBackupContractTest { isQuickPayEnabled = true, quickPayAmount = 10, quickPayDailyLimitMultiplier = 3, + isWatchQuickPayEnabled = true, + watchQuickPayAmount = 1, + watchQuickPayDailyLimitMultiplier = 5, ) val written = written(settings) @@ -54,7 +58,7 @@ class WatchBackupContractTest { } @Test - fun `default settings are written too, so the watch always finds all six`() { + fun `default settings are written too, so the watch always finds all nine`() { 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 65a92e6359..ec28f72ce6 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -222,6 +222,88 @@ 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 9e325c03dd..c98e8d8d99 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt @@ -6,9 +6,12 @@ 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 @@ -36,6 +39,8 @@ 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 @@ -73,6 +78,7 @@ 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) @@ -105,6 +111,10 @@ 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 @@ -154,6 +164,11 @@ 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 }, @@ -214,10 +229,10 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { } /** Runs a pairing from the repository against a watch, confirming on both sides. */ - private suspend fun TestScope.pair(isAuthenticated: Boolean = true): WatchPairingStatus { + private suspend fun TestScope.pair(isAuthenticated: Boolean = true, nodeId: String? = null): WatchPairingStatus { val session = watchSession() val watch = async { runCatching { session.run() } } - sut.startPairing() + sut.startPairing(nodeId) val confirming = async { session.confirmShown() sut.confirmPairing(awaitCode(), isAuthenticated) @@ -271,6 +286,40 @@ 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() @@ -588,6 +637,22 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertTrue(shown.none { it is WatchPairingStatus.Failed }) } + @Test + fun `a pairing queued while the cancelled one is still ending keeps the watch it was started for`() = test { + setUp() + val first = watchSession() + val firstWatch = async { runCatching { first.run() } } + sut.startPairing() + awaitCode() + + sut.cancelPairing() + sut.startPairing("another-watch") + assertIs(firstWatch.await().exceptionOrNull()) + runCurrent() + + assertIs(failure(sut.pairing.value)) + } + // endregion @Test @@ -766,7 +831,12 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertNull(store.watchQuickPay()) assertTrue(store.watchSends().isEmpty()) assertFalse(store.hasWatchInvoice(HASH, nowSecs)) - assertEquals(WatchLinkData(installId = linkData.data.first().installId), linkData.data.first()) + // Only the install id and the note that the watch was paired, which keeps the pair prompt away, are left. + val expected = WatchLinkData( + installId = linkData.data.first().installId, + pairPromptNodeIds = listOf(network.watch.nodeId), + ) + assertEquals(expected, linkData.data.first()) } @Test @@ -795,4 +865,239 @@ class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertEquals(Handshake.ID_BYTES, first.size) 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 + fun `a connected watch without bitkit is found, and the play listing opens on it`() = test { + setUp() + network.hasWatchApp = false + + val watch = assertNotNull(sut.watchWithoutApp()) + sut.installOnWatch(watch.id).getOrThrow() + + assertEquals("market://details?id=$APP_ID", network.opened.last()) + } + + @Test + fun `a watch with bitkit, or none, is no watch to install on`() = test { + setUp() + assertNull(sut.watchWithoutApp()) + + network.isConnected = false + assertNull(sut.watchWithoutApp()) + assertTrue(sut.installOnWatch("watch-node").isFailure) + } + + // endregion + + // region pair prompt + + @Test + fun `a connected watch with bitkit nearby is offered to pair until it was offered once`() = test { + setUp() + + val watch = assertNotNull(sut.watchToOfferPairing()) + assertEquals(network.watch.nodeId, watch.id) + + sut.notePairPrompt(watch.id) + assertNull(sut.watchToOfferPairing()) + } + + @Test + fun `a watch without bitkit, one reached through the cloud, or none is not offered to pair`() = test { + setUp() + + network.hasWatchApp = false + assertNull(sut.watchToOfferPairing()) + + network.hasWatchApp = true + network.isWatchNearby = false + assertNull(sut.watchToOfferPairing()) + + network.isConnected = false + assertNull(sut.watchToOfferPairing()) + } + + @Test + fun `no watch is offered to pair while one is paired, nor once it was unpaired`() = test { + setUp() + pair() + + assertNull(sut.watchToOfferPairing()) + + sut.forget().getOrThrow() + runCurrent() + assertNull(store.load()) + assertEquals(listOf(network.watch.nodeId), store.pairPromptNodeIds()) + assertNull(sut.watchToOfferPairing()) + } + + @Test + fun `a pairing for the watch the prompt offered pairs that watch, and no other`() = test { + setUp() + + sut.startPairing("another-watch") + runCurrent() + assertIs(failure(sut.pairing.value)) + sut.cancelPairing() + + assertEquals(WatchPairingStatus.Paired, pair(nodeId = network.watch.nodeId)) + } + + @Test + fun `a pairing that fails leaves the watch to be offered again`() = test { + hasWatchWallet = false + setUp() + settings.update { it.copy(isPinEnabled = false) } + + assertIs(failure(pair(nodeId = network.watch.nodeId))) + + assertEquals(network.watch.nodeId, sut.watchToOfferPairing()?.id) + } + + @Test + fun `a wiped phone offers the watches again`() = test { + setUp() + sut.notePairPrompt(network.watch.nodeId) + + sut.clearPairPrompts().getOrThrow() + + assertEquals(network.watch.nodeId, sut.watchToOfferPairing()?.id) + } + + @Test + fun `only the latest watches offered are remembered`() = test { + setUp() + + repeat(WatchLinkStore.PAIR_PROMPTS_KEPT) { sut.notePairPrompt("other-$it") } + sut.notePairPrompt("other-0") + sut.notePairPrompt(network.watch.nodeId) + + val kept = store.pairPromptNodeIds() + assertEquals(WatchLinkStore.PAIR_PROMPTS_KEPT, kept.size) + assertEquals(network.watch.nodeId, kept.last()) + assertTrue("other-0" in kept) + assertFalse("other-1" in kept) + } + + // endregion } 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 new file mode 100644 index 0000000000..de524c4e71 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/PayOnWatchInputTest.kt @@ -0,0 +1,117 @@ +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 new file mode 100644 index 0000000000..231cfab571 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/PayOnWatchViewModelTest.kt @@ -0,0 +1,61 @@ +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/WatchInstallViewModelTest.kt b/app/src/test/java/to/bitkit/ui/sheets/watch/WatchInstallViewModelTest.kt new file mode 100644 index 0000000000..19389ab5f0 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/sheets/watch/WatchInstallViewModelTest.kt @@ -0,0 +1,114 @@ +package to.bitkit.ui.sheets.watch + +import android.content.Context +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.R +import to.bitkit.models.Toast +import to.bitkit.repositories.WatchLinkRepo +import to.bitkit.test.BaseUnitTest +import to.bitkit.ui.shared.toast.ToastEventBus +import to.bitkit.wearlink.LinkError +import to.bitkit.wearlink.LinkNode +import kotlin.test.assertEquals +import kotlin.test.assertNull + +@OptIn(ExperimentalCoroutinesApi::class) +class WatchInstallViewModelTest : BaseUnitTest() { + private companion object { + val WATCH = LinkNode("node", "Pixel Watch", isNearby = true, hasApp = false) + } + + private val context = mock() + private val repo = mock() + private var opened = 0 + + @Before + fun setUp() { + whenever(context.getString(R.string.common__error)).thenReturn("Error") + whenever(context.getString(R.string.settings__watch__error_unreachable)).thenReturn("Not reachable") + whenever(context.getString(R.string.settings__watch__install_opened)).thenReturn("Continue on your watch.") + whenever { repo.watchWithoutApp() }.thenReturn(WATCH) + whenever { repo.installOnWatch(any()) }.thenReturn(Result.success(Unit)) + } + + private fun TestScope.toasts(): MutableList { + val toasts = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + ToastEventBus.events.collect { toasts += it } + } + return toasts + } + + @Test + fun `the prompt names the watch and install opens the listing on it, says so and closes`() = test { + val toasts = toasts() + val sut = WatchInstallViewModel(context, repo) + assertEquals("Pixel Watch", sut.uiState.value.watchName) + + sut.onInstallClick { opened++ } + + verify(repo).installOnWatch("node") + assertEquals(1, opened) + assertEquals(listOf(Toast.ToastType.INFO to "Continue on your watch."), toasts.map { it.type to it.title }) + } + + @Test + fun `a tap before the watch was found waits for it and closes nothing meanwhile`() = test { + val found = CompletableDeferred() + whenever { repo.watchWithoutApp() }.doSuspendableAnswer { found.await() } + val sut = WatchInstallViewModel(context, repo) + assertNull(sut.uiState.value.watchName) + + sut.onInstallClick { opened++ } + sut.onInstallClick { opened++ } + assertEquals(0, opened) + verify(repo, never()).installOnWatch(any()) + + found.complete(WATCH) + + verify(repo, times(1)).installOnWatch("node") + assertEquals(1, opened) + } + + @Test + fun `a watch that is gone keeps the prompt and says it is not reachable`() = test { + whenever { repo.watchWithoutApp() }.thenReturn(null) + val toasts = toasts() + val sut = WatchInstallViewModel(context, repo) + + sut.onInstallClick { opened++ } + + assertEquals(0, opened) + verify(repo, never()).installOnWatch(any()) + assertEquals(listOf(Toast.ToastType.ERROR to "Not reachable"), toasts.map { it.type to it.description }) + } + + @Test + fun `a listing that cannot be opened keeps the prompt, and a second tap tries again`() = test { + whenever { repo.installOnWatch(any()) }.thenReturn(Result.failure(LinkError.Unreachable())) + val toasts = toasts() + val sut = WatchInstallViewModel(context, repo) + + sut.onInstallClick { opened++ } + assertEquals(0, opened) + assertEquals(listOf(Toast.ToastType.ERROR), toasts.map { it.type }) + + whenever { repo.installOnWatch(any()) }.thenReturn(Result.success(Unit)) + sut.onInstallClick { opened++ } + + assertEquals(1, opened) + } +} 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 new file mode 100644 index 0000000000..a36c279874 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/sheets/watch/WatchQuickPayViewModelTest.kt @@ -0,0 +1,115 @@ +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 514cfd5370..6b7305f17c 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 @@ -1,11 +1,18 @@ package to.bitkit.ui.sheets.watch +import android.content.Context import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher import org.junit.Before import org.junit.Test import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.atLeast import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq @@ -16,10 +23,12 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever 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.test.BaseUnitTest +import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.wearlink.AbortReason import to.bitkit.wearlink.AttestationFailure import to.bitkit.wearlink.AttestationVerdict @@ -36,7 +45,9 @@ import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue +@OptIn(ExperimentalCoroutinesApi::class) class WatchSheetViewModelTest : BaseUnitTest() { + private val context = mock() private val repo = mock() private val record = MutableStateFlow(null) private val pairing = MutableStateFlow(WatchPairingStatus.Idle) @@ -46,6 +57,17 @@ class WatchSheetViewModelTest : BaseUnitTest() { whenever(repo.record).thenReturn(record) whenever(repo.pairing).thenReturn(pairing) whenever { repo.watches() }.thenReturn(Result.success(emptyList())) + whenever(context.getString(R.string.common__error)).thenReturn("Error") + whenever(context.getString(R.string.settings__watch__error_unreachable)).thenReturn("Not reachable") + whenever(context.getString(R.string.settings__watch__install_opened)).thenReturn("Continue on your watch.") + } + + private fun TestScope.toasts(): MutableList { + val toasts = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + ToastEventBus.events.collect { toasts += it } + } + return toasts } private val transferCode = PairingState.Code( @@ -73,26 +95,27 @@ class WatchSheetViewModelTest : BaseUnitTest() { fun `a connected watch with bitkit nearby can be paired`() = test { val watch = LinkNode("n", "Pixel Watch", isNearby = true, hasApp = true) whenever { repo.watches() }.thenReturn(Result.success(listOf(watch))) - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) sut.refresh() - assertEquals(ConnectedWatch("Pixel Watch", hasApp = true, isNearby = true), sut.uiState.value.connected) + val expected = ConnectedWatch("Pixel Watch", hasApp = true, isNearby = true, id = "n") + assertEquals(expected, sut.uiState.value.connected) assertTrue(sut.uiState.value.connected?.canPair == true) assertFalse(sut.uiState.value.isLoading) } @Test fun `a watch without bitkit, or reached through the cloud, cannot be paired, and each says why`() = test { - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) whenever { repo.watches() }.thenReturn(Result.success(listOf(LinkNode("n", "Watch", true, hasApp = false)))) sut.refresh() - assertEquals(ConnectedWatch("Watch", hasApp = false, isNearby = true), sut.uiState.value.connected) + assertEquals(ConnectedWatch("Watch", hasApp = false, isNearby = true, id = "n"), sut.uiState.value.connected) assertFalse(sut.uiState.value.connected?.canPair == true) whenever { repo.watches() }.thenReturn(Result.success(listOf(LinkNode("n", "Watch", false, hasApp = true)))) sut.refresh() - assertEquals(ConnectedWatch("Watch", hasApp = true, isNearby = false), sut.uiState.value.connected) + assertEquals(ConnectedWatch("Watch", hasApp = true, isNearby = false, id = "n"), sut.uiState.value.connected) assertFalse(sut.uiState.value.connected?.canPair == true) } @@ -101,7 +124,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { val bare = LinkNode("a", "Bare", isNearby = true, hasApp = false) val away = LinkNode("b", "Away", isNearby = false, hasApp = true) val ready = LinkNode("c", "Ready", isNearby = true, hasApp = true) - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) whenever { repo.watches() }.thenReturn(Result.success(listOf(bare, away, ready))) sut.refresh() @@ -116,7 +139,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { fun `opening the sheet again looks from scratch instead of showing the last watch found`() = test { val watch = LinkNode("n", "Pixel Watch", isNearby = true, hasApp = true) whenever { repo.watches() }.thenReturn(Result.success(listOf(watch))) - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) sut.onSheetOpen() assertTrue(sut.uiState.value.connected?.canPair == true) sut.onSheetClose() @@ -130,7 +153,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `a watch that connects while the sheet is open shows on the next look`() = test { - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) sut.onSheetOpen() assertNull(sut.uiState.value.connected) @@ -149,7 +172,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { gate.await() Result.success(listOf(watch)) } - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) sut.onSheetOpen() sut.refresh() @@ -165,7 +188,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `closing the end of a failed pairing looks for the watch again`() = test { - val sut = WatchSheetViewModel(repo).apply { onSheetOpen() } + val sut = WatchSheetViewModel(context, repo).apply { onSheetOpen() } sut.onPairClick() pairing.update { WatchPairingStatus.Failed(LinkError.Timeout()) } val watch = LinkNode("n", "Pixel Watch", isNearby = true, hasApp = true) @@ -180,7 +203,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `no watch, or no wearable service, shows as none connected`() = test { whenever { repo.watches() }.thenReturn(Result.failure(IllegalStateException("no api"))) - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) sut.refresh() @@ -190,7 +213,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `the paired watch shows its key level and whether the settings reached it`() = test { - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) record.update { record(settingsSent = 3) } @@ -205,7 +228,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { 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)) - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) record.update { record() } sut.onEraseClick() @@ -225,7 +248,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `a dialog stays open while the same watch reports, and closes when the watch is gone`() = test { - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) record.update { record() } sut.onEraseClick() @@ -238,7 +261,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `a dialog closes when another watch takes the place of the one it was about`() = test { - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) record.update { record() } sut.onUnpairClick() @@ -250,7 +273,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `a removal that waits shows as pending and can be dropped`() = test { whenever { repo.forget() }.thenReturn(Result.success(Unit)) - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) record.update { record(removal = Removal.Erase) } assertTrue(sut.uiState.value.paired?.isRemoving == true) @@ -275,7 +298,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `a pairing starts on the tap and is cancelled when the sheet closes`() = test { - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) assertNull(sut.uiState.value.pairing) verify(repo, never()).startPairing() @@ -290,9 +313,77 @@ class WatchSheetViewModelTest : BaseUnitTest() { assertNull(sut.uiState.value.pairing) } + @Test + fun `opened from the prompt to pair, the sheet starts a pairing with the watch it offered`() = test { + val sut = WatchSheetViewModel(context, repo) + + sut.onSheetOpen(pairNodeId = "node") + + verify(repo).startPairing("node") + assertEquals(WatchPairStep.Connecting, sut.uiState.value.pairing) + } + + @Test + fun `the prompt's request starts one pairing, not another when the sheet is composed again`() = test { + val sut = WatchSheetViewModel(context, repo) + sut.onSheetOpen(pairNodeId = "node") + sut.onSheetClose() + + sut.onSheetOpen(pairNodeId = "node") + + verify(repo, times(1)).startPairing("node") + assertNull(sut.uiState.value.pairing) + } + + @Test + fun `a sheet closed before the prompt's paired check ends starts no pairing`() = test { + val slowRecord = MutableSharedFlow() + whenever(repo.record).thenReturn(slowRecord) + val sut = WatchSheetViewModel(context, repo) + sut.onSheetOpen(pairNodeId = "node") + + sut.onSheetClose() + slowRecord.emit(null) + + verify(repo, never()).startPairing(anyOrNull()) + assertNull(sut.uiState.value.pairing) + } + + @Test + fun `opened from the prompt while a watch is paired, the sheet starts no pairing`() = test { + record.update { record() } + val sut = WatchSheetViewModel(context, repo) + + sut.onSheetOpen(pairNodeId = "node") + + verify(repo, never()).startPairing(anyOrNull()) + assertNull(sut.uiState.value.pairing) + } + + @Test + fun `opened from settings, the sheet starts no pairing`() = test { + val sut = WatchSheetViewModel(context, repo) + + sut.onSheetOpen() + + verify(repo, never()).startPairing() + assertNull(sut.uiState.value.pairing) + } + + @Test + fun `opened from the prompt while a transfer still shows, the sheet starts no other pairing`() = test { + val sut = WatchSheetViewModel(context, repo) + pairing.update { WatchPairingStatus.Running(PairingState.Transferring) } + + sut.onSheetOpen(pairNodeId = "node") + + verify(repo, never()).startPairing(anyOrNull()) + assertEquals(WatchPairStep.Sending, sut.uiState.value.pairing) + } + @Test fun `the end of an earlier pairing does not show until a pairing is started`() = test { - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) pairing.update { WatchPairingStatus.Failed(LinkError.Timeout()) } @@ -301,7 +392,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `the code step says when confirming sends the wallet and whether the watch is verified`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } val verified = AttestationVerdict.Verified(KeyLevel.TrustedEnvironment) val transfer = PairingState.Code("048213", PairingMode.Transfer, "Pixel Watch", verified) @@ -321,7 +412,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `confirming for a watch that is sent the wallet asks for the phone's check first`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } step(sut, WatchPairingStatus.Running(transferCode)) sut.onPairConfirm() @@ -332,7 +423,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `the wallet is confirmed as checked only once the check was passed`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } step(sut, WatchPairingStatus.Running(transferCode)) sut.onPairConfirm() @@ -345,7 +436,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `leaving the check goes back to the code with nothing confirmed`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } step(sut, WatchPairingStatus.Running(transferCode)) sut.onPairConfirm() @@ -359,7 +450,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `a watch that already holds the wallet is confirmed without a check, and never as checked`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } step(sut, WatchPairingStatus.Running(proofCode)) sut.onPairConfirm() @@ -371,7 +462,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `a passed check that nothing asked for confirms nothing`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } sut.onAuthSuccess() step(sut, WatchPairingStatus.Running(transferCode)) @@ -384,7 +475,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `the check goes away when the pairing ends under it, and passing it then confirms nothing`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } step(sut, WatchPairingStatus.Running(transferCode)) sut.onPairConfirm() @@ -397,7 +488,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `confirming without a code on screen does nothing`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } sut.onPairConfirm() @@ -407,7 +498,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `closing the sheet while the wallet is on its way lets the transfer finish`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } step(sut, WatchPairingStatus.Running(PairingState.Transferring)) sut.onSheetClose() @@ -421,7 +512,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `a transfer that failed while the sheet was closed says so when the sheet opens again`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } step(sut, WatchPairingStatus.Running(PairingState.Transferring)) sut.onSheetClose() pairing.update { WatchPairingStatus.Failed(LinkError.TransferFailed(StoreFailure.Failed)) } @@ -437,7 +528,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `a transfer that paired while the sheet was closed shows as the paired watch`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } step(sut, WatchPairingStatus.Running(PairingState.Transferring)) sut.onSheetClose() pairing.update { WatchPairingStatus.Paired } @@ -449,7 +540,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `reopening the sheet does not show a cancelled pairing that is still ending`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } step(sut, WatchPairingStatus.Running(transferCode)) sut.onSheetClose() @@ -462,7 +553,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `tapping pair cancels what still runs before it starts, so a pairing that is ending is replaced`() = test { - val sut = WatchSheetViewModel(repo) + val sut = WatchSheetViewModel(context, repo) sut.onPairClick() @@ -474,7 +565,7 @@ class WatchSheetViewModelTest : BaseUnitTest() { @Test fun `each failure gets its line, and a refused attestation says the wallet was not sent`() = test { - val sut = WatchSheetViewModel(repo).apply { onPairClick() } + val sut = WatchSheetViewModel(context, repo).apply { onPairClick() } assertEquals( R.string.settings__watch__error_unverified, @@ -515,4 +606,63 @@ 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 { + val sut = WatchSheetViewModel(context, repo) + + 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.onQuickPayClick() + sut.onPairClick() + assertFalse(sut.uiState.value.isQuickPayShown) + } + + // 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) + whenever { repo.watches() }.thenReturn(Result.success(listOf(watch))) + whenever { repo.installOnWatch(any()) }.thenReturn(Result.success(Unit)) + val toasts = toasts() + val sut = WatchSheetViewModel(context, repo) + sut.refresh() + + sut.onInstallClick() + + verify(repo).installOnWatch("node") + assertEquals(listOf(Toast.ToastType.INFO to "Continue on your watch."), toasts.map { it.type to it.title }) + } + + @Test + fun `an install that cannot open the listing says the watch is not reachable`() = test { + val watch = LinkNode("node", "Pixel Watch", isNearby = true, hasApp = false) + whenever { repo.watches() }.thenReturn(Result.success(listOf(watch))) + whenever { repo.installOnWatch(any()) }.thenReturn(Result.failure(LinkError.Unreachable())) + val toasts = toasts() + val sut = WatchSheetViewModel(context, repo) + sut.refresh() + + sut.onInstallClick() + + assertEquals( + listOf(Toast.ToastType.ERROR to "Not reachable"), + toasts.map { it.type to it.description }, + ) + } } diff --git a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt index 5490c07ccb..9ebbc41c40 100644 --- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt @@ -187,6 +187,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { inOrder.verify(cacheStore).reset() inOrder.verify(watchOnlyAccountRepo).clear() inOrder.verify(widgetsStore).reset() + inOrder.verify(watchLinkRepo).clearPairPrompts() inOrder.verify(blocktankRepo).resetState() inOrder.verify(activityRepo).resetState() inOrder.verify(hwWalletRepo).resetState() diff --git a/app/src/test/java/to/bitkit/utils/timedsheets/TimedSheetManagerTest.kt b/app/src/test/java/to/bitkit/utils/timedsheets/TimedSheetManagerTest.kt index 7b3aec09fc..d9110c8f03 100644 --- a/app/src/test/java/to/bitkit/utils/timedsheets/TimedSheetManagerTest.kt +++ b/app/src/test/java/to/bitkit/utils/timedsheets/TimedSheetManagerTest.kt @@ -159,6 +159,33 @@ class TimedSheetManagerTest : BaseUnitTest() { assertEquals(TimedSheetType.USDT, sut.currentSheet.value) } + @Test + fun `a recheck on Home shows a sheet that became eligible, and none after leaving Home`() = test { + val sheet = mock { + on { type } doReturn TimedSheetType.WATCH_PAIR + on { priority } doReturn 1 + } + whenever(sheet.shouldShow()).thenReturn(false) + sut.registerSheet(sheet) + enterHome() + testScope.advanceTimeBy(2100) + assertNull(sut.currentSheet.value) + + whenever(sheet.shouldShow()).thenReturn(true) + sut.onHomeScreenExited() + sut.reevaluate() + testScope.advanceTimeBy(2100) + assertNull(sut.currentSheet.value) + + enterHome() + sut.cancelPendingCheck() + sut.reevaluate() + testScope.advanceTimeBy(2100) + + assertEquals(TimedSheetType.WATCH_PAIR, sut.currentSheet.value) + verify(sheet).onShown() + } + @Test fun `does not show sheets when none eligible`() = test { val sheet = mock { diff --git a/app/src/test/java/to/bitkit/utils/timedsheets/sheets/WatchInstallTimedSheetTest.kt b/app/src/test/java/to/bitkit/utils/timedsheets/sheets/WatchInstallTimedSheetTest.kt new file mode 100644 index 0000000000..cda2eaaced --- /dev/null +++ b/app/src/test/java/to/bitkit/utils/timedsheets/sheets/WatchInstallTimedSheetTest.kt @@ -0,0 +1,78 @@ +package to.bitkit.utils.timedsheets.sheets + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.data.SettingsData +import to.bitkit.data.SettingsStore +import to.bitkit.repositories.WalletRepo +import to.bitkit.repositories.WatchLinkRepo +import to.bitkit.test.BaseUnitTest +import to.bitkit.ui.components.TimedSheetType +import to.bitkit.wearlink.LinkNode +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class WatchInstallTimedSheetTest : BaseUnitTest() { + private val settingsStore = mock() + private val walletRepo = mock() + private val watchLinkRepo = mock() + private val settingsFlow = MutableStateFlow(SettingsData()) + private val watch = LinkNode("node", "Pixel Watch", isNearby = true, hasApp = false) + private lateinit var sut: WatchInstallTimedSheet + + @Before + fun setUp() = runBlocking { + whenever(settingsStore.data).thenReturn(settingsFlow) + whenever(settingsStore.update(any())).then { + val transform = it.getArgument<(SettingsData) -> SettingsData>(0) + settingsFlow.value = transform(settingsFlow.value) + flowOf(settingsFlow.value) + } + whenever(walletRepo.walletExists()).thenReturn(true) + whenever(watchLinkRepo.watchWithoutApp()).thenReturn(watch) + sut = WatchInstallTimedSheet(settingsStore, walletRepo) { watchLinkRepo } + } + + @Test + fun `type is the watch install prompt, last of all`() { + assertEquals(TimedSheetType.WATCH_INSTALL, sut.type) + assertTrue(TimedSheetType.entries.all { it == sut.type || it.priority > sut.priority }) + } + + @Test + fun `shows when a connected watch has no bitkit and the phone has a wallet`() = test { + assertTrue(sut.shouldShow()) + } + + @Test + fun `does not show without a watch that lacks bitkit`() = test { + whenever(watchLinkRepo.watchWithoutApp()).thenReturn(null) + + assertFalse(sut.shouldShow()) + } + + @Test + fun `does not show without a wallet, and then does not look for watches`() = test { + whenever(walletRepo.walletExists()).thenReturn(false) + + assertFalse(sut.shouldShow()) + verify(watchLinkRepo, never()).watchWithoutApp() + } + + @Test + fun `shows once`() = test { + sut.onDismissed() + + assertTrue(settingsFlow.value.watchInstallPromptSeen) + assertFalse(sut.shouldShow()) + } +} diff --git a/app/src/test/java/to/bitkit/utils/timedsheets/sheets/WatchPairTimedSheetTest.kt b/app/src/test/java/to/bitkit/utils/timedsheets/sheets/WatchPairTimedSheetTest.kt new file mode 100644 index 0000000000..2b51339e9c --- /dev/null +++ b/app/src/test/java/to/bitkit/utils/timedsheets/sheets/WatchPairTimedSheetTest.kt @@ -0,0 +1,97 @@ +package to.bitkit.utils.timedsheets.sheets + +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.runBlocking +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.repositories.WalletRepo +import to.bitkit.repositories.WatchLinkRepo +import to.bitkit.test.BaseUnitTest +import to.bitkit.ui.components.TimedSheetType +import to.bitkit.wearlink.LinkNode +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class WatchPairTimedSheetTest : BaseUnitTest() { + private val walletRepo = mock() + private val watchLinkRepo = mock() + private val watch = LinkNode("node", "Pixel Watch", isNearby = true, hasApp = true) + private lateinit var sut: WatchPairTimedSheet + + @Before + fun setUp() = runBlocking { + whenever(walletRepo.walletExists()).thenReturn(true) + whenever(watchLinkRepo.watchToOfferPairing()).thenReturn(watch) + sut = WatchPairTimedSheet(walletRepo) { watchLinkRepo } + } + + @Test + fun `type is the watch pair prompt, after the wallet's own prompts and before the install prompt`() { + assertEquals(TimedSheetType.WATCH_PAIR, sut.type) + assertTrue(sut.priority > TimedSheetType.WATCH_INSTALL.priority) + assertTrue(sut.priority <= TimedSheetType.HIGH_BALANCE.priority) + } + + @Test + fun `shows when a connected watch with bitkit can be offered and the phone has a wallet`() = test { + assertTrue(sut.shouldShow()) + } + + @Test + fun `does not show without a watch to offer`() = test { + whenever(watchLinkRepo.watchToOfferPairing()).thenReturn(null) + + assertFalse(sut.shouldShow()) + } + + @Test + fun `does not show without a wallet, and then does not look for watches`() = test { + whenever(walletRepo.walletExists()).thenReturn(false) + + assertFalse(sut.shouldShow()) + verify(watchLinkRepo, never()).watchToOfferPairing() + } + + @Test + fun `closing it notes the watch it was shown for`() = test { + assertTrue(sut.shouldShow()) + + sut.onDismissed() + + verify(watchLinkRepo).notePairPrompt("node") + } + + @Test + fun `pair hands over the watch it was shown for, and leaves noting it to the pairing`() = test { + assertTrue(sut.shouldShow()) + + assertEquals("node", sut.takeOfferedNodeId()) + sut.onDismissed() + + verify(watchLinkRepo, never()).notePairPrompt(any()) + } + + @Test + fun `follows the watches that connect, for the prompt to be checked again`() = test { + whenever(watchLinkRepo.watchChanges).thenReturn(flowOf(Unit)) + + assertEquals(listOf(Unit), sut.watchChanges().toList()) + } + + @Test + fun `closing it without a watch found notes nothing`() = test { + whenever(watchLinkRepo.watchToOfferPairing()).thenReturn(null) + sut.shouldShow() + + sut.onDismissed() + + verify(watchLinkRepo, never()).notePairPrompt(any()) + } +} diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index c79753445e..150c4d1696 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -289,6 +289,7 @@ import to.bitkit.utils.ServiceError import to.bitkit.utils.timedsheets.TimedSheetManager import to.bitkit.utils.timedsheets.sheets.BackupTimedSheet import to.bitkit.utils.timedsheets.sheets.UsdtTimedSheet +import to.bitkit.utils.timedsheets.sheets.WatchPairTimedSheet import java.math.BigDecimal import java.net.URLEncoder import java.nio.charset.StandardCharsets @@ -422,6 +423,13 @@ class AppViewModelSendFlowTest : BaseUnitTest() { on { visible }.thenReturn(flowOf(true)) } private val timedSheetManager = mock() + private val watchChanges = MutableSharedFlow(extraBufferCapacity = 1) + private val watchPairSheet = mock { + on { type } doReturn TimedSheetType.WATCH_PAIR + on { priority } doReturn TimedSheetType.WATCH_PAIR.priority + on { watchChanges() } doReturn watchChanges + onBlocking { shouldShow() } doReturn false + } private fun presentTimedSheet(type: TimedSheetType): Boolean { val method = AppViewModel::class.java.getDeclaredMethod("tryShowTimedSheet", TimedSheetType::class.java) method.isAccessible = true @@ -1086,6 +1094,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { usdtPreferences = usdtPreferences, highBalanceSheet = mock { on { type } doReturn TimedSheetType.HIGH_BALANCE }, + watchPairSheet = watchPairSheet, + watchInstallSheet = mock { on { type } doReturn TimedSheetType.WATCH_INSTALL }, moveToSparkSheet = mock { on { type } doReturn TimedSheetType.MOVE_TO_SPARK onBlocking { shouldShow() } doReturn false @@ -13719,6 +13729,25 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(backupSheet).onShown() } + @Test + fun `a watch that connects checks the timed sheets again, for the pair prompt to show on Home`() = test { + clearInvocations(timedSheetManager) + + watchChanges.emit(Unit) + runCurrent() + + verify(timedSheetManager).reevaluate() + } + + @Test + fun `pair on the prompt opens the watch sheet on the watch it offered`() = test { + whenever(watchPairSheet.takeOfferedNodeId()).thenReturn("node") + + sut.pairPromptedWatch() + + assertEquals(Sheet.Watch(pairNodeId = "node"), sut.currentSheet.value) + } + @Test fun `unseen USDT intro retries after a scan fails without opening a sheet`() = test { val sheet = useRealTimedSheets() diff --git a/docs/screens-map.md b/docs/screens-map.md index 30ea2388bc..e466aeeea0 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 and shows the paired one; see `docs/wear.md`, Pairing. No design exists yet. Covered by `journeys/settings/watch-no-watch-connected.xml` and `journeys/wear/pair-*.xml`. +`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`. ## Wear OS diff --git a/docs/timed-sheets.md b/docs/timed-sheets.md index 124f8d9c60..1e145cc82a 100644 --- a/docs/timed-sheets.md +++ b/docs/timed-sheets.md @@ -2,7 +2,7 @@ Timed sheets are opportunistic prompts shown from the wallet surface when a feature-specific condition is met. They are separate from the full-screen settings intro routes, even when both presentations reuse the same visual content. -The manager checks sheets two seconds after the home screen resumes and cancels a pending check when the home screen pauses. It shows at most one eligible sheet per check, using this priority order: +The manager checks sheets two seconds after the home screen resumes and cancels a pending check when the home screen pauses. A Wear OS watch with Bitkit that connects while Home shows starts the same check (Watch Pair below). It shows at most one eligible sheet per check, using this priority order: 1. App update 2. USDT @@ -10,6 +10,8 @@ The manager checks sheets two seconds after the home screen resumes and cancels 4. Notifications 5. QuickPay 6. High balance +7. Watch pair +8. Watch install A busy sheet host leaves prompts queued for a later Home visit. While an unseen, undecided USDT intro has not yet been presented in this app session, becoming idle on Home also retries the queue after the same two-second delay. Once the intro is presented, closing sheets does not advance other timed prompts. Eligibility checks that finish after leaving Home or opening another flow cannot open a sheet. @@ -74,3 +76,23 @@ The High Balance sheet is eligible when the wallet balance converts to more than - Any dismissal increments `balanceWarningTimes` and records `balanceWarningIgnoredMillis`. The sheet can appear at most three times while the balance remains above the threshold, with at least one day between appearances. A balance at or below the threshold resets `balanceWarningTimes` to zero. + +## Watch Pair + +The Watch Pair sheet (`WatchPairSheet`, tag `PairedWatchPrompt`) is eligible while the watch link is enabled (`Env.isWatchLinkEnabled`, off on mainnet), the phone holds a wallet, no watch is paired or being removed, and a Wear OS watch connected to the phone has Bitkit, is reached directly and was neither offered before nor paired with this phone (`WatchLinkRepo.watchToOfferPairing`). + +- `Pair` (`PairedWatchPromptPair`) opens the Watch sheet (`Sheet.Watch(pairNodeId)`) on a pairing with the watch the sheet offered, as Pair Watch there does: the watch's Pair screen opens, both devices show the code, and a watch without a wallet is sent one only after both confirmations and the phone's PIN. +- `Later` (`PairedWatchPromptLater`) dismisses the sheet. +- `Later` or any other dismissal notes the watch's node id in the phone's link store, so the sheet shows once per watch. `Pair` does not: only a successful pairing notes the watch, so a pairing that fails (no PIN, a timeout, a cancel) lets the sheet return on the next app start, and unpairing a paired watch does not bring it back. Wiping the phone's wallet forgets the noted watches. Another watch can still get its own sheet. The Watch sheet in Settings › General › Watch always offers Pair Watch. + +See `docs/wear.md`, Pairing › Pair prompt. + +## Watch Install + +The Watch Install sheet (`WatchInstallSheet`) is eligible while the watch link is enabled (`Env.isWatchLinkEnabled`, off on mainnet), the phone holds a wallet, `watchInstallPromptSeen` is false, and a Wear OS watch connected to the phone has no Bitkit (`WatchLinkRepo.watchWithoutApp`). + +- `Install` opens Bitkit's Play listing on that watch (`market://details?id=` through `RemoteActivityHelper`), shows the toast "Continue on your watch." and dismisses the sheet. When the watch is gone or the listing cannot be opened, it shows the "not reachable" error toast and the sheet stays, not marked seen. +- `Later` dismisses the sheet. +- Any dismissal records `watchInstallPromptSeen = true`, so the sheet shows once. The Watch sheet in Settings › General › Watch still offers Install on Watch for such a watch. + +See `docs/wear.md`, Pairing › Install prompt. diff --git a/docs/wear.md b/docs/wear.md index 88febebf20..a5d5f2bdd2 100644 --- a/docs/wear.md +++ b/docs/wear.md @@ -461,10 +461,12 @@ in any other state. ### QuickPay -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 +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 usual result screens, only when every one of these holds: - The wallet is connected and synced (`WalletStatus.Ready`), and no wipe runs. @@ -475,16 +477,20 @@ 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 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 +- 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 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, 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 +- 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 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, @@ -514,10 +520,13 @@ 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.** 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. +- **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. 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. @@ -536,21 +545,26 @@ 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, 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 +- **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 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 phone's QuickPay amount per payment and by the daily limit, and by the two counts above. Whether + 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 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; 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. + 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). ## NFC @@ -740,14 +754,25 @@ 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.** Six of those keys, and nothing else: +- **What the watch adopts.** Nine 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 phone stores no other QuickPay value and no watch-specific limit; none is invented here. + - 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. - **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 @@ -755,7 +780,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 six settings in the phone's encoding, and each network's store id prefix and two servers. + the backup's key, the nine 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 @@ -792,7 +817,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 six values. The phone's `primaryDisplay` is adopted when it +- **Outcomes.** A backup that was read replaces the nine 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 @@ -821,7 +846,6 @@ from VSS and never writes there. - **One sink.** The import does not write the settings itself: it hands what it read to `PhoneStateSink`, as the paired phone's push does. The sink decides which version holds, and whatever reads the settings afterwards never learns where they came from. -- **Later.** The watch-specific limits come with a later part of the pairing work. ### Self-send guard @@ -858,8 +882,9 @@ sending it the wallet, it gives the phone a live, authenticated way to push its the phone unpair the watch or erase 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, a later PR, adds watch-specific limits, a payment -handed from the phone to the watch and the prompt to install the watch app. +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). - **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 @@ -911,8 +936,11 @@ handed from the phone to the watch and the prompt to install the watch app. capability array, so `res/raw/keep.xml` keeps it; without that rule the capability would vanish from release builds only. The phone's release build does not shrink resources. - **Opening the watch app.** The phone opens the watch's Pair screen with a `bitkitwear://pair` link through - `RemoteActivityHelper`, since a listener service may not start an activity on Wear OS. The wearer can also open - it from the watch's settings or onboarding. The link only shows a screen, so any app may send it. + `RemoteActivityHelper`, since a listener service may not start an activity on Wear OS. This is the only way to the + watch's Pair screen: the watch has no button that starts a pairing, the phone always starts it. The link opens the + screen above Home, or above onboarding for a watch without a wallet, which is how that watch receives one; anywhere + else, as during the restore or on Wallet removed, it is dropped. The link only shows a screen, so any app may send + it. - **Debug socket.** Two emulators cannot pair over the Data Layer without a Google account. A debug build therefore swaps the carrier for one TCP connection on the loopback interface when the file `wearlink-socket` exists in its files directory: the watch listens, the phone connects, and `adb forward` with `adb reverse` @@ -1068,13 +1096,13 @@ associated data. One key per direction, so a message cannot be sent back to its whatever the carrier does. The reader records a counter after it applied the body, so a document whose effect a crash cut short is applied again when it is delivered again. - **Documents**, each a full snapshot with one writer: `p2w/control` (paired, revoked, erase), `p2w/settings` - (the six settings and the phone's time of the change) and `w2p/status` (the settings counter the watch applied, + (the nine settings the watch adopts and the phone's time of the change) and `w2p/status` (the settings counter the watch applied, whether it still holds the pairing). Each is stored for delivery after a reconnect and also sent at once. - **A new pairing** has new keys and a new id, so nothing of an earlier one opens. ### Settings push -- The phone publishes the six settings the watch adopts when the pairing is made, at each app start and whenever +- The phone publishes the nine settings the watch adopts when the pairing is made, at each app start and whenever one of them changes, with the phone's time of the change, made strictly later than the last one sent. - The phone finishes a pairing a moment before the watch has noted it, so the watch may drop that first push. Its first status then says it has applied none, and the phone publishes again; this happens at most once per pairing. @@ -1142,7 +1170,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. A per-device cap for the watch comes with part 3. + it. That only refuses more, and ends with the day. The watch also holds its own count to its own daily limit (Watch limits). - **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 @@ -1209,6 +1237,110 @@ 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 +no Bitkit and the phone has a wallet: "Bitkit on Your Watch" (`WatchInstallSheet`), Install (`WatchInstallConfirm`) +and Later (`WatchInstallLater`). Install opens `market://details?id=` on that watch +(`RemoteActivityHelper`), the Play listing of the watch build, which shares the phone's application id. It waits for +the look for the watch, and closes the prompt only once the listing opened, with the toast "Continue on your +watch."; a watch that is gone or a listing that cannot be opened shows the error toast "Your watch is not reachable. +Keep it nearby with Bluetooth on." and leaves the prompt up. Closing it, by Install that opened the listing, by Later +or by any other dismissal, marks it seen (`watchInstallPromptSeen`). The Watch sheet offers the same install for a +watch without Bitkit (`PairedWatchInstall`), with the same two toasts. Behind `Env.isWatchLinkEnabled`, so not on mainnet, and the listing has no +watch build until #2152 is resolved. + +### Pair prompt + +A timed sheet (`docs/timed-sheets.md`), `WatchPairTimedSheet`, shown from Home when a connected watch has Bitkit and +is reached directly, no watch is paired or being removed, and the phone has a wallet: "Pair Your Watch" +(`PairedWatchPrompt`), Pair (`PairedWatchPromptPair`) and Later (`PairedWatchPromptLater`). It is checked 2 s after +Home shows, and again 2 s after a watch with Bitkit connects or gets Bitkit while Home shows (the capability +listener in `WatchDataLayerTransport`, or the debug socket connecting), so a watch connected meanwhile gets its +prompt without a new Home visit. Pair opens the Watch sheet on a pairing with the watch the prompt offered +(`Sheet.Watch(pairNodeId)`), as its own Pair Watch does: the phone opens the watch's Pair screen, both show the +code, and a watch without a wallet is sent one only after both confirmations and the phone's PIN, as in The +ceremony. Nothing about the pairing is decided by the prompt, so it is never silent. Behind `Env.isWatchLinkEnabled`, +so not on mainnet. + +When it shows again: + +- **Once per watch.** Later or any other dismissal notes that watch's node id in the phone's link store + (`WatchLinkStore`, in no backup); a watch noted there is never offered again. The last 10 watches are + remembered. Pair does not note it: only a pairing that succeeds does, so one that fails, as on a phone without a + PIN ("Set a PIN in Bitkit first, then pair your watch."), a timeout or a cancel, lets the prompt return on the + next app start. +- **Once per request.** The sheet takes the prompt's request once: composed again, as after the activity was + recreated, it starts no other pairing, and none while a watch is paired. +- **Not after a pairing.** A watch paired with this phone, from the prompt or from Settings, is noted too, so + unpairing it does not bring the prompt back. Settings › General › Watch pairs it again. +- **Another watch** connected later gets its own prompt, once there is no paired watch. +- **After a wipe.** Wiping the phone's wallet (`WipeWalletUseCase`) forgets the watches noted, so the next wallet is + offered to pair them again from the next app start (the queue dropped the sheet once it was presented). A watch + that kept the earlier wallet then ends on "The watch holds a different wallet." +- **Once per app start at most**, as every timed sheet: the queue drops a sheet once it was presented. + ### Unpair, erase and wipe - **Unpair from the phone.** The phone publishes "revoked" and marks its record. The watch forgets the phone, @@ -1237,7 +1369,8 @@ for delivery after a reconnect. Each device publishes its three when the pairing Phone: Settings › General has one row, Watch (`PairedWatchSettings`), after Hardware Wallets, with the paired watch's name or "Not paired". It opens one bottom sheet (`WatchSheet`; its container's tag `PairedWatchSheet` has no text, so `android layout` does not list it), in the app's sheet host -like Send and Receive, that holds the whole flow: +like Send and Receive, that holds the whole flow. The Pair prompt's Pair opens the same sheet already on a pairing +with the watch it offered, as if Pair Watch had been tapped: - **Watch found.** One line about the connected watch (`PairedWatchStatus`): ready to pair, Bitkit missing on it, has Bitkit but is not reached directly ("Keep it nearby with Bluetooth on"), or none connected; and Pair Watch @@ -1254,6 +1387,8 @@ like Send and Receive, that holds the whole flow: - **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. - **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 @@ -1269,7 +1404,10 @@ The phone's tags start with `PairedWatch` because the watch app's own start with Watch: -- **Pair** (`PairScreen`, `WatchPairScreen`): "Start on phone" (`WatchPairWaiting`), then the phone's name +- **Onboarding** (`OnboardingScreen`): the Bitkit mark (`WatchOnboardingLogo`), the phone icon with "Start on + phone" (`WatchOnboardingStartOnPhone`), which is text and no button, and Restore (`WatchOnboardingRestore`). +- **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 the ring, then a check with "Paired" (`WatchPairDone`) or one line (`WatchPairError`). There is no cancel button: swiping the screen away cancels, at every step. The code and the button are hidden in ambient mode, and @@ -1279,9 +1417,11 @@ Watch: anew, so the phone's retry is answered. A request that comes while a pairing runs past the phone's hello never interrupts it; it is kept, and when that pairing fails or the phone aborts it the screen waits anew. It is dropped when the wearer swipes the pairing away or it pairs. -- **Onboarding** has a second way in, "From phone" (`WatchOnboardingFromPhone`), which opens Pair. -- **Settings** has a row: "Pair phone" (`WatchSettingsPair`), or "Phone" with the phone's name - (`WatchSettingsPaired`, `WatchSettingsPairedName`), whose tap asks "Unpair phone?" above one `EdgeButton` that +- **Pair is opened by the phone only.** Neither onboarding nor Settings has a button that starts a pairing: the Pair + screen comes up when the phone's pair request arrives (The carrier, Opening the watch app), above onboarding or + Home. +- **Settings** has a row only while paired: "Phone" with the phone's name (`WatchSettingsPaired`, + `WatchSettingsPairedName`), whose tap asks "Unpair phone?" above one `EdgeButton` that says "Unpair" (`WatchPhoneUnpairConfirm`); swiping the dialog away cancels. An unpair that fails shows one line under the row (`WatchPhoneUnpairFailed`) while the phone stays paired; the line goes when the pairing changes. @@ -1318,8 +1458,20 @@ 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. -- Not in this part: watch-specific limits, the payment handoff and the install prompt (part 3). Until part 3 the - watch's QuickPay follows the phone's, within the one daily limit the two share. +- 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 + with a timeout, and Pair Watch tries again. Manual test 2b checks the remote launch on a closed app. ## Seed storage @@ -1431,8 +1583,8 @@ still works if it ever happens. ## Restoring with a recovery phrase Onboarding's Restore leads to the length choice (12 or 24 words), then one screen per word, the checksum check, the -optional passphrase and Home. Its other way in, From phone, receives the wallet from the paired phone instead (see -Pairing). +optional passphrase and Home. A watch on onboarding can also receive the wallet from the phone instead: the phone +starts the pairing and opens the watch's Pair screen above onboarding (see Pairing). - The length is one control: tapping 12 or 24 starts typing. - Each word screen shows the progress, such as 3/12, and a text field. After two letters up to six wordlist words diff --git a/journeys/README.md b/journeys/README.md index 2d90f003b9..f06c6d7799 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 | 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, 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, 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) | | 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,7 +221,8 @@ 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-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 | +| `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 | ### Running one on iOS diff --git a/journeys/settings/watch-quickpay-pin.xml b/journeys/settings/watch-quickpay-pin.xml new file mode 100644 index 0000000000..cbb9058e20 --- /dev/null +++ b/journeys/settings/watch-quickpay-pin.xml @@ -0,0 +1,29 @@ + + + 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 f9310cc4a6..b30d4c8726 100644 --- a/journeys/wear/README.md +++ b/journeys/wear/README.md @@ -141,6 +141,8 @@ 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 @@ -231,7 +233,8 @@ adb shell pm clear to.bitkit.dev adb shell am start -n to.bitkit.dev/to.bitkit.wear.ui.MainActivity ``` -`android layout` lists `WatchOnboardingLogo` and `WatchOnboardingRestore`. +`android layout` lists `WatchOnboardingLogo`, `WatchOnboardingStartOnPhone` ("Start on phone") and +`WatchOnboardingRestore`. ### Restored wallet @@ -355,6 +358,14 @@ 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 @@ -426,6 +437,23 @@ Notes: - The phone needs a PIN to send its wallet to a watch (Settings › Security › PIN Code; the journeys use 1111, with biometrics off). Without one that pairing ends on "Set a PIN in Bitkit first, then pair your watch." (`pair-receive-wallet-no-pin.xml`). Pairing with a watch that already holds the wallet needs none. +- **The phone starts every pairing.** The watch has no button that opens its Pair screen: neither onboarding nor + its Settings page offers one. On the socket the phone's Pair Watch (`PairedWatchPair`), or the Pair prompt's Pair + (`PairedWatchPromptPair`), sends the `bitkitwear://pair` link as one frame, and the watch's debug build starts its + activity with it, standing in for the remote launch. So a journey taps Pair on the phone and waits for + `WatchPairScreen` on the watch, which must have its app open (step 4) so its socket listens. The link opens the + Pair screen above Home or onboarding only, never during the restore. +- **The Pair prompt.** A phone with a wallet and no paired watch shows "Pair Your Watch" (`PairedWatchPrompt`) on + Home about 2 s after Home shows with the socket connected, or after the socket connects while Home shows; if it + does not show, leave Home and come back. It shows at most once per app start and once per watch: Later notes the + watch, and so does a pairing that succeeds, while a Pair that fails (no PIN, a timeout, a cancel) lets it return + on the next app start. The socket's watch has one node id, so on one phone install it shows once. The pair + journeys that start on Home wait 3 s and tap Later (`PairedWatchPromptLater`) when it shows; run `pair-prompt.xml` + first, as Later rules it out. To see it again (`pair-prompt.xml`, + `pair-prompt-later.xml`), with no watch paired, delete the phone's link store and restart the app: + `adb -s $PHONE shell run-as to.bitkit.dev rm -f files/datastore/watch_link.json`, then + `adb -s $PHONE shell am force-stop to.bitkit.dev`. Never delete it while paired: it holds the pairing's record. + [Fresh app](#fresh-app) on the phone deletes it too. - The watch's code screen has one button, Match (`WatchPairConfirm`). It has no cancel button: swipe the screen away (Watch gestures, swipe-to-dismiss). - An emulator's Keystore cannot be attested against Google's roots, so the phone's Watch sheet shows @@ -445,8 +473,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 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 +- **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 [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 @@ -456,7 +484,7 @@ keep: ends in an error no step expects, note it against #2152 with the journey and step, and start over from a new wallet: `../bitkit-docker/spark down`, then `up`, and [Fresh app](#fresh-app) on both devices. -The pairing these two journeys need is one wallet on both devices, paired: `pair-receive-wallet.xml` alone leaves +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`. ### Restart @@ -846,7 +874,7 @@ same wallet the phone's invoice would be the watch's own. Debug builds log the t These need capabilities the journey environment lacks: a watch paired with the phone over the Wear Data Layer, which needs the companion app and a Google account, and a watch with a hardware Keystore. Run them with a phone and a physical Wear OS watch that are paired in the system, both with builds of the same flavor signed with the -same key. Tests 1 to 8 and 10 use dev builds without the `wearlink-socket` file; tests 3a and 9 need release-signed +same key. Tests 1 to 8 and 10 to 14 use dev builds without the `wearlink-socket` file; tests 3a and 9 need release-signed builds (`assembleDevRelease` of both apps with a local keystore). 1. **Discovery.** With the watch connected and Bitkit installed on it, open Settings › General › Watch on the phone. @@ -864,8 +892,8 @@ builds (`assembleDevRelease` of both apps with a local keystore). your full wallet" and its key's verdict. - 2a. Note the verdict (StrongBox, secure hardware or not verified) per watch model. - 2b. With the watch app closed before tapping Pair: it opens on the Pair screen. -3. **Set a watch up from the phone.** Remove the wallet from the watch. Tap From phone on the watch, then Pair on - the phone. Set a PIN on the phone first. +3. **Set a watch up from the phone.** Remove the wallet from the watch, which then shows onboarding with no button + to pair. Tap Pair on the phone. Set a PIN on the phone first. - Expected: the phone warns that pairing sends the recovery phrase; Pair asks for the PIN; the watch opens Home with the phone's balance after its first sync. - 3a. Release-signed builds on a watch with a locked bootloader: the same, and the phone's Watch screen shows @@ -880,6 +908,8 @@ builds (`assembleDevRelease` of both apps with a local keystore). - 3e. Without a PIN on the phone: the phone says to set a PIN in Bitkit first, and nothing is sent. - 3f. Tap Pair on the phone and Cancel at once, three times in a row: the watch's Pair screen does not open by itself with a code nobody confirms, and a fourth try is not refused with "Too many attempts". + - 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. @@ -911,3 +941,43 @@ 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. +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 + listing on the watch and the phone toasts "Continue on your watch." (with the watch out of reach it toasts + that the watch is not reachable and the sheet stays); the sheet never shows again, also after Later. The Watch sheet then offers Install on + Watch (`PairedWatchInstall`), which opens the same listing. + - 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. +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 + pairing and the watch app comes to the front on its Pair screen by itself, also with the app closed; the codes + match, and a watch without a wallet is sent one only after Match, Pair and the PIN. + - 14a. Later, then restart the phone app: no prompt. Unpair a watch paired from the prompt, restart: no prompt. + - 14b. A watch without Bitkit, a watch reached only through the cloud, a paired watch, or a mainnet build: no + pair prompt. + - 14c. On a phone without a PIN, Pair ends on "Set a PIN in Bitkit first, then pair your watch."; set the PIN + and restart the phone app: the prompt shows again. With two watches with Bitkit, Pair pairs the one offered. + - 14d. With the phone on Home and no prompt shown since the app started, connect the watch (Bluetooth on, or + install Bitkit on it): the prompt shows within a few seconds, without leaving Home. After Later, wipe the + phone's wallet, create one and restart the phone app: the prompt shows again. + - Not run yet. + diff --git a/journeys/wear/pair-cancel-on-watch.xml b/journeys/wear/pair-cancel-on-watch.xml index 05e0e9e5a3..fcd928986f 100644 --- a/journeys/wear/pair-cancel-on-watch.xml +++ b/journeys/wear/pair-cancel-on-watch.xml @@ -5,15 +5,15 @@ socket. Precondition: journeys/wear/README.md › Phone and watch over the debug socket. The watch holds the phone's - wallet and is not paired, as for pair-same-wallet.xml. Watch: on the Settings page. Phone: on Home. + wallet and is not paired, as for pair-same-wallet.xml. Watch: on the Balance page. Phone: on Home. - On the watch, tap Pair phone (tag "WatchSettingsPair") + 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") On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), then "PairedWatchPair" - Wait up to 15 s until the watch lists "WatchPairCode" + Wait up to 15 s until the watch lists "WatchPairCode": the phone opened the Pair screen Verify the watch lists the Match button (tag "WatchPairConfirm") and no "WatchPairCancel" On the watch, swipe the screen away (README › Watch gestures, swipe-to-dismiss) - Verify the watch lists "WatchSettingsPair" within 5 s + Verify the watch lists "WatchHomePager" and no "WatchPairScreen" within 5 s Wait up to 5 s until the phone lists "PairedWatchPairError" reading "Pairing was cancelled on the watch." On the phone, tap OK (tag "PairedWatchPairClose") and verify "PairedWatchPair" is listed diff --git a/journeys/wear/pair-different-wallet.xml b/journeys/wear/pair-different-wallet.xml index bc50612aeb..98ca46e9d6 100644 --- a/journeys/wear/pair-different-wallet.xml +++ b/journeys/wear/pair-different-wallet.xml @@ -8,13 +8,14 @@ Home. + 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") On the watch, swipe left three times to the Settings page (README › Watch gestures) - Tap Pair phone (tag "WatchSettingsPair") and verify "WatchPairWaiting" is listed On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), then "PairedWatchPair" + Wait up to 10 s until the watch lists "WatchPairScreen": the phone opened the Pair screen Wait up to 15 s until the phone lists "PairedWatchPairError" Verify "PairedWatchPairError" reads "The watch holds a different wallet." - Verify the watch lists "WatchPairError" reading "Different wallet", or already "WatchSettingsPair" again + Verify the watch lists "WatchPairError" reading "Different wallet", or already "WatchHomePager" again On the phone, tap OK (tag "PairedWatchPairClose") and verify "PairedWatchPair" is listed, not "PairedWatchName" - Verify the watch lists "WatchSettingsPair" within 5 s: it is not paired + Verify the watch lists "WatchSettingsAbout" and no "WatchSettingsPaired" within 5 s: it is not paired diff --git a/journeys/wear/pair-prompt-later.xml b/journeys/wear/pair-prompt-later.xml new file mode 100644 index 0000000000..573d52514c --- /dev/null +++ b/journeys/wear/pair-prompt-later.xml @@ -0,0 +1,19 @@ + + + Later closes the phone's prompt to pair a watch, and the prompt does not come back for that watch, also after the + app restarts. Nothing opens on the watch. Settings › General › Watch still pairs it. Two emulators over the + debug socket. + + Precondition: journeys/wear/README.md › Phone and watch over the debug socket and its Pair prompt note: the + phone's link store has never offered the watch. Phone: a dev build with a wallet, not paired, the app not + started yet. Watch: holds a wallet or none, on the Balance page or onboarding, not paired. + + + Start the phone app (unlock it if it has a PIN) + Wait up to 15 s on Home until the phone lists "PairedWatchPrompt" + Tap Later (tag "PairedWatchPromptLater") and verify "PairedWatchPrompt" is no longer listed + Verify the watch does not list "WatchPairScreen" + Restart the phone app (`adb -s $PHONE shell am force-stop to.bitkit.dev`, then start it), unlock it if needed, and verify Home does not list "PairedWatchPrompt" within 10 s + Open Settings, tap Watch (tag "PairedWatchSettings") and verify "PairedWatchPair" is enabled, with "PairedWatchStatus" naming the watch as ready to pair + + diff --git a/journeys/wear/pair-prompt.xml b/journeys/wear/pair-prompt.xml new file mode 100644 index 0000000000..3f6aace794 --- /dev/null +++ b/journeys/wear/pair-prompt.xml @@ -0,0 +1,31 @@ + + + A phone with a wallet offers by itself to pair a connected watch that has Bitkit: a sheet on Home whose Pair + opens the Watch sheet on a pairing, and the phone opens the watch's Pair screen above onboarding. The watch has + no button of its own that starts a pairing. The code shows on both screens and the PIN is asked before the + wallet is sent, as for pair-receive-wallet.xml. Once closed, the prompt does not come back for that watch. Two + emulators over the debug socket. + + Precondition: journeys/wear/README.md › Phone and watch over the debug socket and its Pair prompt note: the + phone's link store has never offered the watch. Phone: a dev build with a wallet and the PIN 1111 set + (Settings › Security › PIN Code), biometrics off, not paired, the app not started yet. Watch: Fresh app, on + onboarding. PHONE and WATCH are the two serials. + + 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" + 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" + 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 + Verify the watch lists "WatchPairCode" with the same six digits, and the phone "PairedWatchSendsWallet" + On the watch, tap Match (tag "WatchPairConfirm") + On the phone, tap Pair (tag "PairedWatchCodeConfirm") and verify the PIN pad is listed (tag "N1") + Enter the PIN: tap "N1" four times + Wait up to 20 s until the phone lists "PairedWatchPairDone", and up to 15 s until the watch lists "WatchHomePager" + On the phone, tap OK (tag "PairedWatchPairClose"), close the sheet with the system Back, unpair the watch as in pair-unpair-from-phone.xml, and return to Home + Restart the phone app (`adb -s $PHONE shell am force-stop to.bitkit.dev`, then start it), unlock it, and verify Home does not list "PairedWatchPrompt" within 10 s: a watch once paired is not offered again + + diff --git a/journeys/wear/pair-receive-wallet-no-pin.xml b/journeys/wear/pair-receive-wallet-no-pin.xml index d5a1930d98..db657f8036 100644 --- a/journeys/wear/pair-receive-wallet-no-pin.xml +++ b/journeys/wear/pair-receive-wallet-no-pin.xml @@ -9,11 +9,11 @@ the watch's serial. - On the watch, tap From phone (tag "WatchOnboardingFromPhone") and verify "WatchPairWaiting" is listed + 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") On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), then "PairedWatchPair" Wait up to 15 s until the phone lists "PairedWatchPairError" reading "Set a PIN in Bitkit first, then pair your watch." Verify the phone never listed "PairedWatchCode" - Verify the watch lists "WatchPairError" reading "Couldn't pair", or already "WatchOnboardingFromPhone" again + Verify the watch lists "WatchPairError" reading "Couldn't pair", or "WatchOnboardingRestore" (the Pair screen may have closed already, or never opened, as the phone ends before the code) Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists no seed file On the phone, tap OK (tag "PairedWatchPairClose") and verify "PairedWatchPair" is listed, not "PairedWatchName" diff --git a/journeys/wear/pair-receive-wallet-pin.xml b/journeys/wear/pair-receive-wallet-pin.xml index 1f0f86785e..6a4cbcb116 100644 --- a/journeys/wear/pair-receive-wallet-pin.xml +++ b/journeys/wear/pair-receive-wallet-pin.xml @@ -13,7 +13,7 @@ (`PairedWatchPairError`) and is started again from a Fresh app on the watch. - On the watch, tap From phone (tag "WatchOnboardingFromPhone") + 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") On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), then "PairedWatchPair" Wait up to 15 s until the phone lists "PairedWatchCode", then tap Match on the watch (tag "WatchPairConfirm") On the phone, tap Pair (tag "PairedWatchCodeConfirm") and verify the PIN pad is listed (tag "N1") diff --git a/journeys/wear/pair-receive-wallet.xml b/journeys/wear/pair-receive-wallet.xml index 047efdf2c2..45cfe85a36 100644 --- a/journeys/wear/pair-receive-wallet.xml +++ b/journeys/wear/pair-receive-wallet.xml @@ -12,9 +12,11 @@ PHONE and WATCH are the two serials. - On the watch, tap From phone (tag "WatchOnboardingFromPhone") and verify "WatchPairWaiting" is listed + 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) 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 Wait up to 15 s until the phone lists "PairedWatchCode" and note its six digits Verify the watch lists "WatchPairCode" with the same six digits Verify the phone lists "PairedWatchSendsWallet" and "PairedWatchUnverified" diff --git a/journeys/wear/pair-retry-after-cancel.xml b/journeys/wear/pair-retry-after-cancel.xml index 17db155240..b228cceb3d 100644 --- a/journeys/wear/pair-retry-after-cancel.xml +++ b/journeys/wear/pair-retry-after-cancel.xml @@ -12,7 +12,7 @@ send the two taps in one command: `adb -s $PHONE shell "input tap <cancel> && input tap <pair>"`. - On the watch, tap Pair phone (tag "WatchSettingsPair") + 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") On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), note the center of "PairedWatchPair", then tap it Wait up to 15 s until the phone lists "PairedWatchCode" and the watch lists "WatchPairCode" On the phone, tap Cancel (tag "PairedWatchCodeCancel") and Pair Watch right after it, in one command as in the description diff --git a/journeys/wear/pair-same-wallet.xml b/journeys/wear/pair-same-wallet.xml index a356bcdfc4..d757b772ec 100644 --- a/journeys/wear/pair-same-wallet.xml +++ b/journeys/wear/pair-same-wallet.xml @@ -8,9 +8,11 @@ page. Phone: on Home. + 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") On the watch, swipe left three times to the Settings page (README › Watch gestures) - Tap Pair phone (tag "WatchSettingsPair") and verify "WatchPairWaiting" is listed + Verify the watch lists "WatchSettingsAbout" and neither "WatchSettingsPaired" nor any row that starts a pairing ("WatchSettingsPair" is not listed) On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), then "PairedWatchPair" + Wait up to 10 s until the watch lists "WatchPairScreen": the phone opened the Pair screen above Home Wait up to 15 s until the phone lists "PairedWatchCode" and note its six digits Verify the watch lists "WatchPairCode" with the same six digits and "WatchPairPhone" with the phone's model name Verify the phone does not list "PairedWatchSendsWallet" diff --git a/journeys/wear/pair-unpair-from-phone.xml b/journeys/wear/pair-unpair-from-phone.xml index e3169e8c26..ac0c6838a6 100644 --- a/journeys/wear/pair-unpair-from-phone.xml +++ b/journeys/wear/pair-unpair-from-phone.xml @@ -12,7 +12,7 @@ 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 "WatchSettingsPair" and no "WatchSettingsPaired" + 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 diff --git a/journeys/wear/pair-unpair-from-watch.xml b/journeys/wear/pair-unpair-from-watch.xml index 6f948fec49..1eb4c73bf2 100644 --- a/journeys/wear/pair-unpair-from-watch.xml +++ b/journeys/wear/pair-unpair-from-watch.xml @@ -11,7 +11,7 @@ Verify the dialog: the text "Unpair phone?" above one button that reads "Unpair" (tag "WatchPhoneUnpairConfirm"), and no "WatchPhoneUnpairCancel" Swipe the dialog away (README › Watch gestures, swipe-to-dismiss) and verify "WatchPhoneUnpairConfirm" is not listed and "WatchSettingsPaired" still is Tap Phone (tag "WatchSettingsPaired") again, then Unpair (tag "WatchPhoneUnpairConfirm") - Verify the watch lists "WatchSettingsPair" within 5 s + Verify the watch lists no "WatchSettingsPaired" within 5 s, and "WatchSettingsAbout" still Wait up to 10 s until the phone lists "PairedWatchPair" and no "PairedWatchName" diff --git a/journeys/wear/pay-request-from-phone.xml b/journeys/wear/pay-request-from-phone.xml new file mode 100644 index 0000000000..4dc8909fb1 --- /dev/null +++ b/journeys/wear/pay-request-from-phone.xml @@ -0,0 +1,33 @@ + + + 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 aa17ea6546..a6e38b67cf 100644 --- a/journeys/wear/quickpay-off-holds.xml +++ b/journeys/wear/quickpay-off-holds.xml @@ -5,7 +5,8 @@ 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 and leave Default Unit Bitcoin, Denomination + 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 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 diff --git a/journeys/wear/quickpay-on-app-start.xml b/journeys/wear/quickpay-on-app-start.xml index e309cb8d11..38004306f5 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 with Default Unit + 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 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 diff --git a/journeys/wear/quickpay-over-limit-holds.xml b/journeys/wear/quickpay-over-limit-holds.xml index 3fc1dc40f8..5f4bd655ff 100644 --- a/journeys/wear/quickpay-over-limit-holds.xml +++ b/journeys/wear/quickpay-over-limit-holds.xml @@ -1,13 +1,14 @@ - With QuickPay on in the phone's settings, an invoice above the phone's QuickPay amount still opens the review and + 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 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×, and the phone app closed. Watch: the app open on the Balance page and the loading ring + 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 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. diff --git a/journeys/wear/quickpay-shared-daily-limit.xml b/journeys/wear/quickpay-shared-daily-limit.xml index 1e1c0fd12d..cf546da31f 100644 --- a/journeys/wear/quickpay-shared-daily-limit.xml +++ b/journeys/wear/quickpay-shared-daily-limit.xml @@ -13,14 +13,15 @@ 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. - Phone: Local Currency USD, on Home. Watch: on the Balance page with the loading ring stopped and a fiat value + 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 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 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 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 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` diff --git a/journeys/wear/quickpay-skips-hold.xml b/journeys/wear/quickpay-skips-hold.xml index 513ea02e9d..276b0b0273 100644 --- a/journeys/wear/quickpay-skips-hold.xml +++ b/journeys/wear/quickpay-skips-hold.xml @@ -1,6 +1,7 @@ - With QuickPay on in the phone's settings, an invoice under the phone's QuickPay amount is paid without the review + 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 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. @@ -8,8 +9,9 @@ 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, 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, 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 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. diff --git a/journeys/wear/quickpay-watch-limit.xml b/journeys/wear/quickpay-watch-limit.xml new file mode 100644 index 0000000000..1d39b9056c --- /dev/null +++ b/journeys/wear/quickpay-watch-limit.xml @@ -0,0 +1,33 @@ + + + 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/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index 80bb872103..11ab67dd98 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -95,16 +95,17 @@ - + - + + +