From ada346596f1ae76b481aef85f95429876fb89738 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sun, 29 Nov 2026 09:17:27 -0300 Subject: [PATCH 01/26] feat: add watch limits and the pay request handoff to wearlink Co-Authored-By: Claude Opus 5.5 --- .../kotlin/to/bitkit/wearlink/LinkDocs.kt | 32 ++- .../to/bitkit/wearlink/LinkEndpoints.kt | 60 ++++ .../kotlin/to/bitkit/wearlink/LinkHandoff.kt | 62 +++++ .../to/bitkit/wearlink/LinkTransport.kt | 14 + .../to/bitkit/wearlink/LinkHandoffTest.kt | 263 ++++++++++++++++++ .../kotlin/to/bitkit/wearlink/LinkHarness.kt | 9 + 6 files changed, 439 insertions(+), 1 deletion(-) create mode 100644 wearlink/src/main/kotlin/to/bitkit/wearlink/LinkHandoff.kt create mode 100644 wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHandoffTest.kt diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkDocs.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkDocs.kt index 2993480e13..16964760f1 100644 --- a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkDocs.kt +++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkDocs.kt @@ -26,7 +26,9 @@ data class ControlDoc(val state: State) { /** * Phone to watch: the phone's settings the watch adopts, as the phone's settings backup names them, and when the - * phone last changed them, by the phone's clock in epoch milliseconds. + * phone last changed them, by the phone's clock in epoch milliseconds. The three `watch…` values are the watch's own + * QuickPay limits, set on the phone; a phone that predates them sends none, and their defaults leave QuickPay off on + * the watch. */ @Serializable data class SettingsDoc( @@ -37,8 +39,36 @@ data class SettingsDoc( val quickPayAmount: Int = 0, val quickPayDailyLimitMultiplier: Int = 0, val changedAtMs: Long = 0, + val isWatchQuickPayEnabled: Boolean = false, + val watchQuickPayAmount: Int = 0, + val watchQuickPayDailyLimitMultiplier: Int = 0, ) +/** + * Phone to watch, a one-shot message: a payment request the phone's user handed to the watch, [input] as the phone + * read it, to be reviewed and held to pay there, never paid under QuickPay. [id] is random per request and names it + * in the answer and in the link that brings the watch app up. + */ +@Serializable +data class PayRequestDoc(val id: String, val input: String) { + override fun toString(): String = "PayRequestDoc(id=$id)" +} + +/** Watch to phone, a one-shot message: what the watch did with the request [id]. Not the payment's outcome. */ +@Serializable +data class PayResultDoc(val id: String, val result: PayResult) + +enum class PayResult { + /** Kept for the link that brings the watch app up on the request's review. */ + Received, + + /** A send is under way on the watch, so the request was dropped. */ + Busy, + + /** Not a request the watch takes, or one it already took or that came too late. */ + Refused, +} + /** Watch to phone: what the watch has applied, and whether it still holds the pairing. */ @Serializable data class StatusDoc( diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt index 7b441ded8d..b1d338d522 100644 --- a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt +++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt @@ -96,6 +96,15 @@ abstract class LinkEndpoint internal constructor( return sealed.counter } + /** + * Seals [body] as the one-shot message [name] and sends it once, never stored by the carrier. Fails with + * [LinkError.Unreachable] when the peer cannot be reached now. + */ + protected suspend fun sendOnce(record: LinkRecord, name: String, body: ByteArray) { + val path = LinkPaths.state(record.pairingId, name) + transport.send(record.peerNodeId, path, channel(record.pairingId).seal(path, body).envelope) + } + /** * Replaces the record with the one of a pairing that just finished, dropping the keys of the one before and * whatever an earlier pairing's peer said for the guards. @@ -172,6 +181,11 @@ class PhoneLink( private val onWatchPaired: () -> Unit = {}, nowMs: () -> Long, ) : LinkEndpoint(LinkRole.Phone, transport, keys, store, peer, nowMs) { + private companion object { + /** How many answers to handed-off requests wait for a collector that is slow to take them. */ + const val PAY_RESULT_BUFFER = 16 + } + /** Notes the finished pairing with [link], replacing any earlier watch, and tells the watch it stands. */ suspend fun onPaired(link: PairedLink): LinkRecord = locked { val record = replace(link, nowMs()) @@ -193,6 +207,27 @@ class PhoneLink( } } + private val _payResults = MutableSharedFlow(extraBufferCapacity = PAY_RESULT_BUFFER) + + /** What the watch answered to the payment requests handed to it, as they arrive. */ + val payResults: Flow = _payResults.asSharedFlow() + + /** + * Hands the payment request [input] to the paired watch as the one-shot message [LinkPaths.PAY_REQUEST], under + * [id]. Fails with [LinkError.NotPaired] without a pairing or while a removal waits, and with + * [LinkError.Unreachable] when the watch cannot be reached now; nothing is stored for later. + */ + suspend fun requestPay(id: String, input: String): Unit = locked { + val record = store.load()?.takeIf { it.removal == null } ?: throw LinkError.NotPaired() + sendOnce(record, LinkPaths.PAY_REQUEST, encode(PayRequestDoc(id, input))) + } + + /** Opens [uri] on the paired watch, as the link to a handed-off request. */ + suspend fun openOnWatch(uri: String) { + val record = store.load()?.takeIf { it.removal == null } ?: throw LinkError.NotPaired() + transport.open(record.peerNodeId, uri) + } + /** * Asks the watch to forget the phone, and with [isErase] to delete its wallet too. The record stays, marked, * until the watch acknowledges or [forget] drops it: an erase is best effort, since a watch that never @@ -220,6 +255,10 @@ class PhoneLink( } override suspend fun apply(record: LinkRecord, name: String, body: ByteArray, counter: Long) { + if (name == LinkPaths.PAY_RESULT) { + _payResults.tryEmit(decode(body)) + return + } if (name != LinkPaths.STATUS) throw LinkError.Rejected("unknown document") val status = decode(body) if (status.state != StatusDoc.State.Paired) { @@ -262,6 +301,13 @@ interface WatchLinkListener : PeerStateListener { * app publishes from elsewhere, not from inside the call. */ fun onPhonePaired() + + /** + * The phone's user handed [request] to the watch, already authenticated as the paired phone's and new. The app + * keeps it for the link that brings it up on the review, or says why not; the answer goes back to the phone. + * Called while the link handles a packet, so it only decides and stores, and never waits on the screen. + */ + suspend fun onPayRequest(request: PayRequestDoc): PayResult = PayResult.Refused } /** What the watch reports about itself in its status. */ @@ -283,6 +329,15 @@ class WatchLink( record } + /** + * Tells the phone what became of the handed-off request [id] after the watch first answered it, as when the + * watch's app dropped it for a send under way. Nothing is sent without a pairing, or when the phone is away. + */ + suspend fun answerPay(id: String, result: PayResult): Unit = locked { + val record = store.load() ?: return@locked + runSuspendCatching { sendOnce(record, LinkPaths.PAY_RESULT, encode(PayResultDoc(id, result))) } + } + /** The wearer's unpair, also before the wallet is removed from the watch: tells the phone, then forgets it. */ suspend fun unpair(): Unit = locked { val record = store.load() ?: return@locked @@ -300,6 +355,11 @@ class WatchLink( } if (updated != null) publishStatus(updated, StatusDoc.State.Paired) } + LinkPaths.PAY_REQUEST -> { + val request = decode(body) + val result = if (request.isWellFormed()) listener.onPayRequest(request) else PayResult.Refused + runSuspendCatching { sendOnce(record, LinkPaths.PAY_RESULT, encode(PayResultDoc(request.id, result))) } + } LinkPaths.CONTROL -> when (decode(body).state) { ControlDoc.State.Paired -> { store.update { if (it?.pairingId == record.pairingId) it.copy(lastSeenMs = nowMs()) else it } diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkHandoff.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkHandoff.kt new file mode 100644 index 0000000000..c159450614 --- /dev/null +++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkHandoff.kt @@ -0,0 +1,62 @@ +package to.bitkit.wearlink + +/** + * A payment request handed from the phone to the watch. The phone sends it authenticated over the link + * ([PayRequestDoc]), and then opens [LinkPaths.payUri] on the watch, since only an activity may bring the watch app + * to the front. The link carries the id alone, so whoever sends it opens nothing: the watch app takes the request + * from [HandoffInbox] by that id, once, and only within [HandoffInbox.WINDOW_MS] of its arrival. A handed-off + * request always ends on the review and the hold to pay, never under QuickPay. `docs/wear.md`, Pairing › Payment + * handoff. + */ +object LinkHandoff { + /** The characters of a request id: 16 random bytes in lowercase hex. */ + const val ID_CHARS = 32 + + /** Above any payment request the phone hands over; a longer input is refused. */ + const val MAX_INPUT_CHARS = 8 * 1024 + + private val ID = Regex("^[0-9a-f]{$ID_CHARS}$") + + fun isId(id: String): Boolean = ID.matches(id) +} + +/** Whether the request has an id the phone makes and an input of a size a payment request has. */ +fun PayRequestDoc.isWellFormed(): Boolean = + LinkHandoff.isId(id) && input.isNotBlank() && input.length <= LinkHandoff.MAX_INPUT_CHARS + +/** + * The handed-off requests the watch received and has not opened yet, in memory only. Each is taken once, by its id, + * and only within [WINDOW_MS] of when it arrived, by the watch's clock; no rule compares the two devices' clocks. The + * last [MAX_IDS] ids stay known after they were taken or dropped, so a request that arrives again under one of them + * is refused. + */ +class HandoffInbox(private val nowMs: () -> Long) { + companion object { + /** How long after it arrived a handed-off request can still be opened on the watch. */ + const val WINDOW_MS = 60_000L + + /** How many request ids the watch remembers. */ + const val MAX_IDS = 20 + } + + private class Entry(val input: String, val arrivedAtMs: Long) + + private val lock = Any() + private val pending = LinkedHashMap() + private val seen = ArrayDeque() + + /** Keeps [request] for the link that opens it. False when its id was seen already, so it is not kept again. */ + fun put(request: PayRequestDoc): Boolean = synchronized(lock) { + if (request.id in seen) return false + seen.addLast(request.id) + while (seen.size > MAX_IDS) pending.remove(seen.removeFirst()) + pending[request.id] = Entry(request.input, nowMs()) + true + } + + /** The input of the request [id], once, while it is within [WINDOW_MS] of its arrival; null otherwise. */ + fun take(id: String): String? = synchronized(lock) { + val entry = pending.remove(id) ?: return null + entry.input.takeIf { nowMs() - entry.arrivedAtMs in 0..WINDOW_MS } + } +} diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt index e3f796314c..01f1c910c1 100644 --- a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt +++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt @@ -72,10 +72,24 @@ object LinkPaths { /** The link the watch app opens its Pair screen for. */ const val PAIR_URI = "bitkitwear://pair" + /** + * The link the watch app opens a handed-off payment request for, by its id alone: the request itself only ever + * arrives authenticated, as [PAY_REQUEST], so any app may send the link and it opens nothing without one. + */ + const val PAY_URI = "bitkitwear://pay" + const val PAY_ID = "id" + const val CONTROL = "p2w/control" const val SETTINGS = "p2w/settings" const val STATUS = "w2p/status" + /** The one-shot messages of a payment handed from the phone to the watch, never stored by the carrier. */ + const val PAY_REQUEST = "p2w/pay" + const val PAY_RESULT = "w2p/pay" + + /** The link that opens the handed-off request [id] on the watch. */ + fun payUri(id: String): String = "$PAY_URI?$PAY_ID=$id" + /** The name of the guard document of [kind] (see [LinkGuards]) that [writer] writes. */ fun guard(writer: LinkRole, kind: String): String = (if (writer == LinkRole.Phone) "p2w" else "w2p") + "/$kind" diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHandoffTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHandoffTest.kt new file mode 100644 index 0000000000..240c7b0557 --- /dev/null +++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHandoffTest.kt @@ -0,0 +1,263 @@ +package to.bitkit.wearlink + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class LinkHandoffTest { + private companion object { + val ID = "ab".repeat(16) + val OTHER_ID = "cd".repeat(16) + const val INVOICE = "lnbcrt10u1pexample" + + fun idOf(index: Int) = index.toString(16).padStart(LinkHandoff.ID_CHARS, '0') + } + + private suspend fun TestScope.paired(harness: LinkHarness = LinkHarness(backgroundScope)): LinkHarness { + val watchSession = harness.watchPairing() + val phoneSession = harness.phonePairing() + val watch = async { watchSession.run() } + val phone = async { phoneSession.run() } + phoneSession.state.first { it is PairingState.Code } + watchSession.state.first { it is PairingState.Code } + watchSession.confirmShown() + phoneSession.confirmShown(isAuthenticated = true) + harness.phoneLink.onPaired(phone.await()) + harness.watchLink.onPaired(watch.await()) + runCurrent() + return harness + } + + private fun TestScope.results(harness: LinkHarness): MutableList { + val results = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { harness.phoneLink.payResults.collect { results += it } } + return results + } + + // region watch limits in the settings + + @Test + fun `the watch limits reach the watch with the settings`() = runTest { + val harness = paired() + val settings = SettingsDoc( + isQuickPayEnabled = true, + quickPayAmount = 5, + quickPayDailyLimitMultiplier = 5, + isWatchQuickPayEnabled = true, + watchQuickPayAmount = 1, + watchQuickPayDailyLimitMultiplier = 3, + ) + + harness.phoneLink.publishSettings(settings) + runCurrent() + + val applied = harness.appliedSettings.single() + assertTrue(applied.isWatchQuickPayEnabled) + assertEquals(1, applied.watchQuickPayAmount) + assertEquals(3, applied.watchQuickPayDailyLimitMultiplier) + } + + @Test + fun `settings from a phone that predates the watch limits leave watch quickpay off`() { + val older = """{"isQuickPayEnabled":true,"quickPayAmount":5,"quickPayDailyLimitMultiplier":5,"changedAtMs":1}""" + + val settings = linkJson.decodeFromString(SettingsDoc.serializer(), older) + + assertFalse(settings.isWatchQuickPayEnabled) + assertEquals(0, settings.watchQuickPayAmount) + assertEquals(0, settings.watchQuickPayDailyLimitMultiplier) + } + + // endregion + + // region the request over the link + + @Test + fun `a handed-off request reaches the watch and its answer the phone`() = runTest { + val harness = paired() + val results = results(harness) + + harness.phoneLink.requestPay(ID, INVOICE) + runCurrent() + + assertEquals(listOf(PayRequestDoc(ID, INVOICE)), harness.payRequests) + assertEquals(listOf(PayResultDoc(ID, PayResult.Received)), results) + } + + @Test + fun `the request and its answer are one-shot messages, encrypted, never stored by the carrier`() = runTest { + val harness = paired() + val before = harness.network.sent.size + + harness.phoneLink.requestPay(ID, INVOICE) + runCurrent() + + val handoff = harness.network.sent.drop(before) + assertEquals(2, handoff.size) + assertTrue(handoff.none { it.isState }) + assertTrue(handoff.none { it.payload.decodeToString().contains(INVOICE) }) + assertTrue(handoff[0].path.endsWith(LinkPaths.PAY_REQUEST)) + assertTrue(handoff[1].path.endsWith(LinkPaths.PAY_RESULT)) + } + + @Test + fun `a watch that is busy answers busy`() = runTest { + val harness = paired() + harness.payAnswer = { PayResult.Busy } + val results = results(harness) + + harness.phoneLink.requestPay(ID, INVOICE) + runCurrent() + + assertEquals(listOf(PayResultDoc(ID, PayResult.Busy)), results) + } + + @Test + fun `a request with a malformed id or input is refused without reaching the app`() = runTest { + val harness = paired() + val results = results(harness) + + harness.phoneLink.requestPay("not-an-id", INVOICE) + harness.phoneLink.requestPay(ID, " ") + runCurrent() + + assertTrue(harness.payRequests.isEmpty()) + assertEquals(listOf(PayResult.Refused, PayResult.Refused), results.map { it.result }) + } + + @Test + fun `a replayed request is not taken again`() = runTest { + val harness = paired() + harness.phoneLink.requestPay(ID, INVOICE) + runCurrent() + val request = harness.network.sent.last { it.path.endsWith(LinkPaths.PAY_REQUEST) } + + harness.network.replay(request) + runCurrent() + + assertEquals(1, harness.payRequests.size) + assertTrue(harness.watchErrors.any { it is LinkError.Rejected }) + } + + @Test + fun `an unreachable watch fails the request at once and nothing waits for later`() = runTest { + val harness = paired() + harness.network.isConnected = false + + assertFailsWith { harness.phoneLink.requestPay(ID, INVOICE) } + harness.network.reconnect() + runCurrent() + + assertTrue(harness.payRequests.isEmpty()) + } + + @Test + fun `no request is sent without a pairing or while a removal waits`() = runTest { + val harness = paired() + harness.phoneLink.remove(isErase = false) + + assertFailsWith { harness.phoneLink.requestPay(ID, INVOICE) } + assertFailsWith { LinkHarness(backgroundScope).phoneLink.requestPay(ID, INVOICE) } + } + + @Test + fun `the watch tells the phone later that it dropped a request it had taken`() = runTest { + val harness = paired() + val results = results(harness) + harness.phoneLink.requestPay(ID, INVOICE) + runCurrent() + + harness.watchLink.answerPay(ID, PayResult.Busy) + runCurrent() + + assertEquals(listOf(PayResult.Received, PayResult.Busy), results.map { it.result }) + } + + @Test + fun `the phone opens the request's link on the paired watch`() = runTest { + val harness = paired() + + harness.phoneLink.openOnWatch(LinkPaths.payUri(ID)) + + assertEquals("bitkitwear://pay?id=$ID", harness.network.opened.last()) + } + + @Test + fun `a request prints no input`() { + assertFalse(PayRequestDoc(ID, INVOICE).toString().contains(INVOICE)) + } + + // endregion + + // region the watch's inbox + + @Test + fun `a request is taken once`() { + val inbox = HandoffInbox { 0 } + inbox.put(PayRequestDoc(ID, INVOICE)) + + assertEquals(INVOICE, inbox.take(ID)) + assertNull(inbox.take(ID)) + } + + @Test + fun `a request is not taken after its window`() { + var now = 0L + val inbox = HandoffInbox { now } + inbox.put(PayRequestDoc(ID, INVOICE)) + + now = HandoffInbox.WINDOW_MS + 1 + + assertNull(inbox.take(ID)) + } + + @Test + fun `a request is taken at the end of its window`() { + var now = 0L + val inbox = HandoffInbox { now } + inbox.put(PayRequestDoc(ID, INVOICE)) + + now = HandoffInbox.WINDOW_MS + + assertEquals(INVOICE, inbox.take(ID)) + } + + @Test + fun `an id seen before is not kept again, also after it was taken`() { + val inbox = HandoffInbox { 0 } + assertTrue(inbox.put(PayRequestDoc(ID, INVOICE))) + inbox.take(ID) + + assertFalse(inbox.put(PayRequestDoc(ID, "lnbcrt1other"))) + assertNull(inbox.take(ID)) + } + + @Test + fun `only the last ids are kept, and an old one opens nothing`() { + val inbox = HandoffInbox { 0 } + inbox.put(PayRequestDoc(OTHER_ID, INVOICE)) + repeat(HandoffInbox.MAX_IDS) { inbox.put(PayRequestDoc(idOf(it), INVOICE)) } + + assertNull(inbox.take(OTHER_ID)) + assertEquals(INVOICE, inbox.take(idOf(1))) + } + + @Test + fun `an unknown id opens nothing`() { + assertNull(HandoffInbox { 0 }.take(ID)) + } + + // endregion +} diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt index fcc2b93e13..84223ca101 100644 --- a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt +++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt @@ -81,6 +81,10 @@ class LinkHarness(scope: CoroutineScope) { /** How often the phone heard, from a pairing's first status, that the watch noted it. */ var watchPaired = 0 + /** The payment requests the watch was handed, and what it answers to them. */ + val payRequests = mutableListOf() + var payAnswer: (PayRequestDoc) -> PayResult = { PayResult.Received } + /** What each side holds of the other's guard documents. */ val phonePeer = RecordingPeer() val watchPeer = RecordingPeer() @@ -131,6 +135,11 @@ class LinkHarness(scope: CoroutineScope) { override fun onPhonePaired() { phonePaired++ } + + override suspend fun onPayRequest(request: PayRequestDoc): PayResult { + payRequests += request + return payAnswer(request) + } }, info = { WatchInfo("1.0 (1)", isLockSet = true) }, nowMs = { now }, From b4fce205c8413d4f46f51cc6f4d961d557e17a96 Mon Sep 17 00:00:00 2001 From: Joao Victor Sena Date: Sun, 29 Nov 2026 12:28:44 -0300 Subject: [PATCH 02/26] feat: hold watch quickpay to its own limits set from the phone's watch sheet Co-Authored-By: Claude Opus 5.5 --- .../main/java/to/bitkit/data/SettingsStore.kt | 10 + .../java/to/bitkit/data/WatchLinkStore.kt | 4 + .../to/bitkit/repositories/QuickPayRepo.kt | 32 ++- .../to/bitkit/repositories/WatchLinkRepo.kt | 18 ++ .../ui/sheets/watch/WatchQuickPayViewModel.kt | 109 ++++++++++ .../to/bitkit/ui/sheets/watch/WatchSheet.kt | 198 ++++++++++++++++-- .../ui/sheets/watch/WatchSheetViewModel.kt | 15 +- app/src/main/res/values-ar/strings.xml | 5 + app/src/main/res/values-b+es+419/strings.xml | 5 + app/src/main/res/values-ca/strings.xml | 5 + app/src/main/res/values-cs/strings.xml | 5 + app/src/main/res/values-de/strings.xml | 5 + app/src/main/res/values-el/strings.xml | 5 + app/src/main/res/values-es-rES/strings.xml | 5 + app/src/main/res/values-es/strings.xml | 5 + app/src/main/res/values-fr/strings.xml | 5 + app/src/main/res/values-it/strings.xml | 5 + app/src/main/res/values-nl/strings.xml | 5 + app/src/main/res/values-pl/strings.xml | 5 + app/src/main/res/values-pt-rBR/strings.xml | 5 + app/src/main/res/values-pt/strings.xml | 5 + app/src/main/res/values-ru/strings.xml | 5 + app/src/main/res/values/strings.xml | 5 + .../java/to/bitkit/models/BackupJsonTest.kt | 24 +++ .../bitkit/models/WatchBackupContractTest.kt | 11 +- .../bitkit/repositories/QuickPayRepoTest.kt | 64 ++++++ .../bitkit/repositories/WatchLinkRepoTest.kt | 36 ++++ .../watch/WatchQuickPayViewModelTest.kt | 115 ++++++++++ .../sheets/watch/WatchSheetViewModelTest.kt | 27 +++ wear/src/main/AndroidManifest.xml | 9 +- .../java/to/bitkit/wear/data/HandoffStore.kt | 52 +++++ .../to/bitkit/wear/data/QuickPaySpendStore.kt | 13 +- .../java/to/bitkit/wear/data/SettingsStore.kt | 33 ++- .../to/bitkit/wear/models/PhoneSettings.kt | 64 +++++- .../bitkit/wear/repositories/PhoneLinkRepo.kt | 30 ++- .../bitkit/wear/repositories/QuickPayRepo.kt | 48 +++-- .../main/java/to/bitkit/wear/ui/LaunchGate.kt | 20 +- .../java/to/bitkit/wear/ui/LaunchRequest.kt | 30 ++- .../src/main/java/to/bitkit/wear/ui/Routes.kt | 11 +- .../java/to/bitkit/wear/ui/WearNavHost.kt | 13 +- .../wear/ui/screens/send/SendViewModel.kt | 10 +- .../wear/data/QuickPaySpendStoreTest.kt | 26 ++- .../to/bitkit/wear/data/SettingsStoreTest.kt | 19 +- .../to/bitkit/wear/link/PhoneLinkRepoTest.kt | 108 ++++++++++ .../wear/models/PhoneBackupContractTest.kt | 13 +- .../wear/models/PhoneSettingsParserTest.kt | 69 +++++- .../wear/repositories/QuickPayRepoTest.kt | 65 +++++- .../java/to/bitkit/wear/ui/LaunchGateTest.kt | 54 ++++- .../to/bitkit/wear/ui/LaunchRequestTest.kt | 26 +++ .../wear/ui/screens/send/SendViewModelTest.kt | 19 ++ .../test/resources/phone-backup-contract.json | 5 +- 51 files changed, 1387 insertions(+), 93 deletions(-) create mode 100644 app/src/main/java/to/bitkit/ui/sheets/watch/WatchQuickPayViewModel.kt create mode 100644 app/src/test/java/to/bitkit/ui/sheets/watch/WatchQuickPayViewModelTest.kt create mode 100644 wear/src/main/java/to/bitkit/wear/data/HandoffStore.kt 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..1a8d9a57e5 100644 --- a/app/src/main/java/to/bitkit/data/WatchLinkStore.kt +++ b/app/src/main/java/to/bitkit/data/WatchLinkStore.kt @@ -60,6 +60,10 @@ class WatchLinkStore internal constructor( override val record: Flow = store.data.map { it.record }.distinctUntilChanged() + /** The watch's last QuickPay count as it changes, or null without a paired watch or before its first count. */ + val watchQuickPayUpdates: Flow = + store.data.map { data -> data.watchQuickPay?.takeIf { data.record != null } }.distinctUntilChanged() + override suspend fun load(): LinkRecord? = store.data.first().record override suspend fun update(transform: (LinkRecord?) -> LinkRecord?): LinkRecord? = diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index 4f0525c74d..871986381e 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -161,8 +161,9 @@ class QuickPayRepo @Inject constructor( } /** - * Queues [change] behind every earlier settings call, so changes are decided in call order. When payments need a - * PIN and [change] enables QuickPay or raises one of its limits against the settings current at that point, it + * Queues [change] behind every earlier settings call, so changes are decided in call order. When [change] needs + * the PIN ([QuickPayChange.needsAuth]) and enables QuickPay or raises one of its limits against the settings + * current at that point, it * saves nothing and opens a check in [pendingSettingsChange], or is ignored while a check is already open. Any * other change saves at once and closes an open check. The result completes once the change is decided. */ @@ -205,7 +206,7 @@ class QuickPayRepo @Inject constructor( var next = open settingsStore.update { settings -> when { - !settings.requiresPaymentAuth || !change.isRaise(settings) -> { + !change.needsAuth(settings) || !change.isRaise(settings) -> { next = null change.applyTo(settings) } @@ -989,10 +990,15 @@ 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. A raise asks for the PIN or biometric check + * when [needsAuth]: for the phone's own QuickPay while payments need the PIN, for the watch's whenever the app has a + * PIN, since the watch has none of its own to ask for. + */ sealed interface QuickPayChange { fun isRaise(settings: SettingsData): Boolean fun applyTo(settings: SettingsData): SettingsData + fun needsAuth(settings: SettingsData): Boolean = settings.requiresPaymentAuth data class Enabled(val value: Boolean) : QuickPayChange { override fun isRaise(settings: SettingsData) = value && !settings.isQuickPayEnabled @@ -1008,6 +1014,24 @@ 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) + override fun needsAuth(settings: SettingsData) = settings.isPinEnabled + } + + data class WatchAmount(val value: Int) : QuickPayChange { + override fun isRaise(settings: SettingsData) = value > settings.watchQuickPayAmount + override fun applyTo(settings: SettingsData) = settings.copy(watchQuickPayAmount = value) + override fun needsAuth(settings: SettingsData) = settings.isPinEnabled + } + + data class WatchDailyLimitMultiplier(val value: Int) : QuickPayChange { + override fun isRaise(settings: SettingsData) = value > settings.watchQuickPayDailyLimitMultiplier + override fun applyTo(settings: SettingsData) = settings.copy(watchQuickPayDailyLimitMultiplier = value) + override fun needsAuth(settings: SettingsData) = settings.isPinEnabled + } } 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..604bac5bc6 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt @@ -31,6 +31,8 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlinx.datetime.TimeZone +import kotlinx.datetime.toLocalDateTime import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore import to.bitkit.data.SettingsData @@ -47,6 +49,7 @@ import to.bitkit.wearlink.AttestationPolicy import to.bitkit.wearlink.AttestationStatusList import to.bitkit.wearlink.AttestationVerifier import to.bitkit.wearlink.LinkCrypto +import to.bitkit.wearlink.LinkGuards import to.bitkit.wearlink.LinkKeyStore import to.bitkit.wearlink.LinkNode import to.bitkit.wearlink.LinkPacket @@ -84,6 +87,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 @@ -221,6 +225,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() @@ -388,8 +400,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() 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..96da6e9fb6 --- /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 whenever the app has a PIN, 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..c2e0b3eb3d 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,25 @@ 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.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 +61,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. */ @@ -67,9 +78,12 @@ private val REFRESH_INTERVAL = 3.seconds fun WatchSheet( app: AppViewModel, 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() } @@ -88,19 +102,34 @@ 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, + 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,6 +148,7 @@ fun WatchSheet( private fun Content( uiState: WatchSheetUiState, modifier: Modifier = Modifier, + quickPay: WatchQuickPayUiState = WatchQuickPayUiState(), onPairClick: () -> Unit = {}, onPairClose: () -> Unit = {}, onPairConfirm: () -> Unit = {}, @@ -127,10 +157,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 +177,38 @@ 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, + ) } VerticalSpacer(16.dp) } @@ -182,6 +236,8 @@ private fun Content( @Composable private fun ColumnScope.Unpaired( uiState: WatchSheetUiState, + isQuickPayEnabled: Boolean, + onQuickPayClick: () -> Unit, onPairClick: () -> Unit, ) { val connected = uiState.connected @@ -197,6 +253,8 @@ private fun ColumnScope.Unpaired( color = Colors.White64, modifier = Modifier.testTag("PairedWatchStatus") ) + VerticalSpacer(16.dp) + QuickPayRow(isEnabled = isQuickPayEnabled, onClick = onQuickPayClick) Illustration(R.drawable.phone) PrimaryButton( text = stringResource(R.string.settings__watch__pair_button), @@ -211,6 +269,8 @@ private fun ColumnScope.Unpaired( @Composable private fun ColumnScope.Paired( watch: PairedWatch, + isQuickPayEnabled: Boolean, + onQuickPayClick: () -> Unit, onUnpairClick: () -> Unit, onEraseClick: () -> Unit, onStopWaitingClick: () -> Unit, @@ -268,6 +328,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 +357,99 @@ 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") + ) + } + } +} + +/** [cents] as dollars with two decimals, as the QuickPay limits read. */ +private fun dollars(cents: Long): String = BigDecimal.valueOf(cents, 2).toPlainString() + @Composable private fun ColumnScope.Pairing( step: WatchPairStep, @@ -492,3 +647,18 @@ 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..41c92c59c0 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 @@ -79,7 +79,9 @@ 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() } @@ -104,7 +106,7 @@ class WatchSheetViewModel @Inject constructor( /** Starts a pairing with the connected watch. */ fun onPairClick() { watchLinkRepo.cancelPairing() - _uiState.update { it.copy(pairing = WatchPairStep.Connecting, isAuthShown = false) } + _uiState.update { it.copy(pairing = WatchPairStep.Connecting, isAuthShown = false, isQuickPayShown = false) } watchLinkRepo.startPairing() } @@ -148,9 +150,14 @@ class WatchSheetViewModel @Inject constructor( refreshJob?.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) } + fun onUnpairClick() = _uiState.update { it.copy(dialog = WatchRemoveDialog.Unpair) } fun onEraseClick() = _uiState.update { it.copy(dialog = WatchRemoveDialog.Erase) } @@ -225,6 +232,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,6 +243,7 @@ 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. */ diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index c1f0ec4f52..1610aadedc 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -925,6 +925,11 @@ لا توجد محفظة على هذه الساعة. الإقران يرسل إليها عبارة الاسترداد الخاصة بك، فتصبح حاملة لمحفظتك الكاملة. إقران الساعة أكّد الرمز على ساعتك. + QuickPay على الساعة + تدفع ساعتك بهذه الطريقة حتى ${limit} يوميًا. ومع هذا الهاتف تبقى ضمن حد QuickPay اليومي لهذا الهاتف. + QuickPay متوقف على هذا الهاتف، لذا فهو متوقف على ساعتك أيضًا. + المُنفق اليوم عبر QuickPay على ساعتك: ${spent} + المدفوعات حتى ${amount} على ساعتك لا تحتاج إلى الضغط المطوّل للدفع. لا يوجد رمز PIN على ساعتك، لذا اجعل هذا المبلغ منخفضًا. {name} جاهزة للإقران. الإعدادات ليست على الساعة بعد. إعدادات الساعة محدّثة. 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..ee28bcb84b 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -946,6 +946,11 @@ 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. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 2ba3dd584b..7260a28165 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -940,6 +940,11 @@ 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. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index da41b94409..a624593cf0 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -945,6 +945,11 @@ 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í. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 80b190f8c3..c4e6621d3d 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -782,6 +782,11 @@ 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. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 12973abf61..cf74830b8e 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -925,6 +925,11 @@ Αυτό το ρολόι δεν έχει πορτοφόλι. Η σύζευξη του στέλνει τη φράση ανάκτησής σου, οπότε θα περιέχει ολόκληρο το πορτοφόλι σου. Σύζευξη ρολογιού Επιβεβαίωσε τον κωδικό στο ρολόι σου. + QuickPay στο ρολόι + Το ρολόι σας πληρώνει έτσι έως ${limit} την ημέρα. Μαζί με αυτό το τηλέφωνο μένει εντός του ημερήσιου ορίου QuickPay αυτού του τηλεφώνου. + Το QuickPay είναι απενεργοποιημένο σε αυτό το τηλέφωνο, άρα και στο ρολόι σας. + Δαπανήθηκαν σήμερα με QuickPay στο ρολόι σας: ${spent} + Οι πληρωμές έως ${amount} στο ρολόι σας δεν χρειάζονται παρατεταμένο πάτημα. Το ρολόι σας δεν έχει PIN, οπότε κρατήστε το ποσό χαμηλό. Το {name} είναι έτοιμο για σύζευξη. Οι ρυθμίσεις δεν είναι ακόμη στο ρολόι. Οι ρυθμίσεις του ρολογιού είναι ενημερωμένες. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index ea84475100..12c7a123b8 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -943,6 +943,11 @@ 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. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index b24fd0f4f0..60d2d0301e 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -779,6 +779,11 @@ 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. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 032ffb21e3..784dda64e2 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -782,6 +782,11 @@ 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. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index e767df0977..aacb19a096 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -942,6 +942,11 @@ 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. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 3c85fff08d..c0fe8619f7 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -940,6 +940,11 @@ 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. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index ef62f31260..70df2f18de 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -783,6 +783,11 @@ 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. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index e6c3bb4597..43be9cada8 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -947,6 +947,11 @@ 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. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index a86f2e8e92..41ee79bc46 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -761,6 +761,11 @@ 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. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 2c1f4ce0c1..03915b86ab 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -959,6 +959,11 @@ На этих часах нет кошелька. При сопряжении на них отправляется ваша фраза восстановления, поэтому на них будет храниться ваш кошелёк целиком. Сопряжение Часов Подтвердите код на часах. + QuickPay на часах + Так часы платят до ${limit} в день. Вместе с этим телефоном они остаются в пределах дневного лимита QuickPay этого телефона. + QuickPay выключен на этом телефоне, а значит, и на часах. + Потрачено сегодня через QuickPay на часах: ${spent} + Платежи до ${amount} на часах проходят без удержания. На часах нет PIN-кода, поэтому держите сумму небольшой. Устройство {name} готово к сопряжению. Настройки ещё не переданы на часы. Настройки часов актуальны. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 864c33d60c..f32b4fa284 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1283,6 +1283,11 @@ 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. 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..64a7f9d2a6 100644 --- a/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt +++ b/app/src/test/java/to/bitkit/models/WatchBackupContractTest.kt @@ -15,8 +15,8 @@ import kotlin.test.assertEquals /** * The Wear OS app imports the phone's settings by reading the settings backup from VSS (docs/wear.md, Settings - * sync). `wear/src/test/resources/phone-backup-contract.json` holds what it relies on: the backup's key, 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 +34,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 +44,9 @@ class WatchBackupContractTest { isQuickPayEnabled = true, quickPayAmount = 10, quickPayDailyLimitMultiplier = 3, + isWatchQuickPayEnabled = true, + watchQuickPayAmount = 1, + watchQuickPayDailyLimitMultiplier = 5, ) val written = written(settings) @@ -54,7 +57,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..409d698173 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -222,6 +222,70 @@ class QuickPayRepoTest : BaseUnitTest() { } } + @Test + fun `turning on or raising the watch's quickpay asks for the pin whenever the app has one`() = test { + stubSettingsUpdate() + listOf( + pinSettings(isBiometricEnabled = true), + SettingsData(isPinEnabled = true, isPinForPaymentsEnabled = false), + ).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, and so does a raise without a pin`() = 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, + ) + + settingsData.value = SettingsData(isPinEnabled = false) + sut.requestSettingsChange(QuickPayChange.WatchEnabled(true)).await().getOrThrow() + sut.requestSettingsChange(QuickPayChange.WatchAmount(50)).await().getOrThrow() + + assertNull(sut.pendingSettingsChange.value) + assertTrue(settingsData.value.isWatchQuickPayEnabled) + assertEquals(50, settingsData.value.watchQuickPayAmount) + } + + @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..26c47d48df 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt @@ -9,6 +9,8 @@ import kotlinx.coroutines.flow.update 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 @@ -271,6 +273,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() 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..2187c32ac2 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 @@ -515,4 +515,31 @@ 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(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(repo) + sut.onQuickPayClick() + sut.onSheetClose() + assertFalse(sut.uiState.value.isQuickPayShown) + + sut.onQuickPayClick() + sut.onPairClick() + assertFalse(sut.uiState.value.isQuickPayShown) + } + + // endregion } 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 @@ - + - + + +