Modern Apps git

← Modern-Apps.git

globalesim: pay-first setup fee, SIM ID transfer, payment fixes

Commit
d5202e50273533af9fd3af77f8c898a93f9c81df
Author
vayun-mathur <[email protected]>
When
2026-10-24 23:52 UTC (1 month ago)
Parents
8a984f1

Diff

globalesim/AGENTS.md
diff --git a/globalesim/AGENTS.md b/globalesim/AGENTS.mdindex 6d2f519e0b..dcedbcf265 100644--- a/globalesim/AGENTS.md+++ b/globalesim/AGENTS.md@@ -7,21 +7,25 @@ _Install: ./install globalesim (dev by default)._ - Gradle: :globalesim / dir: globalesim/ - Package roots present: ui, data, domain, platform - Entry files: MainActivity.kt, Route.kt, Navigation.kt-- Deps: :library:network, :library:ui (via conventions), androidx.datastore.preferences, stripe-android+- Deps: :library:network, :library:log, :library:ui (via conventions), androidx.datastore.preferences, stripe-android - Metadata: metadata_data/globalesim.md (present) - Rust: no / screenshotTest: yes  ## Overview **Purpose:** Travel data eSIM storefront. One global eSIM per anonymous account — top up USD credit, data deducts at the local per-country rate. Credit never expires. **Key features:**-- Anonymous account (client-minted UUIDv4, no email/PII) with transfer codes for new phones-- Rate catalog, wallet top-ups (budget pool → on-SIM wallet), Stripe card purchases+- Pay-first: no eSIM until the first top-up ($5 min, card or crypto); the server keeps a $3 setup fee and funds the rest+- Anonymous account (client-minted UUIDv4, no PII). The account id is the only credential and is shown as the "SIM ID": Copy SIM ID on the old phone, Claim on a phone without an eSIM+- Rate catalog (server-scaled to the wallet's face value), Stripe card and NOWPayments crypto (+5%) top-ups, $5–$20 per payment - One-tap install handoff to the euicc LPA (`EsimLink.provisioningUri` pinned to LPA package) **Architecture / data-flow:** `ui/` screens → `platform/EsimViewModel` (single `EsimUiState`) → `data/api/EsimApi` (own `/esim/v1/*` on api.maproj.org, FIRST_PARTY) with pure `domain/QuoteMath` and `data/AnonymousIdStore` (DataStore UUID). The reseller vendor is server-only (`location_share_server/src/handlers/esim*.rs`) and never named here.-**Entry points + reading order:** `Route` (`Home` / `Rates` / `Install` / `Transfer` / `Budget`) → `MainActivity.kt` → `Navigation.kt` → `platform/EsimViewModel.kt` → `data/api/EsimApi.kt`.+**Entry points + reading order:** `Route.Tabs` (Purchase + Pricing tabs, no other routes) → `MainActivity.kt` → `Navigation.kt` → `platform/EsimViewModel.kt` → `data/api/EsimApi.kt`. **Gotchas:**-- Top-up buttons disable while loading; each attempt carries a fresh idempotency key, server dedupes replays-- PaymentSheet presents from `pendingClientSecret` via LaunchedEffect; cleared on done/cancel+- After any payment the ViewModel polls `/status` until the wallet rises (server-owned pending checkout + `pending_credit_cents` keep it going); pull-to-refresh on Purchase reloads status+- One open crypto checkout per account, owned by the server and restored from `/status`+- PaymentSheet presents each client secret once (saved across recreation); cleared on done/cancel+- ViewModel messages are shown once by the tab host in `Navigation.kt`, not by the screens+- Never log the account id / SIM ID; the clipboard copy is flagged sensitive - Install shows no QR/code — same-phone QR is unscannable; direct LPA handoff only - `rememberPaymentSheet` is deprecated in stripe-android 23.x (same as fooddelivery); leave until repo migrates @@ -34,16 +38,15 @@ _Install: ./install globalesim (dev by default)._ - com/vayunmathur/globalesim/data/api/EsimApi.kt — BASE_URL + url(path) + NetworkClient calls - com/vayunmathur/globalesim/data/api/EsimDtos.kt — generic DTOs only, no vendor strings - com/vayunmathur/globalesim/data/AnonymousIdStore.kt-### domain/ — pure math (no Android)-- com/vayunmathur/globalesim/domain/QuoteMath.kt+### domain/ — pure logic (no Android)+- com/vayunmathur/globalesim/domain/QuoteMath.kt — payment bounds, cents formatting/parsing+- com/vayunmathur/globalesim/domain/CheckoutUrls.kt+- com/vayunmathur/globalesim/domain/EsimActivationCode.kt ### platform/ — ViewModel - com/vayunmathur/globalesim/platform/EsimViewModel.kt ### ui/ — one public @Composable per file-- com/vayunmathur/globalesim/ui/HomeScreen.kt-- com/vayunmathur/globalesim/ui/RatesScreen.kt-- com/vayunmathur/globalesim/ui/InstallScreen.kt-- com/vayunmathur/globalesim/ui/TransferScreen.kt-- com/vayunmathur/globalesim/ui/BudgetScreen.kt+- com/vayunmathur/globalesim/ui/HomeScreen.kt — Purchase tab (balance, top-up, install, Copy SIM ID / Claim)+- com/vayunmathur/globalesim/ui/PricingScreen.kt — Pricing tab  ## Verify (this module only) ```
globalesim/src/main/java/com/vayunmathur/globalesim/Navigation.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/Navigation.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/Navigation.ktindex f25c3bc95e..ef5f91ef46 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/Navigation.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/Navigation.kt@@ -3,21 +3,20 @@ package com.vayunmathur.globalesim import android.content.Intent import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.runtime.Composable-import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.platform.LocalContext import androidx.core.net.toUri import com.vayunmathur.globalesim.platform.EsimViewModel import com.vayunmathur.globalesim.ui.HomeScreen import com.vayunmathur.globalesim.ui.PricingScreen-import com.vayunmathur.globalesim.ui.TransferScreen import com.vayunmathur.library.ui.IconGlobe import com.vayunmathur.library.ui.IconSim import com.vayunmathur.library.ui.PagerTab import com.vayunmathur.library.ui.TabStyle import com.vayunmathur.library.ui.TabbedPagerScaffold+import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack-import kotlinx.coroutines.launch  @Composable fun Navigation(viewModel: EsimViewModel) {@@ -25,66 +24,46 @@ fun Navigation(viewModel: EsimViewModel) {      MainNavigation(backStack) {         entry<Route.Tabs> {-            EsimTabs(-                viewModel = viewModel,-                onOpenTransfer = { backStack.add(Route.Transfer) },-            )-        }-        entry<Route.Transfer> {-            TransferScreen(-                state = viewModel.state,-                onTransferOut = viewModel::transferOut,-                onTransferIn = { oldId, code ->-                    viewModel.transferIn(oldId, code) { backStack.reset(Route.Tabs) }-                },-                onNavigateBack = { backStack.pop() },-            )+            EsimTabs(viewModel = viewModel)         }     } }  /**  * The two bottom-nav tabs: Purchase (your eSIM + top-ups) and Pricing- * (searchable per-country rates). Install and Transfer push on top as- * ordinary routes.+ * (searchable per-country rates). ViewModel messages are shown here, once,+ * rather than by each tab (both tabs stay composed in the pager).  */ @Composable-private fun EsimTabs(-    viewModel: EsimViewModel,-    onOpenTransfer: () -> Unit,-) {+private fun EsimTabs(viewModel: EsimViewModel) {     val context = LocalContext.current+    val messenger = rememberMessenger()+    val message = viewModel.state.message+    LaunchedEffect(message) {+        if (message != null) {+            messenger.show(message)+            viewModel.dismissMessage()+        }+    }     val pagerState = rememberPagerState(pageCount = { 2 })     val tabs = listOf(         PagerTab("Purchase", { IconSim() }) {             HomeScreen(                 state = viewModel.state,-                onCreateEsim = viewModel::createEsim,                 onStartCardPurchase = viewModel::startCardPurchase,-                onCardPurchaseDone = {-                    viewModel.clearPendingPurchase()-                    viewModel.refreshAll()-                },+                onCardPurchaseDone = viewModel::finishCardPurchase,                 onStartCryptoPurchase = { cents ->                     viewModel.startCryptoPurchase(cents) { url ->                         context.startActivity(Intent(Intent.ACTION_VIEW, url.toUri()))                     }                 },-                onCheckCryptoStatus = {-                    viewModel.checkCryptoStatus { status ->-                        if (status == "finished") viewModel.refreshAll()-                    }-                },                 onClearCryptoInvoice = viewModel::clearPendingInvoice,-                onOpenTransfer = onOpenTransfer,-                onDismissError = viewModel::dismissError,+                onClaim = viewModel::claim,+                onRefresh = viewModel::refresh,             )         },         PagerTab("Pricing", { IconGlobe() }) {-            PricingScreen(-                state = viewModel.state,-                onDismissError = viewModel::dismissError,-            )+            PricingScreen(state = viewModel.state, onRefresh = viewModel::refreshRates)         },     )     TabbedPagerScaffold(tabs = tabs, pagerState = pagerState, tabStyle = TabStyle.BottomNav)
globalesim/src/main/java/com/vayunmathur/globalesim/Route.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/Route.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/Route.ktindex d163a9c85d..d80561fd4e 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/Route.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/Route.kt@@ -8,8 +8,4 @@ sealed interface Route : NavKey {     /** Tab host: Purchase + Pricing. */     @Serializable     data object Tabs : Route--    /** Move the eSIM to a new phone. */-    @Serializable-    data object Transfer : Route }
globalesim/src/main/java/com/vayunmathur/globalesim/data/AnonymousIdStore.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/data/AnonymousIdStore.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/data/AnonymousIdStore.ktindex ba56518133..79829cff39 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/data/AnonymousIdStore.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/data/AnonymousIdStore.kt@@ -13,8 +13,8 @@ private val Context.esimAccountStore by preferencesDataStore(name = "esim_accoun  /**  * Anonymous account id store. The id is a client-minted UUIDv4 — no email,- * no PII. The same id (+ transfer code) reinstalls the user's eSIMs on a- * new phone. Auto-registers with the backend on first use.+ * no PII — minted locally on first use. It is the account's only+ * credential; the app shows it as the "SIM ID" for claiming on another phone.  */ class AnonymousIdStore(private val context: Context) {     val accountId: Flow<String?> =@@ -29,7 +29,7 @@ class AnonymousIdStore(private val context: Context) {         return fresh     } -    /** Replaces the id (used after a transfer-in adopts the new device id). */+    /** Replaces the id (after this install's eSIM was claimed onto another phone). */     suspend fun replace(newId: String) {         context.esimAccountStore.edit { it[KEY_ACCOUNT_ID] = newId }     }
globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimApi.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimApi.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimApi.ktindex 3fef7d15df..53239ae9ba 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimApi.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimApi.kt@@ -49,28 +49,14 @@ object EsimApi {     private suspend inline fun <reified Res> get(path: String): Res =         wrapApiErrors { NetworkClient.getJson(url(path)) } -    suspend fun register(accountId: String): RegisterResponse =-        post("/esim/v1/register", RegisterRequest(accountId))-     suspend fun rates(): RatesResponse = get("/esim/v1/rates")      suspend fun status(accountId: String): StatusResponse =         post("/esim/v1/status", AccountRequest(accountId)) -    suspend fun detail(accountId: String, iccid: String): ProfileDto =-        post("/esim/v1/detail", ManageRequest(accountId, iccid))--    suspend fun enable(accountId: String, iccid: String): ManageResponse =-        post("/esim/v1/enable", ManageRequest(accountId, iccid))--    suspend fun disable(accountId: String, iccid: String): ManageResponse =-        post("/esim/v1/disable", ManageRequest(accountId, iccid))--    suspend fun transferOut(accountId: String): TransferOutResponse =-        post("/esim/v1/transfer-out", TransferOutRequest(accountId))--    suspend fun transferIn(oldAccountId: String, code: String, newAccountId: String): TransferInResponse =-        post("/esim/v1/transfer-in", TransferInRequest(oldAccountId, code, newAccountId))+    /** Move the eSIM whose SIM ID is [simId] onto [accountId] (this phone). */+    suspend fun claim(simId: String, accountId: String): OkResponse =+        post("/esim/v1/transfer-in", TransferInRequest(simId, accountId))      suspend fun stripeKey(): StripeKeyResponse = get("/esim/v1/stripe-key") @@ -80,6 +66,6 @@ object EsimApi {     suspend fun nowPayInvoice(accountId: String, amountCents: Long): NowPayInvoiceResponse =         post("/esim/v1/nowpay-invoice", NowPayInvoiceRequest(accountId, amountCents)) -    suspend fun nowPayStatus(accountId: String, invoiceId: String): NowPayStatusResponse =-        post("/esim/v1/nowpay-status", NowPayStatusRequest(accountId, invoiceId))+    suspend fun nowPayCancel(accountId: String): OkResponse =+        post("/esim/v1/nowpay-cancel", AccountRequest(accountId)) }
globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimDtos.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimDtos.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimDtos.ktindex 216f4c77e2..b275b6ab4e 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimDtos.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimDtos.kt@@ -18,15 +18,6 @@ import kotlinx.serialization.Serializable  * SerialName decodes to defaults with no error).  */ -@Serializable-data class RegisterRequest(@SerialName("account_id") val accountId: String)--@Serializable-data class RegisterResponse(-    @SerialName("ok") val ok: Boolean = false,-    @SerialName("profile") val profile: ProfileDto? = null,-)- @Serializable data class RateDto(     @SerialName("country_code") val countryCode: String,@@ -61,33 +52,28 @@ data class ProfileDto( )  @Serializable-data class StatusResponse(@SerialName("profile") val profile: ProfileDto? = null)--@Serializable-data class ManageRequest(-    @SerialName("account_id") val accountId: String,-    @SerialName("iccid") val iccid: String,+data class StatusResponse(+    @SerialName("profile") val profile: ProfileDto? = null,+    /** The account's one open crypto checkout, if any. */+    @SerialName("pending_invoice_url") val pendingInvoiceUrl: String? = null,+    /** Paid but not yet in the wallet (eSIM being created, or funding retrying). */+    @SerialName("pending_credit_cents") val pendingCreditCents: Long = 0,+    /** The balance is a last-known fallback; the server couldn't read it live. */+    @SerialName("balance_stale") val balanceStale: Boolean = false,+    /** This account's eSIM was claimed onto another phone. */+    @SerialName("transferred") val transferred: Boolean = false, )  @Serializable-data class ManageResponse(@SerialName("ok") val ok: Boolean = false)--@Serializable-data class TransferOutRequest(@SerialName("account_id") val accountId: String)--@Serializable-data class TransferOutResponse(@SerialName("transfer_code") val transferCode: String = "")+data class OkResponse(@SerialName("ok") val ok: Boolean = false) +/** Claim: [oldAccountId] is the SIM ID copied from the other phone. */ @Serializable data class TransferInRequest(     @SerialName("old_account_id") val oldAccountId: String,-    @SerialName("code") val code: String,     @SerialName("new_account_id") val newAccountId: String, ) -@Serializable-data class TransferInResponse(@SerialName("ok") val ok: Boolean = false)- @Serializable data class StripeKeyResponse(@SerialName("publishable_key") val publishableKey: String = "") @@ -112,19 +98,7 @@ data class NowPayInvoiceResponse(     @SerialName("invoice_id") val invoiceId: String = "",     /** Extra credit the 5% crypto bonus adds, in USD cents. */     @SerialName("bonus_usd_cents") val bonusUsdCents: Long = 0,-)--@Serializable-data class NowPayStatusRequest(-    @SerialName("account_id") val accountId: String,-    @SerialName("invoice_id") val invoiceId: String,-)--@Serializable-data class NowPayStatusResponse(@SerialName("status") val status: String = "waiting")--@Serializable-data class ErrorBody(-    @SerialName("error") val error: String = "",-    @SerialName("message") val message: String = "",+    @SerialName("amount_cents") val amountCents: Long = 0,+    /** True when the server returned the account's already-open checkout. */+    @SerialName("existing") val existing: Boolean = false, )
globalesim/src/main/java/com/vayunmathur/globalesim/domain/QuoteMath.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/domain/QuoteMath.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/domain/QuoteMath.ktindex 41953eb527..e1057a2c58 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/domain/QuoteMath.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/domain/QuoteMath.kt@@ -5,16 +5,26 @@ package com.vayunmathur.globalesim.domain  * no float money anywhere. The server is authoritative; this is display-only.  */ object QuoteMath {-    /** Rough USD headline: the cheapest rate rounds to ~$1/GB. */+    /** Payment bounds on both rails, mirroring the server (which enforces them). */+    const val PAYMENT_MIN_CENTS = 500L+    const val PAYMENT_MAX_CENTS = 2000L++    private val AMOUNT = Regex("""^\$?\s*(\d{1,6})(?:[.,](\d{1,2}))?$""")+     fun formatCents(cents: Long): String {         val dollars = cents / 100         val rem = (cents % 100).toString().padStart(2, '0')         return "$$dollars.$rem"     } -    /** Data MB a wallet balance buys at a per-GB price. Floor — never overpromise. */-    fun mbFor(pricePerGbCents: Long, walletCents: Long): Long {-        if (pricePerGbCents <= 0) return 0-        return walletCents * 1024 / pricePerGbCents+    /**+     * Parse a typed dollar amount to cents with integer math: "12", "12.5",+     * "$12.50" and the decimal-comma "12,50" all work. Null when unparseable.+     */+    fun parseAmountCents(text: String): Long? {+        val match = AMOUNT.matchEntire(text.trim()) ?: return null+        val dollars = match.groupValues[1].toLong()+        val cents = match.groupValues[2].padEnd(2, '0').toLong()+        return dollars * 100 + cents     } }
globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.ktindex bbdffb96d7..d0be0f05ee 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt@@ -10,24 +10,35 @@ import com.vayunmathur.globalesim.data.AnonymousIdStore import com.vayunmathur.globalesim.data.api.EsimApi import com.vayunmathur.globalesim.data.api.ProfileDto import com.vayunmathur.globalesim.data.api.RateDto+import com.vayunmathur.globalesim.data.api.StatusResponse import com.vayunmathur.globalesim.domain.upgradeCheckoutUrl-import com.vayunmathur.library.log.Log+import java.io.IOException import java.util.UUID+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Duration.Companion.seconds+import kotlin.time.TimeSource+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay import kotlinx.coroutines.launch  /** UI state for the single-eSIM storefront. */ data class EsimUiState(     val loading: Boolean = false,+    val statusLoaded: Boolean = false,+    val refreshing: Boolean = false,+    /** This install's account id, shown to the user as the "SIM ID". */+    val simId: String? = null,     val profile: ProfileDto? = null,     val rates: List<RateDto> = emptyList(),-    val transferCode: String? = null,     val pendingClientSecret: String? = null,-    val pendingAmountCents: Long = 0,-    /** Pending crypto invoice (url + id + bonus); cleared when paid/closed. */+    /** Pending crypto checkout; cleared once the credit lands or the user cancels. */     val pendingInvoiceUrl: String? = null,-    val pendingInvoiceId: String? = null,-    val pendingBonusCents: Long = 0,-    val error: String? = null,+    /** Paid but not yet in the wallet (eSIM being created, or funding retrying). */+    val pendingCreditCents: Long = 0,+    /** The balance shown is last-known; the server couldn't read it live. */+    val balanceStale: Boolean = false,+    /** One-shot snackbar text, consumed by the tab host. */+    val message: String? = null, )  class EsimViewModel(app: Application) : AndroidViewModel(app) {@@ -36,19 +47,15 @@ class EsimViewModel(app: Application) : AndroidViewModel(app) {     var state by mutableStateOf(EsimUiState())         private set -    /** True once an initial status load completed (success or fail). */-    private var statusAttempted = false+    private var creditWatch: Job? = null+    private var creditBaselineCents: Long = 0+    private var watchingCrypto = false      init {         viewModelScope.launch {-            // Mint the anonymous id only. Provisioning happens on explicit-            // user action (createEsim) — never on launch, since each-            // provision is a real $1.75 vendor charge. Rates are public;-            // status loads once to discover an existing eSIM, then only-            // refreshes when a profile is present (refreshAll guard).-            // TEMP-DEBUG: log the stored account id. Remove after diagnosis.-            val id = idStore.getOrCreate()-            Log.status("Esim", "stored account_id=$id")+            // Mint the anonymous id only. The server creates the eSIM itself+            // once the account's first payment lands.+            state = state.copy(simId = idStore.getOrCreate())             refreshRates()             refreshStatus()         }@@ -56,79 +63,126 @@ class EsimViewModel(app: Application) : AndroidViewModel(app) {      private suspend fun accountId(): String = idStore.getOrCreate() -    /**-     * Explicit user action: provision the account's one eSIM. Each call is-     * a real vendor charge, so the UI gates this behind a confirmation-     * button — it is NEVER called on launch. Idempotent server-side:-     * re-tapping an existing account returns its profile.-     */-    fun createEsim() {+    fun dismissMessage() {+        state = state.copy(message = null)+    }++    fun refreshStatus() {         viewModelScope.launch {-            state = state.copy(loading = true, error = null)-            runCatching { EsimApi.register(accountId()) }-                .onSuccess {-                    state = state.copy(profile = it.profile)-                    refreshAll()-                }-                .onFailure { state = state.copy(loading = false, error = it.message) }+            state = state.copy(loading = true)+            loadStatus()+            state = state.copy(loading = false)         }     } -    fun dismissError() {-        state = state.copy(error = null)+    /** Pull-to-refresh: reload status + balance without the full-card spinner. */+    fun refresh() {+        viewModelScope.launch {+            state = state.copy(refreshing = true)+            loadStatus()+            state = state.copy(refreshing = false)+        }     } -    fun refreshAll() {-        refreshRates()-        // No eSIM and no load attempted yet: status runs once via init.-        // After that, skip account calls until a profile exists.-        if (state.profile == null && statusAttempted) return-        refreshStatus()+    private suspend fun loadStatus() {+        runCatching { EsimApi.status(accountId()) }+            .onSuccess { if (applyStatus(it)) creditWatch?.cancel() }+            .onFailure { state = state.copy(message = friendly(it)) }+        state = state.copy(statusLoaded = true)     } -    fun refreshStatus() {-        viewModelScope.launch {-            state = state.copy(loading = true, error = null)-            runCatching { EsimApi.status(accountId()) }-                .onSuccess { state = state.copy(loading = false, profile = it.profile) }-                .onFailure {-                    // 404 = unknown account = no eSIM created yet. Normal-                    // state, not an error: show the welcome card, no snackbar.-                    if (it is EsimApi.ApiError && it.statusCode == 404) {-                        state = state.copy(loading = false, profile = null)-                    } else {-                        state = state.copy(loading = false, error = it.message)-                    }-                }-            statusAttempted = true+    /**+     * Apply a status read. The server owns the open crypto checkout and any+     * credit still on its way, so its view wins: this restores Reopen/Cancel+     * (and the watcher) after a restart. Returns true when an in-flight+     * payment watch has nothing left to wait for.+     */+    private suspend fun applyStatus(status: StatusResponse): Boolean {+        if (status.transferred) {+            onMovedAway()+            return true+        }+        val profile = status.profile+        val landed = profile != null && !status.balanceStale &&+            profile.walletUsdCents > creditBaselineCents+        val serverPending = status.pendingInvoiceUrl?.let(::upgradeCheckoutUrl)+        state = state.copy(+            profile = profile,+            pendingInvoiceUrl = serverPending,+            pendingCreditCents = status.pendingCreditCents,+            balanceStale = status.balanceStale,+        )+        val stillOwed = status.pendingCreditCents > 0+        if ((serverPending != null || stillOwed) && creditWatch?.isActive != true) {+            captureCreditBaseline()+            watchForCredit(crypto = serverPending != null)+        }+        return when {+            stillOwed -> false+            landed -> true+            // Checkout closed with nothing credited: failed, expired, or too small to count.+            watchingCrypto && serverPending == null -> true+            else -> false         }     } -    fun refreshRates() {-        viewModelScope.launch {-            runCatching { EsimApi.rates() }-                .onSuccess { state = state.copy(rates = it.rates) }-                .onFailure { state = state.copy(error = it.message) }-        }+    /** The eSIM was claimed onto another phone: start this install over fresh. */+    private suspend fun onMovedAway() {+        val fresh = UUID.randomUUID().toString()+        idStore.replace(fresh)+        state = state.copy(+            simId = fresh,+            profile = null,+            pendingInvoiceUrl = null,+            pendingCreditCents = 0,+            balanceStale = false,+            message = "This eSIM was moved to another phone.",+        )     } -    fun setEnabled(iccid: String, enabled: Boolean) {-        viewModelScope.launch {-            runCatching {-                if (enabled) EsimApi.enable(accountId(), iccid)-                else EsimApi.disable(accountId(), iccid)+    /**+     * Poll status until the payment shows up in the wallet. Both rails fund+     * the wallet from a server webhook, and NOWPayments can report `finished`+     * before that webhook lands, so the balance is the only reliable "paid"+     * signal. Lives in viewModelScope so polling continues while the user is+     * in the browser and the balance is current on return.+     */+    private fun watchForCredit(crypto: Boolean) {+        creditWatch?.cancel()+        watchingCrypto = crypto+        creditWatch = viewModelScope.launch {+            try {+                val started = TimeSource.Monotonic.markNow()+                while (true) {+                    if (started.elapsedNow() >= CREDIT_WATCH_TIMEOUT) {+                        state = state.copy(message = "Payment not detected yet. Pull down to check again later.")+                        break+                    }+                    delay(if (started.elapsedNow() < FAST_POLL_WINDOW) FAST_POLL else SLOW_POLL)+                    val status = runCatching { EsimApi.status(accountId()) }.getOrNull() ?: continue+                    // Data usage can drain the wallet mid-watch; track the low so a+                    // top-up still reads as a rise. Stale reads say nothing.+                    status.profile?.takeIf { !status.balanceStale }?.let {+                        creditBaselineCents = minOf(creditBaselineCents, it.walletUsdCents)+                    }+                    if (applyStatus(status)) break+                }+            } finally {+                // A replacement watch may already own the flag.+                if (creditWatch === coroutineContext[Job]) watchingCrypto = false             }-                .onSuccess { refreshStatus() }-                .onFailure { state = state.copy(error = it.message) }         }     } -    fun transferOut() {+    private fun captureCreditBaseline() {+        creditBaselineCents = state.profile?.walletUsdCents ?: 0+    }++    fun refreshRates() {         viewModelScope.launch {-            state = state.copy(loading = true, error = null, transferCode = null)-            runCatching { EsimApi.transferOut(accountId()) }-                .onSuccess { state = state.copy(loading = false, transferCode = it.transferCode) }-                .onFailure { state = state.copy(loading = false, error = it.message) }+            runCatching { EsimApi.rates() }+                .onSuccess { state = state.copy(rates = it.rates) }+                .onFailure { state = state.copy(message = friendly(it)) }         }     } @@ -136,47 +190,40 @@ class EsimViewModel(app: Application) : AndroidViewModel(app) {      * Start a card purchase: fetch the publishable key (once per process)      * and a PaymentIntent for [amountCents]. The screen presents the      * PaymentSheet with the resulting client secret; the server credits-     * the budget via the Stripe webhook, and [onSheetReady] fires so the-     * screen can present immediately.+     * the wallet via the Stripe webhook.      */-    fun startCardPurchase(amountCents: Long, publishableKey: String?, onKey: (String) -> Unit, onSheetReady: () -> Unit) {+    fun startCardPurchase(amountCents: Long, publishableKey: String?, onKey: (String) -> Unit) {         viewModelScope.launch {-            state = state.copy(loading = true, error = null, pendingClientSecret = null)+            state = state.copy(loading = true, pendingClientSecret = null)+            captureCreditBaseline()             runCatching {                 val key = publishableKey ?: EsimApi.stripeKey().publishableKey-                val intent = EsimApi.stripeIntent(accountId(), amountCents)-                Triple(key, intent.clientSecret, amountCents)+                key to EsimApi.stripeIntent(accountId(), amountCents).clientSecret             }-                .onSuccess { (key, secret, amount) ->+                .onSuccess { (key, secret) ->                     onKey(key)-                    state = state.copy(-                        loading = false,-                        pendingClientSecret = secret,-                        pendingAmountCents = amount,-                    )-                    onSheetReady()+                    state = state.copy(loading = false, pendingClientSecret = secret)                 }-                .onFailure { state = state.copy(loading = false, error = it.message) }+                .onFailure { state = state.copy(loading = false, message = paymentError(it)) }         }     } -    /** Clear the pending sheet secret after it completes or is cancelled. */-    fun clearPendingPurchase() {-        state = state.copy(pendingClientSecret = null, pendingAmountCents = 0, loading = false)+    /** Clear the pending sheet secret; on success, watch for the webhook credit. */+    fun finishCardPurchase(paid: Boolean) {+        state = state.copy(pendingClientSecret = null, loading = false)+        if (paid) watchForCredit(crypto = false)     }      /**      * Start a crypto purchase: create a NOWPayments invoice for [amountCents]      * face value. The screen opens the hosted checkout URL; the server-     * credits the budget + 5% bonus via the IPN webhook. [onInvoiceReady]-     * fires with the checkout URL to open.+     * credits the wallet + 5% bonus via the IPN webhook. The server allows+     * one open checkout per account and hands back that one if it exists.      */     fun startCryptoPurchase(amountCents: Long, onInvoiceReady: (String) -> Unit) {         viewModelScope.launch {-            state = state.copy(-                loading = true, error = null,-                pendingInvoiceUrl = null, pendingInvoiceId = null, pendingBonusCents = 0,-            )+            state = state.copy(loading = true)+            captureCreditBaseline()             runCatching { EsimApi.nowPayInvoice(accountId(), amountCents) }                 .onSuccess {                     // NOWPayments sometimes returns a cleartext http link,@@ -186,59 +233,77 @@ class EsimViewModel(app: Application) : AndroidViewModel(app) {                     state = state.copy(                         loading = false,                         pendingInvoiceUrl = secureUrl,-                        pendingInvoiceId = it.invoiceId,-                        pendingBonusCents = it.bonusUsdCents,-                        pendingAmountCents = amountCents,+                        message = if (it.existing) "Reopened your open crypto checkout." else null,                     )+                    watchForCredit(crypto = true)                     onInvoiceReady(secureUrl)                 }-                .onFailure { state = state.copy(loading = false, error = it.message) }-        }-    }--    /** Poll the invoice status after the user returns from checkout. */-    fun checkCryptoStatus(onResult: (String) -> Unit) {-        val invoiceId = state.pendingInvoiceId ?: return-        viewModelScope.launch {-            runCatching { EsimApi.nowPayStatus(accountId(), invoiceId) }-                .onSuccess {-                    if (it.status == "finished") {-                        state = state.copy(pendingInvoiceUrl = null, pendingInvoiceId = null)-                        refreshStatus()+                .onFailure {+                    val message = if (it is EsimApi.ApiError && it.statusCode == 409) {+                        "A crypto payment is already starting."+                    } else {+                        paymentError(it)                     }-                    onResult(it.status)+                    state = state.copy(loading = false, message = message)                 }-                .onFailure { state = state.copy(error = it.message) }         }     } -    /** Clear the pending crypto invoice (user closed checkout). */+    /** Cancel the open crypto checkout here and on the server, freeing the slot. */     fun clearPendingInvoice() {-        state = state.copy(-            pendingInvoiceUrl = null, pendingInvoiceId = null,-            pendingBonusCents = 0, pendingAmountCents = 0, loading = false,-        )+        creditWatch?.cancel()+        state = state.copy(pendingInvoiceUrl = null, loading = false)+        viewModelScope.launch {+            runCatching { EsimApi.nowPayCancel(accountId()) }+                .onFailure { state = state.copy(message = friendly(it)) }+        }     } -    fun transferIn(oldAccountId: String, code: String, onDone: () -> Unit) {+    /** Move the eSIM whose SIM ID was copied from another phone onto this one. */+    fun claim(simId: String) {         viewModelScope.launch {-            state = state.copy(loading = true, error = null)-            val fresh = UUID.randomUUID().toString()-            runCatching { EsimApi.transferIn(oldAccountId, code.trim(), fresh) }+            state = state.copy(loading = true)+            runCatching { EsimApi.claim(simId.trim(), accountId()) }                 .onSuccess {-                    idStore.replace(fresh)-                    // Claimed account owns the moved eSIM — status/budget are-                    // valid now. Set a non-null profile first so refreshAll-                    // doesn't skip them, then overwrite with live data.+                    creditWatch?.cancel()                     state = state.copy(                         loading = false,-                        transferCode = null,-                        profile = state.profile ?: ProfileDto(iccid = "", status = "active"),+                        pendingInvoiceUrl = null,+                        pendingClientSecret = null,+                        message = "eSIM moved to this phone.",                     )-                    refreshAll()-                    onDone()+                    loadStatus()+                }+                .onFailure {+                    val message = when ((it as? EsimApi.ApiError)?.statusCode) {+                        400 -> "That doesn't look like a SIM ID."+                        404 -> "No eSIM found for that SIM ID."+                        409 -> "This phone already has an eSIM."+                        else -> friendly(it)+                    }+                    state = state.copy(loading = false, message = message)                 }-                .onFailure { state = state.copy(loading = false, error = it.message) }         }     }++    private fun paymentError(t: Throwable): String = when ((t as? EsimApi.ApiError)?.statusCode) {+        400 -> "Payments must be between $5 and $20."+        410 -> "This eSIM moved to another phone."+        else -> friendly(t)+    }++    private fun friendly(t: Throwable): String = when (val code = (t as? EsimApi.ApiError)?.statusCode) {+        null -> if (t is IOException) "No connection. Check your internet and try again." else "Something went wrong."+        429 -> "Too many requests. Try again in a minute."+        in 500..599 -> "Service unavailable. Try again shortly."+        else -> "Request failed ($code)."+    }++    private companion object {+        val FAST_POLL = 2.seconds+        val SLOW_POLL = 10.seconds+        val FAST_POLL_WINDOW = 2.minutes+        // Crypto settlement waits on block confirmations.+        val CREDIT_WATCH_TIMEOUT = 45.minutes+    } }
globalesim/src/main/java/com/vayunmathur/globalesim/ui/ClaimCard.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/ClaimCard.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/ClaimCard.ktnew file mode 100644index 0000000000..50ee071304--- /dev/null+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/ClaimCard.kt@@ -0,0 +1,42 @@+package com.vayunmathur.globalesim.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text++/** Claim an eSIM onto this phone with the SIM ID copied from the other phone. */+@Composable+fun ClaimCard(busy: Boolean, onClaim: (String) -> Unit, modifier: Modifier = Modifier) {+    var simId by rememberSaveable { mutableStateOf("") }+    Card(modifier.fillMaxWidth()) {+        Column(Modifier.padding(16.dp)) {+            Text("Already have an eSIM on another phone?", style = MaterialTheme.typography.bodyMedium)+            OutlinedTextField(+                value = simId,+                onValueChange = { simId = it },+                label = { Text("SIM ID") },+                singleLine = true,+                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+            )+            OutlinedButton(+                onClick = { onClaim(simId) },+                enabled = !busy && simId.isNotBlank(),+                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+            ) {+                Text("Claim on this phone")+            }+        }+    }+}
globalesim/src/main/java/com/vayunmathur/globalesim/ui/HomeScreen.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/HomeScreen.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/HomeScreen.ktindex f14283b89b..35e23fb47d 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/HomeScreen.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/HomeScreen.kt@@ -1,347 +1,254 @@ package com.vayunmathur.globalesim.ui +import android.annotation.SuppressLint+import android.content.ActivityNotFoundException+import android.content.ClipData+import android.content.ClipDescription+import android.content.ClipboardManager+import android.content.Context import android.content.Intent+import android.os.PersistableBundle import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.shape.RoundedCornerShape-import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp-import androidx.core.net.toUri import com.stripe.android.PaymentConfiguration import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.PaymentSheetResult import com.stripe.android.paymentsheet.rememberPaymentSheet+import com.vayunmathur.globalesim.data.api.ProfileDto import com.vayunmathur.globalesim.domain.QuoteMath import com.vayunmathur.globalesim.domain.buildActivationCode import com.vayunmathur.globalesim.platform.EsimUiState import com.vayunmathur.library.intents.euicc.EsimLink+import com.vayunmathur.library.ui.AppPullToRefreshBox import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.LoadingIndicator import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.OutlinedTextField-import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.rememberMessenger-import kotlin.math.roundToLong  /**- * Home: your global eSIM at a glance — status, wallet balance, one-tap- * top-up presets, and links to rates / install / budget / transfer.- * One eSIM per account: no country picking, no per-trip buying.+ * Purchase tab: your global eSIM at a glance — balance, top-up, install,+ * and Copy SIM ID for moving to another phone. Without an eSIM it shows+ * the setup terms, the first top-up, and Claim for an eSIM copied from+ * another phone. Pull down anywhere to refresh status and balance.  */ @Composable fun HomeScreen(     state: EsimUiState,-    onCreateEsim: () -> Unit,-    onStartCardPurchase: (amountCents: Long, publishableKey: String?, onKey: (String) -> Unit, onSheetReady: () -> Unit) -> Unit,-    onCardPurchaseDone: () -> Unit,+    onStartCardPurchase: (amountCents: Long, publishableKey: String?, onKey: (String) -> Unit) -> Unit,+    onCardPurchaseDone: (paid: Boolean) -> Unit,     onStartCryptoPurchase: (Long) -> Unit,-    onCheckCryptoStatus: () -> Unit,     onClearCryptoInvoice: () -> Unit,-    onOpenTransfer: () -> Unit,-    onDismissError: () -> Unit,+    onClaim: (simId: String) -> Unit,+    onRefresh: () -> Unit, ) {     val messenger = rememberMessenger()-    val error = state.error-    LaunchedEffect(error) {-        if (error != null) {-            messenger.show(error)-            onDismissError()-        }-    }     val context = LocalContext.current     var publishableKey by remember { mutableStateOf<String?>(null) }     var sheetError by remember { mutableStateOf<String?>(null) }+    LaunchedEffect(sheetError) {+        sheetError?.let {+            messenger.show(it)+            sheetError = null+        }+    }     val paymentSheet = rememberPaymentSheet { result ->         when (result) {             is PaymentSheetResult.Completed -> {                 messenger.show("Payment complete — credit lands shortly.")-                onCardPurchaseDone()-            }-            is PaymentSheetResult.Canceled -> {-                onCardPurchaseDone()+                onCardPurchaseDone(true)             }+            is PaymentSheetResult.Canceled -> onCardPurchaseDone(false)             is PaymentSheetResult.Failed -> {                 sheetError = result.error.localizedMessage ?: "Payment failed"-                onCardPurchaseDone()+                onCardPurchaseDone(false)             }         }     }-    sheetError?.let { messenger.show(it) }-    // Present the sheet when the client secret lands. The secret is cleared-    // on completion/cancel so a recomposition never re-presents.+    // Present each client secret once. Saved across recreation so a rotation+    // with the secret still pending doesn't present the sheet a second time.     val pendingSecret = state.pendingClientSecret+    var presentedSecret by rememberSaveable { mutableStateOf<String?>(null) }     LaunchedEffect(pendingSecret) {-        if (pendingSecret != null) {-            paymentSheet.presentWithPaymentIntent(-                pendingSecret,-                PaymentSheet.Configuration("Global eSIM"),-            )+        if (pendingSecret != null && pendingSecret != presentedSecret) {+            presentedSecret = pendingSecret+            paymentSheet.presentWithPaymentIntent(pendingSecret, PaymentSheet.Configuration("Global eSIM"))         }     }     AppScaffold(         title = "Purchase",         scrollBehavior = appBarScrollBehavior(),     ) { padding ->-        Column(-            Modifier.padding(padding).padding(16.dp).verticalScroll(rememberScrollState()),+        AppPullToRefreshBox(+            isRefreshing = state.refreshing,+            onRefresh = onRefresh,+            modifier = Modifier.fillMaxSize(),+            topClearance = padding.calculateTopPadding(),         ) {-            val profile = state.profile-            Card(Modifier.fillMaxWidth()) {-                Column(Modifier.padding(16.dp)) {-                    if (state.loading && profile == null) {-                        LoadingIndicator()-                    } else if (profile == null) {-                        Text("One global eSIM for 200+ countries")-                        Text(-                            "Pay as you go, credit never expires",-                            modifier = Modifier.padding(top = 4.dp),-                        )-                        Text(-                            "No email or phone number or KYC required",-                            modifier = Modifier.padding(top = 4.dp),-                        )-                        Text(-                            "Set up your eSIM now",-                            modifier = Modifier.padding(top = 4.dp),-                        )-                        Button(-                            onClick = onCreateEsim,-                            enabled = !state.loading,-                            modifier = Modifier.fillMaxWidth().padding(top = 12.dp),-                        ) {-                            Text("Create my eSIM")+            Column(+                Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(padding).padding(16.dp),+            ) {+                val profile = state.profile+                Card(Modifier.fillMaxWidth()) {+                    Column(Modifier.padding(16.dp)) {+                        when {+                            !state.statusLoaded -> LoadingIndicator()+                            profile == null && state.pendingCreditCents > 0 -> {+                                Text("Payment received", style = MaterialTheme.typography.titleMedium)+                                Text(+                                    "Creating your eSIM. This page updates on its own.",+                                    modifier = Modifier.padding(top = 4.dp),+                                )+                            }+                            profile == null -> SetupTerms()+                            else -> BalanceSummary(profile, state.balanceStale, state.pendingCreditCents)                         }-                    } else {-                        Text("Status: ${profile.status}")-                        Text(-                            "Balance: ${QuoteMath.formatCents(profile.walletUsdCents)}",-                            modifier = Modifier.padding(top = 4.dp),-                        )                     }                 }-            }-            if (profile != null) {-                TopUpCard(-                    loading = state.loading,-                    onBuyWithCard = { cents ->-                        onStartCardPurchase(-                            cents,-                            publishableKey,-                            { key ->+                if (state.statusLoaded) {+                    TopUpCard(+                        busy = state.loading || state.pendingClientSecret != null,+                        onBuyWithCard = { cents ->+                            onStartCardPurchase(cents, publishableKey) { key ->                                 publishableKey = key                                 PaymentConfiguration.init(context, key)-                            },-                            {},-                        )-                    },-                    onBuyWithCrypto = { cents -> onStartCryptoPurchase(cents) },-                    pendingInvoiceUrl = state.pendingInvoiceUrl,-                    pendingBonusCents = state.pendingBonusCents,-                    onCheckCryptoStatus = onCheckCryptoStatus,-                    onClearCryptoInvoice = onClearCryptoInvoice,-                    modifier = Modifier.padding(top = 12.dp),-                )-                OutlinedButton(-                    onClick = {-                        // The vendor stores SM-DP+ and matching ID separately;-                        // the LPA needs the full LPA:1$<smdp>$<code> string.-                        // A bare matching ID fails validation and lands on a-                        // blank manual-entry page. The server sometimes fuses-                        // smdp+code with the `$` missing, so normalize first.-                        val full = buildActivationCode(profile.activationCode, profile.smdpAddress)-                        // TEMP-DEBUG: part counts only, never the code itself.-                        com.vayunmathur.library.log.Log.status(-                            "Esim",-                            "install len=${full.length} parts=${full.split('$').size} " +-                                "smdpLen=${profile.smdpAddress.length} codeLen=${profile.activationCode.length}",-                        )-                        val intent = Intent(-                            Intent.ACTION_VIEW,-                            EsimLink.provisioningUri(full),-                        ).setPackage(EsimLink.LPA_PACKAGE)-                        context.startActivity(intent)-                    },-                    modifier = Modifier.fillMaxWidth().padding(top = 12.dp),-                ) {-                    Text("Install / reinstall eSIM")-                }-                OutlinedButton(-                    onClick = onOpenTransfer,-                    modifier = Modifier.fillMaxWidth().padding(top = 8.dp),-                ) {-                    Text("Move to new phone")+                            }+                        },+                        onBuyWithCrypto = onStartCryptoPurchase,+                        pendingInvoiceUrl = state.pendingInvoiceUrl,+                        onClearCryptoInvoice = onClearCryptoInvoice,+                        modifier = Modifier.padding(top = 12.dp),+                    )                 }-            }-        }-    }-}--/**- * Custom-amount top-up. The user types any dollar amount; two side-by-side- * buttons pay by card ($5 min) or crypto ($2 min, +5% bonus), both capped- * at $20. Payment funds the eSIM wallet directly — there is no manual- * move step and no separate credit pool.- */-@Composable-private fun TopUpCard(-    loading: Boolean,-    onBuyWithCard: (Long) -> Unit,-    onBuyWithCrypto: (Long) -> Unit,-    pendingInvoiceUrl: String?,-    pendingBonusCents: Long,-    onCheckCryptoStatus: () -> Unit,-    onClearCryptoInvoice: () -> Unit,-    modifier: Modifier = Modifier,-) {-    val context = LocalContext.current-    val messenger = rememberMessenger()-    var amountText by remember { mutableStateOf("") }-    // Parse "$12.34" / "12.34" to integer cents; null while invalid.-    val amountCents: Long? = remember(amountText) {-        val cleaned = amountText.trim().removePrefix("$")-        if (cleaned.isEmpty()) null-        else cleaned.toDoubleOrNull()?.let { (it * 100).roundToLong() }?.takeIf { it > 0 }-    }-    val cardOk = amountCents != null && amountCents in 500..2000-    val cryptoOk = amountCents != null && amountCents in 200..2000-    // Inline validation: only when the field is non-empty and parses.-    // Card floor is $5, but the message is rail-agnostic per spec —-    // the card button simply stays disabled below $5.-    val rangeError: String? = when {-        amountText.isBlank() || amountCents == null -> null-        amountCents < 200 -> "Minimum $2 payment."-        amountCents > 2000 -> "$20 max payment."-        else -> null-    }-    // Live bonus preview: 5% of the entered amount.-    val bonusPreview: Long? = amountCents?.let { (it * 105) / 100 - it }?.takeIf { cryptoOk }-    Card(modifier.fillMaxWidth()) {-        Column(Modifier.padding(16.dp)) {-            Text("Top up")-            OutlinedTextField(-                value = amountText,-                onValueChange = { amountText = it },-                label = { Text("Amount (USD)") },-                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),-                singleLine = true,-                isError = rangeError != null,-                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),-            )-            if (rangeError != null) {-                Text(-                    rangeError,-                    color = MaterialTheme.colorScheme.error,-                    style = MaterialTheme.typography.bodySmall,-                    modifier = Modifier.padding(top = 4.dp),-                )-            }-            if (bonusPreview != null && bonusPreview > 0) {-                Text(-                    "Crypto bonus: +${QuoteMath.formatCents(bonusPreview)} extra.",-                    modifier = Modifier.padding(top = 4.dp),-                )-            }-            Row(-                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),-                horizontalArrangement = Arrangement.spacedBy(8.dp),-            ) {-                Button(-                    onClick = { onBuyWithCard(amountCents!!) },-                    enabled = !loading && cardOk,-                    modifier = Modifier.weight(1f),-                ) {-                    Text("Card topup")+                if (state.statusLoaded && profile == null && state.pendingCreditCents == 0L) {+                    ClaimCard(+                        busy = state.loading,+                        onClaim = onClaim,+                        modifier = Modifier.padding(top = 12.dp),+                    )                 }-                BadgedBox(badge = "+5%", modifier = Modifier.weight(1f)) {-                    Button(-                        onClick = { onBuyWithCrypto(amountCents!!) },-                        enabled = !loading && cryptoOk,-                        modifier = Modifier.fillMaxWidth(),+                if (profile != null) {+                    Row(+                        modifier = Modifier.fillMaxWidth().padding(top = 12.dp),+                        horizontalArrangement = Arrangement.spacedBy(8.dp),                     ) {-                        Text("Crypto topup")+                        OutlinedButton(+                            onClick = {+                                // The vendor stores SM-DP+ and matching ID separately;+                                // the LPA needs the full LPA:1$<smdp>$<code> string.+                                // A bare matching ID fails validation and lands on a+                                // blank manual-entry page. The server sometimes fuses+                                // smdp+code with the `$` missing, so normalize first.+                                val full = buildActivationCode(profile.activationCode, profile.smdpAddress)+                                val intent = Intent(Intent.ACTION_VIEW, EsimLink.provisioningUri(full))+                                    .setPackage(EsimLink.LPA_PACKAGE)+                                try {+                                    context.startActivity(intent)+                                } catch (_: ActivityNotFoundException) {+                                    messenger.show("This phone doesn't have the eSIM installer.")+                                }+                            },+                            modifier = Modifier.weight(1f),+                        ) {+                            Text("Install eSIM")+                        }+                        OutlinedButton(+                            onClick = {+                                state.simId?.let {+                                    copySimId(context, it)+                                    messenger.show("SIM ID copied. Paste it into Claim on your new phone.")+                                }+                            },+                            enabled = state.simId != null,+                            modifier = Modifier.weight(1f),+                        ) {+                            Text("Copy SIM ID")+                        }                     }                 }             }-            if (pendingInvoiceUrl != null) {-                Text(-                    "Checkout open in your browser. Come back here when you've paid.",-                    modifier = Modifier.padding(top = 8.dp),-                )-                if (pendingBonusCents > 0) {-                    Text(-                        "Bonus on this payment: +${QuoteMath.formatCents(pendingBonusCents)}.",-                        modifier = Modifier.padding(top = 4.dp),-                    )-                }-                Button(-                    onClick = {-                        context.startActivity(Intent(Intent.ACTION_VIEW, pendingInvoiceUrl.toUri()))-                    },-                    modifier = Modifier.fillMaxWidth().padding(top = 8.dp),-                ) {-                    Text("Reopen checkout")-                }-                OutlinedButton(-                    onClick = {-                        onCheckCryptoStatus()-                        messenger.show("Checking payment…")-                    },-                    modifier = Modifier.fillMaxWidth().padding(top = 8.dp),-                ) {-                    Text("I've paid — check status")-                }-                OutlinedButton(-                    onClick = onClearCryptoInvoice,-                    modifier = Modifier.fillMaxWidth().padding(top = 8.dp),-                ) {-                    Text("Cancel crypto payment")-                }-            }         }     } } -/** Small pill badge overlapped on the top-end corner of [content]. */+/** Setup terms for a phone with no eSIM yet. The $3 fee gets its own line. */ @Composable-private fun BadgedBox(-    badge: String,-    modifier: Modifier = Modifier,-    content: @Composable () -> Unit,-) {-    Box(modifier) {-        content()-        Surface(-            shape = RoundedCornerShape(8.dp),-            color = MaterialTheme.colorScheme.tertiaryContainer,-            modifier = Modifier.align(Alignment.TopEnd).offset(x = 4.dp, y = (-8).dp),-        ) {-            Text(-                badge,-                style = MaterialTheme.typography.labelSmall,-                modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),-            )+private fun SetupTerms() {+    Text("One global eSIM for 200+ countries", style = MaterialTheme.typography.titleMedium)+    Text(+        "Pay as you go, credit never expires. No email, phone number or KYC.",+        modifier = Modifier.padding(top = 4.dp),+    )+    Text(+        "$3 one-time setup fee",+        style = MaterialTheme.typography.titleSmall,+        color = MaterialTheme.colorScheme.primary,+        modifier = Modifier.padding(top = 12.dp),+    )+    Text(+        "Taken from your first top-up ($5 minimum). A $5 top-up leaves $2 of credit.",+        style = MaterialTheme.typography.bodyMedium,+        modifier = Modifier.padding(top = 2.dp),+    )+}++@Composable+private fun BalanceSummary(profile: ProfileDto, stale: Boolean, pendingCreditCents: Long) {+    // A stale read with no history is a placeholder zero, not a real balance.+    val unknown = stale && profile.status == "unknown" && profile.walletUsdCents == 0L+    Text(+        if (unknown) "—" else QuoteMath.formatCents(profile.walletUsdCents),+        style = MaterialTheme.typography.headlineMedium,+    )+    Text(+        "Balance · ${statusLabel(profile.status)}" + if (stale && !unknown) " · last known" else "",+        style = MaterialTheme.typography.bodyMedium,+    )+    if (pendingCreditCents > 0) {+        Text(+            "${QuoteMath.formatCents(pendingCreditCents)} on its way. No need to pay again.",+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.primary,+            modifier = Modifier.padding(top = 4.dp),+        )+    }+}++private fun statusLabel(status: String): String = when (status) {+    "pending" -> "Activating"+    "active" -> "Active"+    "suspended" -> "Paused"+    "terminated" -> "Terminated"+    "unknown" -> "Checking…"+    else -> status.replaceFirstChar { it.uppercase() }+}++/** The SIM ID is the account's only credential: flag the clip as sensitive so it isn't previewed. */+@SuppressLint("InlinedApi") // Before Android 13 the extra is ignored; the copy still works.+private fun copySimId(context: Context, simId: String) {+    val clip = ClipData.newPlainText("SIM ID", simId).apply {+        description.extras = PersistableBundle().apply {+            putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true)         }     }+    context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(clip) }
globalesim/src/main/java/com/vayunmathur/globalesim/ui/PricingScreen.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/PricingScreen.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/PricingScreen.ktindex b93af0f581..41686618f1 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/PricingScreen.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/PricingScreen.kt@@ -1,6 +1,5 @@ package com.vayunmathur.globalesim.ui -import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues@@ -10,11 +9,11 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color@@ -29,15 +28,14 @@ import com.vayunmathur.library.ui.IconSim import com.vayunmathur.library.ui.LazyListScaffold import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.ListItemDefaults-import com.vayunmathur.library.ui.LoadingIndicator import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.ui.animatedColor import com.vayunmathur.library.ui.animatedDp import com.vayunmathur.library.ui.appBarScrollBehavior-import com.vayunmathur.library.ui.rememberMessenger  /**  * Pricing: searchable per-country rate list with the search field in the@@ -49,17 +47,9 @@ import com.vayunmathur.library.ui.rememberMessenger @Composable fun PricingScreen(     state: EsimUiState,-    onDismissError: () -> Unit,+    onRefresh: () -> Unit, ) {-    val messenger = rememberMessenger()-    val error = state.error-    LaunchedEffect(error) {-        if (error != null) {-            messenger.show(error)-            onDismissError()-        }-    }-    var query by remember { mutableStateOf("") }+    var query by rememberSaveable { mutableStateOf("") }     val expanded = remember { mutableStateListOf<String>() }     val filtered = remember(state.rates, query) {         if (query.isBlank()) state.rates@@ -88,13 +78,17 @@ fun PricingScreen(     ) {         if (filtered.isEmpty()) {             item(key = "pricing-empty") {-                if (state.loading) {-                    LoadingIndicator(Modifier.padding(16.dp))+                if (query.isBlank()) {+                    EmptyState(+                        title = "No rates yet",+                        message = "Rates couldn't be loaded.",+                        icon = { IconSim() },+                        action = { OutlinedButton(onClick = onRefresh) { Text("Retry") } },+                    )                 } else {                     EmptyState(-                        title = if (query.isBlank()) "No rates yet" else "No matches",-                        message = if (query.isBlank()) "Pull down or reopen to refresh."-                        else "Try another country name or code.",+                        title = "No matches",+                        message = "Try another country name or code.",                         icon = { IconSim() },                     )                 }@@ -158,7 +152,6 @@ fun PricingScreen(                                     } else {                                         rate.networks.forEach { net ->                                             ListItem(-                                                modifier = Modifier.clickable {},                                                 content = { Text(net.operator) },                                                 supportingContent = {                                                     Text(QuoteMath.formatCents(net.pricePerGbUsdCents) + " / GB")
globalesim/src/main/java/com/vayunmathur/globalesim/ui/TopUpCard.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/TopUpCard.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/TopUpCard.ktnew file mode 100644index 0000000000..b5033ae040--- /dev/null+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/TopUpCard.kt@@ -0,0 +1,146 @@+package com.vayunmathur.globalesim.ui++import android.content.Intent+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.unit.dp+import androidx.core.net.toUri+import com.vayunmathur.globalesim.domain.QuoteMath+import com.vayunmathur.globalesim.domain.QuoteMath.PAYMENT_MAX_CENTS+import com.vayunmathur.globalesim.domain.QuoteMath.PAYMENT_MIN_CENTS+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text++/**+ * Custom-amount top-up: any dollar amount from $5 to $20, paid by card or+ * crypto (+5% bonus). Payment funds the eSIM wallet directly; the ViewModel+ * watches the balance, so there is no manual "I've paid" step.+ */+@Composable+fun TopUpCard(+    busy: Boolean,+    onBuyWithCard: (Long) -> Unit,+    onBuyWithCrypto: (Long) -> Unit,+    pendingInvoiceUrl: String?,+    onClearCryptoInvoice: () -> Unit,+    modifier: Modifier = Modifier,+) {+    val context = LocalContext.current+    var amountText by rememberSaveable { mutableStateOf("") }+    val amountCents = remember(amountText) { QuoteMath.parseAmountCents(amountText) }+    val amountOk = amountCents != null && amountCents in PAYMENT_MIN_CENTS..PAYMENT_MAX_CENTS+    val inputError: String? = when {+        amountText.isBlank() -> null+        amountCents == null -> "Enter an amount like 10 or 12.50."+        amountCents < PAYMENT_MIN_CENTS -> "Minimum ${QuoteMath.formatCents(PAYMENT_MIN_CENTS)} payment."+        amountCents > PAYMENT_MAX_CENTS -> "${QuoteMath.formatCents(PAYMENT_MAX_CENTS)} max payment."+        else -> null+    }+    Card(modifier.fillMaxWidth()) {+        Column(Modifier.padding(16.dp)) {+            OutlinedTextField(+                value = amountText,+                onValueChange = { amountText = it },+                label = { Text("Top up amount (USD)") },+                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),+                singleLine = true,+                isError = inputError != null,+                modifier = Modifier.fillMaxWidth(),+            )+            if (inputError != null) {+                Text(+                    inputError,+                    color = MaterialTheme.colorScheme.error,+                    style = MaterialTheme.typography.bodySmall,+                    modifier = Modifier.padding(top = 4.dp),+                )+            }+            Row(+                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+                horizontalArrangement = Arrangement.spacedBy(8.dp),+            ) {+                Button(+                    onClick = { amountCents?.let(onBuyWithCard) },+                    enabled = !busy && amountOk,+                    modifier = Modifier.weight(1f),+                ) {+                    Text("Card topup")+                }+                BadgedBox(badge = "+5%", modifier = Modifier.weight(1f)) {+                    Button(+                        onClick = { amountCents?.let(onBuyWithCrypto) },+                        enabled = !busy && amountOk && pendingInvoiceUrl == null,+                        modifier = Modifier.fillMaxWidth(),+                    ) {+                        Text("Crypto topup")+                    }+                }+            }+            if (pendingInvoiceUrl != null) {+                Row(+                    modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+                    horizontalArrangement = Arrangement.spacedBy(8.dp),+                ) {+                    OutlinedButton(+                        onClick = {+                            context.startActivity(Intent(Intent.ACTION_VIEW, pendingInvoiceUrl.toUri()))+                        },+                        modifier = Modifier.weight(1f),+                    ) {+                        Text("Reopen checkout")+                    }+                    OutlinedButton(+                        onClick = onClearCryptoInvoice,+                        modifier = Modifier.weight(1f),+                    ) {+                        Text("Cancel")+                    }+                }+            }+        }+    }+}++/** Small pill badge overlapped on the top-end corner of [content]. */+@Composable+private fun BadgedBox(+    badge: String,+    modifier: Modifier = Modifier,+    content: @Composable () -> Unit,+) {+    Box(modifier) {+        content()+        Surface(+            shape = MaterialTheme.shapes.small,+            color = MaterialTheme.colorScheme.tertiaryContainer,+            modifier = Modifier.align(Alignment.TopEnd).offset(x = 4.dp, y = (-8).dp),+        ) {+            Text(+                badge,+                style = MaterialTheme.typography.labelSmall,+                modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),+            )+        }+    }+}
globalesim/src/main/java/com/vayunmathur/globalesim/ui/TransferScreen.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/TransferScreen.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/ui/TransferScreen.ktdeleted file mode 100644index fdab18793a..0000000000--- a/globalesim/src/main/java/com/vayunmathur/globalesim/ui/TransferScreen.kt+++ /dev/null@@ -1,98 +0,0 @@-package com.vayunmathur.globalesim.ui--import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScroll-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dp-import com.vayunmathur.globalesim.platform.EsimUiState-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.LoadingIndicator-import com.vayunmathur.library.ui.OutlinedTextField-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.appBarScrollBehavior-import com.vayunmathur.library.ui.rememberMessenger--/**- * Device transfer: show a one-time code on the old phone, enter old id +- * code on the new phone. The server moves the eSIM + credit and rotates- * the code — codes are single-use.- */-@Composable-fun TransferScreen(-    state: EsimUiState,-    onTransferOut: () -> Unit,-    onTransferIn: (oldAccountId: String, code: String) -> Unit,-    onNavigateBack: () -> Unit,-) {-    val messenger = rememberMessenger()-    val error = state.error-    // Shown once per failure, not on every recomposition.-    LaunchedEffect(error) {-        if (error != null) messenger.show(error)-    }-    var oldId by remember { mutableStateOf("") }-    var code by remember { mutableStateOf("") }-    AppScaffold(-        title = "Move to new phone",-        scrollBehavior = appBarScrollBehavior(),-        onNavigateBack = onNavigateBack,-    ) { padding ->-        Column(-            Modifier.padding(padding).padding(16.dp).verticalScroll(rememberScrollState()),-        ) {-            Card(Modifier.fillMaxWidth()) {-                Column(Modifier.padding(16.dp)) {-                    Text("On this (old) phone")-                    val shown = state.transferCode-                    if (shown != null) {-                        Text("Your code: $shown", modifier = Modifier.padding(top = 8.dp))-                        Text("Enter it on the new phone. Single use.")-                    } else {-                        Button(-                            onClick = onTransferOut,-                            enabled = !state.loading,-                            modifier = Modifier.fillMaxWidth().padding(top = 8.dp),-                        ) {-                            if (state.loading) LoadingIndicator() else Text("Show transfer code")-                        }-                    }-                }-            }-            Card(Modifier.fillMaxWidth().padding(top = 12.dp)) {-                Column(Modifier.padding(16.dp)) {-                    Text("On the new phone")-                    OutlinedTextField(-                        value = oldId,-                        onValueChange = { oldId = it },-                        label = { Text("Old account id") },-                        modifier = Modifier.fillMaxWidth().padding(top = 8.dp),-                    )-                    OutlinedTextField(-                        value = code,-                        onValueChange = { code = it },-                        label = { Text("Transfer code") },-                        modifier = Modifier.fillMaxWidth().padding(top = 8.dp),-                    )-                    Button(-                        onClick = { onTransferIn(oldId, code) },-                        enabled = !state.loading && oldId.isNotBlank() && code.isNotBlank(),-                        modifier = Modifier.fillMaxWidth().padding(top = 12.dp),-                    ) {-                        Text("Claim eSIM on this phone")-                    }-                }-            }-        }-    }-}
globalesim/src/screenshotTest/kotlin/com/vayunmathur/globalesim/ui/MetadataPreviews.kt
diff --git a/globalesim/src/screenshotTest/kotlin/com/vayunmathur/globalesim/ui/MetadataPreviews.kt b/globalesim/src/screenshotTest/kotlin/com/vayunmathur/globalesim/ui/MetadataPreviews.ktindex 8563cdd345..915a1f0bf6 100644--- a/globalesim/src/screenshotTest/kotlin/com/vayunmathur/globalesim/ui/MetadataPreviews.kt+++ b/globalesim/src/screenshotTest/kotlin/com/vayunmathur/globalesim/ui/MetadataPreviews.kt@@ -52,15 +52,13 @@ class MetadataPreviews {     fun Preview1Purchase() {         DynamicTheme(darkTheme = true) {             HomeScreen(-                state = EsimUiState(profile = demoProfile),-                onCreateEsim = {},-                onStartCardPurchase = { _, _, _, _ -> },+                state = EsimUiState(statusLoaded = true, simId = "demo", profile = demoProfile),+                onStartCardPurchase = { _, _, _ -> },                 onCardPurchaseDone = {},                 onStartCryptoPurchase = {},-                onCheckCryptoStatus = {},                 onClearCryptoInvoice = {},-                onOpenTransfer = {},-                onDismissError = {},+                onClaim = {},+                onRefresh = {},             )         }     }@@ -72,7 +70,7 @@ class MetadataPreviews {         DynamicTheme(darkTheme = true) {             PricingScreen(                 state = EsimUiState(rates = demoRates),-                onDismissError = {},+                onRefresh = {},             )         }     }
globalesim/src/test/java/com/vayunmathur/globalesim/domain/QuoteMathTest.kt
diff --git a/globalesim/src/test/java/com/vayunmathur/globalesim/domain/QuoteMathTest.kt b/globalesim/src/test/java/com/vayunmathur/globalesim/domain/QuoteMathTest.ktindex 433ea3b75f..f4091f592f 100644--- a/globalesim/src/test/java/com/vayunmathur/globalesim/domain/QuoteMathTest.kt+++ b/globalesim/src/test/java/com/vayunmathur/globalesim/domain/QuoteMathTest.kt@@ -2,6 +2,7 @@ package com.vayunmathur.globalesim.domain  import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertNull  class QuoteMathTest {     @Test@@ -13,11 +14,15 @@ class QuoteMathTest {     }      @Test-    fun mbForFloorsNeverOverpromises() {-        // $1 wallet at $1.38/GB ≈ 742 MB, floored.-        assertEquals(742L, QuoteMath.mbFor(138, 100))-        assertEquals(1024L, QuoteMath.mbFor(100, 100))-        assertEquals(0L, QuoteMath.mbFor(0, 100))-        assertEquals(0L, QuoteMath.mbFor(138, 0))+    fun parsesAmountsIncludingDecimalComma() {+        assertEquals(1200L, QuoteMath.parseAmountCents("12"))+        assertEquals(1250L, QuoteMath.parseAmountCents("12.5"))+        assertEquals(1250L, QuoteMath.parseAmountCents("$12.50"))+        assertEquals(1234L, QuoteMath.parseAmountCents("12,34"))+        assertEquals(500L, QuoteMath.parseAmountCents(" 5 "))+        assertNull(QuoteMath.parseAmountCents("12.345"))+        assertNull(QuoteMath.parseAmountCents("abc"))+        assertNull(QuoteMath.parseAmountCents(""))+        assertNull(QuoteMath.parseAmountCents("1e3"))     } }
metadata_data/globalesim.md
diff --git a/metadata_data/globalesim.md b/metadata_data/globalesim.mdindex abd91ba630..ed09e6b217 100644--- a/metadata_data/globalesim.md+++ b/metadata_data/globalesim.md@@ -3,10 +3,11 @@ Global data eSIM, pay as you go, unexpiring, no KYC, ~$1/GB US, ~€0.6/GB EU Features: - One global eSIM that works in 200+ countries - Pay as you go: top up credit, data deducts at the local per-GB rate-- Credit never expires and works everywhere you travel+- Credit never expires - Anonymous account - no email or phone number needed-- Move your eSIM to a new phone with a transfer code-- Install with one tap via the on-device eSIM manager-- Top up by card or crypto - crypto payments get 5% extra credit free+- Transferable to a new phone all within the app+- Install with one tap+- $3 one-time setup fee, taken from your first top-up ($5 minimum)+- Pay with card or crypto - crypto payments get 5% extra credit free  Internet only used for: browsing rates, topping up and managing your eSIM