diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 47e49828e2..6b6930e6ba 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -186,6 +186,12 @@ class CacheStore internal constructor( store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends - hash) } } + suspend fun addMoveToSparkHash(paymentHash: String) { + val hash = paymentHash.lowercase() + if (hash in store.data.first().moveToSparkHashes) return + store.updateData { it.copy(moveToSparkHashes = it.moveToSparkHashes + hash) } + } + /** Keeps [paymentHash] with its invoice's expiry in epoch seconds, [expiresAt], when known. */ suspend fun addLdkSendHash(paymentHash: String, expiresAt: Long? = null) { val hash = paymentHash.lowercase() @@ -369,6 +375,11 @@ data class AppCacheData( * never reads a retry's earlier failed attempt as its outcome. */ val sparkUncertainSends: Map = mapOf(), + /** + * Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and + * Activity shows the move as one. + */ + val moveToSparkHashes: List = listOf(), /** Hashes of the Lightning sends the node started, so Spark holds off while the node can't list them. */ val ldkSendHashes: List = listOf(), /** Invoice expiry in epoch seconds of the [ldkSendHashes] that know it. */ diff --git a/app/src/main/java/to/bitkit/ext/Activities.kt b/app/src/main/java/to/bitkit/ext/Activities.kt index ba9c832c42..fc2d68971e 100644 --- a/app/src/main/java/to/bitkit/ext/Activities.kt +++ b/app/src/main/java/to/bitkit/ext/Activities.kt @@ -76,6 +76,10 @@ fun Activity.matchesPaymentId(paymentHashOrTxId: String): Boolean = when (this) fun Activity.isTransfer() = this is Activity.Onchain && this.v1.isTransfer +/** Whether this is the channel send of a move to Spark, one of [moveHashes], which Activity shows as a move. */ +fun Activity.isMoveToSpark(moveHashes: Set) = this is Activity.Lightning && + v1.txType == PaymentType.SENT && v1.id.lowercase() in moveHashes + fun Activity.doesExist() = this is Activity.Onchain && this.v1.doesExist fun Activity.isReplacedSentTransaction(txIdsInBoostTxIds: Set): Boolean = diff --git a/app/src/main/java/to/bitkit/models/BackupPayloads.kt b/app/src/main/java/to/bitkit/models/BackupPayloads.kt index ef9d2d903c..f47b49e10c 100644 --- a/app/src/main/java/to/bitkit/models/BackupPayloads.kt +++ b/app/src/main/java/to/bitkit/models/BackupPayloads.kt @@ -7,8 +7,18 @@ import com.synonym.bitkitcore.IBtInfo import com.synonym.bitkitcore.IBtOrder import com.synonym.bitkitcore.IcJitEntry import com.synonym.bitkitcore.PreActivityMetadata +import kotlinx.serialization.EncodeDefault +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonDecoder +import kotlinx.serialization.json.JsonPrimitive import to.bitkit.data.AppCacheData import to.bitkit.data.SettingsData import to.bitkit.data.WatchOnlyAccountAllocationState @@ -44,8 +54,31 @@ data class MetadataBackupV1( * `sparkExitNextFundingIndexes`. Null in envelopes written before this field. */ val sparkExitEarlierAddresses: Map>? = null, + /** + * The payment hashes of moves to Spark, lowercase hex and sorted, which Activity shows as moves. Null in envelopes + * written before this field or with none; a value that is not a list of strings reads as none. + */ + @OptIn(ExperimentalSerializationApi::class) + @EncodeDefault(EncodeDefault.Mode.NEVER) + @Serializable(with = LenientStringListSerializer::class) + val moveToSparkPaymentHashes: List? = null, ) +/** Reads a list of strings, or an empty list for any other value, so one unreadable field keeps the rest. */ +internal object LenientStringListSerializer : KSerializer> { + private val delegate = ListSerializer(String.serializer()) + override val descriptor = delegate.descriptor + + override fun serialize(encoder: Encoder, value: List) = delegate.serialize(encoder, value) + + override fun deserialize(decoder: Decoder): List { + val element = (decoder as? JsonDecoder)?.decodeJsonElement() ?: return delegate.deserialize(decoder) + val items = (element as? JsonArray)?.map { it as? JsonPrimitive } ?: return emptyList() + if (items.any { it == null || !it.isString }) return emptyList() + return items.map { requireNotNull(it).content } + } +} + /** * An earlier Spark exit address as both apps back it up. [kind] is `keptChange` or `cancelledFunding`; a reader skips * one it does not know. What the address holds is read again from the chain. diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index b7e4faf5ac..0011f3ce73 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -87,6 +87,7 @@ import to.bitkit.models.toLdkNetwork import to.bitkit.services.CoreService import to.bitkit.services.LightningService import to.bitkit.services.PaykitSdkService +import to.bitkit.services.SparkError import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError import to.bitkit.utils.Logger @@ -716,11 +717,15 @@ class BackupRepo @Inject constructor( * read, so a failed or skipped restore never loses the stored exit data. */ private suspend fun uploadSparkExitBackup(): Result = runSuspendCatching { + val staged = sparkRepo.importStagedExitState() + if (staged is StagedExitImport.Rejected) { + setAsideRejectedExitBackup(rejectedStagedExitCopy(staged)) + sparkRepo.discardStagedExitState(staged.exitState) + } + // Dropping a rejected staged copy asks for the stored backup to be merged again, until a merge succeeds. if (!sparkRepo.hasMergedRemoteExitState) { sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() - val remote = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value - ?.let { json.decodeFromString(String(it)) } - sparkRepo.mergeRemoteExitBackup(remote).getOrThrow() + mergeStoredExitBackup() } val backup = sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() vssBackupClient.putObject( @@ -729,6 +734,56 @@ class BackupRepo @Inject constructor( ).getOrThrow() } + /** + * Merges the stored exit backup into Spark. One Spark can't import is set aside, and replaced only when it is still + * the stored one after that, so exit data another device stored meanwhile is merged first. + */ + private suspend fun mergeStoredExitBackup() { + var stored = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value + repeat(EXIT_MERGE_ATTEMPTS) { + val remote = stored?.let { bytes -> + runCatching { json.decodeFromString(String(bytes)) }.getOrNull() + } + val merged = if (stored != null && remote == null) { + Result.failure(SparkError.ExitStateUnimportable()) + } else { + sparkRepo.mergeRemoteExitBackup(remote) + } + val error = merged.exceptionOrNull() ?: return + val unimportable = stored + if (error !is SparkError.ExitStateUnimportable || unimportable == null) throw error + setAsideRejectedExitBackup(unimportable) + val current = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value + if (current.contentEquals(unimportable)) { + sparkRepo.skipUnimportableRemoteExitState(remote?.exitState) + return + } + stored = current + } + throw SparkExitBackupChanged() + } + + private suspend fun rejectedStagedExitCopy(staged: StagedExitImport.Rejected): ByteArray { + val stored = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value + val remote = stored?.let { bytes -> + runCatching { json.decodeFromString(String(bytes)) }.getOrNull() + } + if (stored != null && remote?.exitState == staged.exitState) return stored + val copy = SparkExitBackupV1( + createdAt = currentTimeMillis(), + network = remote?.network ?: staged.network, + exitState = staged.exitState, + ) + return json.encodeToString(copy).toByteArray() + } + + private suspend fun setAsideRejectedExitBackup(data: ByteArray) { + val key = rejectedExitKey(data) + if (vssBackupClient.getObject(key).getOrThrow() != null) return + vssBackupClient.putObject(key = key, data = data).getOrThrow() + Logger.warn("Set Spark exit data Spark can't import aside as '$key'", context = TAG) + } + suspend fun persistWalletBackup(): Result = withContext(ioDispatcher) { walletBackupMutex.withLock { uploadWalletBackup() } @@ -921,6 +976,8 @@ class BackupRepo @Inject constructor( pubkyContactProfileOverrides = pubkyContactProfileOverrides, hwWalletNames = hwWalletNames, sparkExitEarlierAddresses = sparkExitEarlierAddressesBackup(), + moveToSparkPaymentHashes = cacheData.moveToSparkHashes.map { it.lowercase() }.distinct().sorted() + .takeIf { it.isNotEmpty() }, ) json.encodeToString(payload).toByteArray() @@ -1131,7 +1188,13 @@ class BackupRepo @Inject constructor( connectionSession.replay() // Before the slower categories, so the exit data is staged before Spark connects and syncs. performRestore(BackupCategory.SPARK_EXIT, failedCategories) { dataBytes -> - val parsed = json.decodeFromString(String(dataBytes)) + val parsed = runCatching { json.decodeFromString(String(dataBytes)) } + .getOrElse { + // A layout this app can't read never becomes readable here, so it is kept for one that can, + // and the restore reports the exit data as not restored, its backup status untouched. + if (it is IllegalArgumentException) setAsideRejectedExitBackup(dataBytes) + throw it + } sparkRepo.restoreExitBackup(parsed, backupWalletIndex()).getOrThrow() parsed.createdAt } @@ -1265,11 +1328,20 @@ class BackupRepo @Inject constructor( // The exit then looks once for funding addresses that still hold coins and nothing watches: each one // below the index, and those a scan forward from it finds used, which also moves the index past them. sparkExitFundingRecoveryPending = it.sparkExitFundingRecoveryPending + restoredIndexKeys, + // Both apps back the moves up beside the cache; the device's own stay. + moveToSparkHashes = ( + it.moveToSparkHashes + cleanCache.moveToSparkHashes + parsed.moveToSparkPaymentHashes.orEmpty() + ).map { hash -> hash.lowercase() }.distinct(), ) } runCatching { restoreSparkExitEarlierAddresses(parsed.sparkExitEarlierAddresses) } .onFailure { Logger.warn("Failed to restore the earlier Spark exit addresses", it, context = TAG) } - Logger.debug("Restored caches: ${jsonLogOf(parsed.cache.copy(cachedRates = emptyList()))}", TAG) + // Payment history stays out of the log, as support requests attach it. + val logged = parsed.cache.copy( + cachedRates = emptyList(), + moveToSparkHashes = emptyList(), + ) + Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) onCacheRestored() val persisted = preActivityMetadataRepo.upsertPreActivityMetadata(parsed.tagMetadata) .onFailure { Logger.warn("Failed to restore pre-activity metadata", it, context = TAG) } @@ -1555,9 +1627,25 @@ class BackupRepo @Inject constructor( private const val MINUTE_IN_MS = 60_000 private const val BACKUP_DEBOUNCE = 5000L // 5 seconds + /** + * The remote key of exit data Spark can never import, shared with bitkit-ios. A later, different copy goes + * under this key plus `_` and the first 16 hex digits of its SHA-256; an existing copy is never replaced. + */ + internal const val SPARK_EXIT_REJECTED_KEY = "SPARK_EXIT_REJECTED" + private const val REJECTED_DIGEST_HEX_DIGITS = 16 + + /** Where exit data Spark can't import is kept: one key per copy, so none replaces another. */ + internal fun rejectedExitKey(data: ByteArray): String { + val digest = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) } + return SPARK_EXIT_REJECTED_KEY + "_" + digest.take(REJECTED_DIGEST_HEX_DIGITS) + } + /** Spark's exit data can reach several MB and changes with every payment, so its uploads are spaced out. */ private const val SPARK_EXIT_BACKUP_DEBOUNCE = 60_000L + /** How many times the exit backup merges stored data another device replaced meanwhile before it gives up. */ + private const val EXIT_MERGE_ATTEMPTS = 3 + /** Maximum captures before deferring a changing wallet to the next scheduled backup. */ private const val WALLET_SNAPSHOT_ATTEMPTS = 3 @@ -1588,6 +1676,8 @@ internal class WalletBackupSnapshotChanged : AppError("Private payment state cha internal class SparkExitBackupDeferred : AppError("Spark has not connected and synced yet") +internal class SparkExitBackupChanged : AppError("Stored Spark exit backup kept changing while it was merged") + private class PublicAddressRestoreFailed(cause: Throwable) : AppError( "Failed to retain public address exclusion during restore", cause, diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index e46b0f3da3..35566bcecf 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -8,6 +8,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import org.lightningdevkit.ldknode.Bolt11Invoice @@ -16,6 +17,7 @@ import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.NodeException import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentStatus +import to.bitkit.data.CacheStore import to.bitkit.di.BgDispatcher import to.bitkit.ext.runSuspendCatching import to.bitkit.ext.totalNextOutboundHtlcLimitSats @@ -29,16 +31,19 @@ import java.util.concurrent.atomic.AtomicReference import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds /** * Moves the balance of the user's Lightning channels to their own Spark wallet, paying a Spark invoice over the * channels only. Blocktank is closing its channels, and this is the cheapest way to keep the balance in Spending. */ @Singleton -class MoveToSparkRepo @Inject constructor( - @BgDispatcher private val bgDispatcher: CoroutineDispatcher, +class MoveToSparkRepo internal constructor( + private val bgDispatcher: CoroutineDispatcher, private val lightningRepo: LightningRepo, private val sparkRepo: SparkRepo, + private val cacheStore: CacheStore, + private val paymentHashOf: (bolt11: String) -> String, ) { companion object { private const val TAG = "MoveToSparkRepo" @@ -49,17 +54,31 @@ class MoveToSparkRepo @Inject constructor( /** How long the move waits for the payment to settle before it reports it as still in flight. */ private val PAYMENT_TIMEOUT = 2.minutes + /** How often a move waiting past its timeout reads the node's stored payment again, as the node may be down. */ + private val STORED_PAYMENT_RECHECK = 30.seconds + /** The failures that mean no route carried the amount, so a smaller one may route. */ private val NO_ROUTE_REASONS = setOf(PaymentFailureReason.ROUTE_NOT_FOUND, PaymentFailureReason.RETRIES_EXHAUSTED) } - private val ownPaymentHashes = ConcurrentHashMap.newKeySet() + @Inject + constructor( + @BgDispatcher bgDispatcher: CoroutineDispatcher, + lightningRepo: LightningRepo, + sparkRepo: SparkRepo, + cacheStore: CacheStore, + ) : this(bgDispatcher, lightningRepo, sparkRepo, cacheStore, { Bolt11Invoice.fromStr(it).paymentHash() }) + private val watchedPaymentHashes = ConcurrentHashMap.newKeySet() private val reportedPaymentHashes = ConcurrentHashMap.newKeySet() - /** Whether [paymentHash] is a move to Spark, whose send and receive the app does not announce as payments. */ - fun isMovePayment(paymentHash: String): Boolean = paymentHash in ownPaymentHashes + /** + * Whether [paymentHash] is a move to Spark, whose send and receive the app does not announce as payments; also one + * from before a restart. + */ + suspend fun isMovePayment(paymentHash: String): Boolean = + paymentHash.lowercase() in cacheStore.data.first().moveToSparkHashes /** * Whether the move screen waits on [paymentHash] or already reported its outcome, so the app raises no failure @@ -68,6 +87,9 @@ class MoveToSparkRepo @Inject constructor( fun isWatchedMovePayment(paymentHash: String): Boolean = paymentHash in watchedPaymentHashes || paymentHash in reportedPaymentHashes + /** The payment hashes of the moves to Spark, so Activity shows each as a move rather than a payment. */ + val moveHashes: Flow> = cacheStore.data.map { it.moveToSparkHashes.toSet() }.distinctUntilChanged() + /** Whether the channels hold a balance worth moving to a usable Spark wallet. */ val canMove: Flow = combine(lightningRepo.lightningState, sparkRepo.state) { lightning, spark -> MoveToSparkMath.canMove(lightning.channels, spark) @@ -116,8 +138,8 @@ class MoveToSparkRepo @Inject constructor( /** Pays [quote] over the channels and waits for it to settle in Spark. */ suspend fun move(quote: MoveToSparkQuote): Result = withContext(bgDispatcher) { runSuspendCatching { - val paymentHash = Bolt11Invoice.fromStr(quote.invoice).paymentHash() - ownPaymentHashes += paymentHash + val paymentHash = paymentHashOf(quote.invoice) + cacheStore.addMoveToSparkHash(paymentHash) watchedPaymentHashes += paymentHash try { payAndWait(quote, paymentHash) @@ -171,7 +193,8 @@ class MoveToSparkRepo @Inject constructor( /** * Waits for the payment of a move still [inFlight] to settle after the move stopped waiting. It listens first, then - * reads the node's stored payment, so an outcome that arrived after the move stopped listening is not missed. + * reads the node's stored payment, so an outcome that arrived after the move stopped listening is not missed, and + * reads it again while it waits, as the node may be down for a read. */ suspend fun awaitSettled(inFlight: MoveToSparkOutcome.InFlight): Result = withContext(bgDispatcher) { @@ -180,21 +203,21 @@ class MoveToSparkRepo @Inject constructor( val settled = async(start = CoroutineStart.UNDISPATCHED) { lightningRepo.nodeEvents.first { it.settles(inFlight.paymentHash, inFlight.paymentId) } } - val stored = lightningRepo.listPaymentsOrNull()?.firstOrNull { it.id == inFlight.paymentId } - when (stored?.status) { - PaymentStatus.SUCCEEDED -> { - settled.cancel() - MoveToSparkOutcome.Moved(inFlight.amountSats, (stored.feePaidMsat ?: 0uL) / 1000uL) - } - PaymentStatus.FAILED -> { - settled.cancel() - throw MoveToSparkError.PaymentFailed(null) - } - else -> when (val event = settled.await()) { - is Event.PaymentSuccessful -> event.moved(inFlight.amountSats) - else -> throw MoveToSparkError.PaymentFailed((event as? Event.PaymentFailed)?.reason) + var moved: MoveToSparkOutcome.Moved? = null + while (moved == null) { + val stored = lightningRepo.listPaymentsOrNull()?.firstOrNull { it.id == inFlight.paymentId } + moved = when (stored?.status) { + PaymentStatus.SUCCEEDED -> + MoveToSparkOutcome.Moved(inFlight.amountSats, (stored.feePaidMsat ?: 0uL) / 1000uL) + PaymentStatus.FAILED -> throw MoveToSparkError.PaymentFailed(null) + else -> withTimeoutOrNull(STORED_PAYMENT_RECHECK) { settled.await() }?.let { + (it as? Event.PaymentSuccessful)?.moved(inFlight.amountSats) + ?: throw MoveToSparkError.PaymentFailed((it as? Event.PaymentFailed)?.reason) + } } } + settled.cancel() + moved } }.onFailure { Logger.warn("Failed to move '${inFlight.amountSats}' sats to Spark after the wait", it, context = TAG) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index 44bedac639..b8fe69b490 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -1486,8 +1486,8 @@ class PaykitPaymentProofRepo @Inject constructor( when (payment.status) { PaymentStatus.PENDING -> Unit // A Spark retry of an invoice the node failed shares its hash and decides the payment. - PaymentStatus.FAILED -> when (lightningRepo.sparkLightningSend(paymentHash)) { - is SparkLightningSend.Found -> reconcileSparkLightningProof(proof, paymentHash) + PaymentStatus.FAILED -> when (val send = lightningRepo.sparkLightningSend(paymentHash)) { + is SparkLightningSend.Found -> reconcileSparkLightningProof(proof, paymentHash, send) SparkLightningSend.Unavailable -> Unit SparkLightningSend.NotFound -> removeLightningProofsLocked(paymentHash) } @@ -1499,8 +1499,12 @@ class PaykitPaymentProofRepo @Inject constructor( } } - private suspend fun reconcileSparkLightningProof(proof: PendingPaykitPaymentProof, paymentHash: String) { - val send = lightningRepo.sparkLightningSend(paymentHash) as? SparkLightningSend.Found ?: return + private suspend fun reconcileSparkLightningProof( + proof: PendingPaykitPaymentProof, + paymentHash: String, + read: SparkLightningSend.Found? = null, + ) { + val send = read ?: lightningRepo.sparkLightningSend(paymentHash) as? SparkLightningSend.Found ?: return when (send.status) { SparkPaymentStatus.PENDING -> Unit SparkPaymentStatus.FAILED -> removeLightningProofsLocked(paymentHash) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 14d8a12bf9..9733315ad4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -24,8 +24,10 @@ import com.synonym.bitkitcore.ServiceRouteLeg import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -34,6 +36,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.onSubscription import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex @@ -121,6 +124,12 @@ class SparkRepo @Inject constructor( /** Tries to learn the outcome of a send whose result was lost while Spark cannot list its payments. */ private const val SETTLE_ATTEMPTS = 10 + /** + * How far before a send's start Spark may date its own failure, as Spark's clock can differ from the phone's. + * Shared with bitkit-ios. + */ + private const val OWN_FAILURE_CLOCK_MARGIN_SECS = 10uL + /** How long a journaled withdrawal Spark doesn't list stays open before a sync closes it as never sent. */ private val UNLISTED_WITHDRAWAL_GRACE = 10.minutes @@ -169,12 +178,19 @@ class SparkRepo @Inject constructor( private val unsavedPayments = ConcurrentHashMap.newKeySet() private val isCollectingEvents = AtomicBoolean(false) + private val eventsSubscribed = CompletableDeferred() private val refreshMutex = Mutex() /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ private val sendsInFlight = ConcurrentHashMap() + /** The latest failure Spark dated for each send seen this process, by payment hash, in epoch seconds. */ + private val sendFailedAt = ConcurrentHashMap() + + /** Spark payment ids of the sends whose outcome was reported, so the poll and Spark's event report it once. */ + private val reportedSendIds = ConcurrentHashMap.newKeySet() + /** Counts sends recorded, so a listing drops a failed hash only when it was recorded before the listing. */ private val sendRecords = AtomicLong() private val sendRecordedAt = ConcurrentHashMap() @@ -182,6 +198,12 @@ class SparkRepo @Inject constructor( /** Sends whose outcome Spark didn't report, by payment hash. */ private val uncertainSends = ConcurrentHashMap() + /** Serialises the imports of staged exit data, so a restore and Spark's start never import it at once. */ + private val exitImportMutex = Mutex() + + /** Held while saved holds are taken back and while a send leaves flight, so neither reads the other halfway. */ + private val holdRestoreMutex = Mutex() + @Volatile private var hasSyncedActivities = false @@ -258,9 +280,7 @@ class SparkRepo @Inject constructor( // A retry reads as connecting until it fails again. _state.update { it.copy(hasStartFailed = false) } runSuspendCatching { - if (isCollectingEvents.compareAndSet(false, true)) { - scope.launch { sparkService.events.collect { onSdkEvent(it) } } - } + collectEvents() restoreUncertainSends() val isExiting = exitStore(walletIndex).isActive() _state.update { it.copy(isExiting = isExiting) } @@ -306,6 +326,7 @@ class SparkRepo @Inject constructor( unsavedPayments.clear() sendsInFlight.clear() uncertainSends.clear() + sendFailedAt.clear() hasSyncedActivities = false hasMergedRemoteExitState = false isLostForExit = false @@ -509,9 +530,10 @@ class SparkRepo @Inject constructor( /** * Pays [bolt11] and returns its payment hash, the id ldk-node payments use, so the send flow can match it. * Fails with [SparkError.SendRefused] when nothing left the wallet: Spark was not connected, could not prepare the - * payment, or its fee was over [maxTotalFeeMsat]; with [SparkError.InvoiceExpired], a [SparkError.SendRefused], - * when Spark refuses an expired invoice at prepare or send; and with [ServiceError.PaymentDeadlineExpired] past - * [paymentDeadlineAt]. A failure inside the send is a [PaymentPendingException], as the payment may have been + * payment or list its payments, or its fee was over [maxTotalFeeMsat]; with [SparkError.InvoiceExpired], a + * [SparkError.SendRefused], when Spark refuses an expired invoice at prepare or send; and with + * [ServiceError.PaymentDeadlineExpired] past [paymentDeadlineAt]. A failure inside the send is a + * [PaymentPendingException], as the payment may have been * dispatched, and its event decides it. An invoice this wallet already sends is not sent again: one in flight or * pending fails with [PaymentPendingException], and one Spark completed returns its hash. After a restore, a * still-valid invoice created before it that the Spark operators can't show unsent fails with @@ -550,60 +572,76 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found if earlier.status == PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) // Spark's list, synced or unreadable, can lack a send it made before the restore, as on the node's - // path, so the operators decide. + // path, so the operators decide. Before Spark syncs, its list can't date an earlier attempt they show + // failed, which a send must start past, so that one is refused too. else -> refuseUnverifiedRestoredInvoice( bolt11, invoice.timestamp.toEpochSeconds(), expiresAt.toEpochSeconds(), + isFailedUnsent = canListPayments(), ) } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() - if (sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) != null) { - throw PaymentPendingException(paymentHash) + val isEntered = holdRestoreMutex.withLock { + sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) == null } - val sent = try { - sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() - cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) - spending { - // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) - // The checks above and both writes suspend, so the deadline and an exit that started meanwhile - // are checked last, before the send. - runCatching { - ensurePaymentDeadline(paymentDeadlineAt) - ensureNotExiting() - }.onFailure { + if (!isEntered) throw PaymentPendingException(paymentHash) + // Kept in flight until its result is handled, so a sync meanwhile never takes back its saved hold. + try { + val startedAt = sendStartedAt(paymentHash) + val sent = run { + sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() + cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) + spending { + // Kept until the call returns, so a send cut off by process death or cancellation stays held. + cacheStore.addSparkUncertainSend(paymentHash, startedAt) + // The checks above and both writes suspend, so the deadline and an exit that started meanwhile + // are checked last, before the send. + runCatching { + ensurePaymentDeadline(paymentDeadlineAt) + ensureNotExiting() + }.onFailure { + cacheStore.removeSparkUncertainSend(paymentHash) + cacheStore.removeSparkSendHash(paymentHash) + throw it + } + runSuspendCatching { sparkService.send(prepared) } + } + } + sent.onSuccess { noteFailure(it) } + val payment = sent.getOrElse { + // The SDK checks the expiry again before anything goes out, so an expired invoice left nothing. + if (it.isInvoiceExpired()) { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) - throw it + throw SparkError.InvoiceExpired(it) } - runSuspendCatching { sparkService.send(prepared) } + // Spark selects the leaves to spend before anything goes to the operators, so a short balance left + // nothing, for instance when an earlier send spent it after the balance was read. + if (it is SdkException.InsufficientFunds) { + cacheStore.removeSparkUncertainSend(paymentHash) + cacheStore.removeSparkSendHash(paymentHash) + throw SparkError.SendRefused("Spark balance can't cover the payment", it) + } + Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) + settleUncertainSend(paymentHash, expiresAt) + throw PaymentPendingException(paymentHash) } - } finally { - sendsInFlight.remove(paymentHash.lowercase()) - } - val payment = sent.getOrElse { - // The SDK checks the expiry again before anything goes out, so an expired invoice left nothing. - if (it.isInvoiceExpired()) { + // A send Spark took stays held until Spark settles it or its invoice expires, as Spark's list may not + // show it yet. + if (payment.status == PaymentStatus.PENDING) { + settleUncertainSend(paymentHash, expiresAt) + } else { cacheStore.removeSparkUncertainSend(paymentHash) - cacheStore.removeSparkSendHash(paymentHash) - throw SparkError.InvoiceExpired(it) } - // Spark selects the leaves to spend before anything goes to the operators, so a short balance left - // nothing, for instance when an earlier send spent it after the balance was read. - if (it is SdkException.InsufficientFunds) { - cacheStore.removeSparkUncertainSend(paymentHash) - cacheStore.removeSparkSendHash(paymentHash) - throw SparkError.SendRefused("Spark balance can't cover the payment", it) + Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) + paymentHash + } finally { + withContext(NonCancellable) { + holdRestoreMutex.withLock { sendsInFlight.remove(paymentHash.lowercase()) } } - Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) - settleUncertainSend(paymentHash, expiresAt) - throw PaymentPendingException(paymentHash) } - cacheStore.removeSparkUncertainSend(paymentHash) - Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) - paymentHash }.onFailure { if (it is PaymentAbortedBeforeSend) { Logger.debug("Aborted Spark invoice pay before send", context = TAG) @@ -615,8 +653,10 @@ class SparkRepo @Inject constructor( private suspend fun settleUncertainSend(paymentHash: String, expiresAt: ULong) { val failedAt = clock.now().epochSeconds - uncertainSends[paymentHash.lowercase()] = UncertainSend(failedAt.toULong(), expiresAt) - cacheStore.addSparkUncertainSend(paymentHash, failedAt) + // The time kept before the send went out stays its start, which tells its own failure from earlier ones. + val startedAt = cacheStore.data.first().sparkUncertainSends[paymentHash.lowercase()] ?: failedAt + uncertainSends[paymentHash.lowercase()] = UncertainSend(startedAt.toULong(), failedAt.toULong(), expiresAt) + cacheStore.addSparkUncertainSend(paymentHash, startedAt) scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { @@ -633,51 +673,107 @@ class SparkRepo @Inject constructor( } } - /** Settles an uncertain send once Spark shows its outcome; true once it is settled, also by another caller. */ - private suspend fun trySettleUncertainSend(paymentHash: String): Boolean { + /** + * Settles an uncertain send once Spark shows its outcome; true once it is settled, also by another caller. A + * failure event for it [isFailureEvent] shows Spark reached the send, as a sync since would. A [listing] just + * read from Spark is used instead of reading it again, and then only for the hold [held] taken before it was read. + */ + private suspend fun trySettleUncertainSend( + paymentHash: String, + isFailureEvent: Boolean = false, + listing: List? = null, + held: UncertainSend? = null, + ): Boolean { val key = paymentHash.lowercase() val uncertain = uncertainSends[key] ?: return true + if (held != null && uncertain !== held) return false // Spark finishes an interrupted send only on a later sync, and a sync that never reached it still returns. val isSynced = hasSyncedSince(uncertain.failedAt) if (isSynced) _state.update { it.copy(hasSynced = true) } // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark // can still fail to resume it, so only an expired invoice shows a missing send will never go out. - val isFinal = isSynced && clock.now().epochSeconds.toULong() >= uncertain.expiresAt - val send = listedLightningSend(paymentHash) + val isFinal = (isSynced || isFailureEvent) && clock.now().epochSeconds.toULong() >= uncertain.expiresAt + val send = listedLightningSend(paymentHash, listing) val isSettled = when (send) { SparkLightningSend.NotFound -> isFinal - // A failed row may be an earlier attempt's, so it is final only when a missing one would be. - is SparkLightningSend.Found -> send.status != PaymentStatus.FAILED || isFinal + // A failure dated before the send started is an earlier attempt's, so it is final only when a missing + // send would be. + is SparkLightningSend.Found if send.status == PaymentStatus.COMPLETED -> true + // A pending send ends with its own payment event, or at its invoice's expiry. + is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> isFinal + is SparkLightningSend.Found -> isFinal || hasOwnFailure(paymentHash, listing) SparkLightningSend.Unavailable -> false } // Only the caller that takes the hash off settles it, so its outcome is reported once. - if (!isSettled || !uncertainSends.remove(key, uncertain)) return isSettled - cacheStore.removeSparkUncertainSend(paymentHash) + if (!isSettled) return false + if (!takeUncertainSend(paymentHash, uncertain, send)) return true when (send) { SparkLightningSend.NotFound -> { - cacheStore.removeSparkSendHash(paymentHash) - _nodeEvents.emit(Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR)) + // A retry that entered Spark's send call since the hold was taken reports its own outcome. + if (!sendsInFlight.containsKey(key)) { + _nodeEvents.emit( + Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR) + ) + } } - // A pending send ends with its own payment event. + // Spark still runs a pending send past its invoice's expiry, so its own payment event reports it. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> Unit is SparkLightningSend.Found -> { - if (send.status == PaymentStatus.FAILED) cacheStore.removeSparkSendHash(paymentHash) - settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } + val listed = (listing ?: runSuspendCatching { listPayments() }.getOrNull()) + ?.latestSend(paymentHash) + val isOwn = listed != null && + listed.timestamp.safe() + OWN_FAILURE_CLOCK_MARGIN_SECS.safe() >= uncertain.startedAt + if (send.status == PaymentStatus.FAILED) { + // Its row stayed pending while held, so it takes the failure now. + listed?.let { recordActivity(it) } + } + when { + listed == null -> settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } + // A retry started after the hold was taken reads as pending, and its own event reports it. + listed.status == PaymentStatus.PENDING -> Unit + // A retry that entered Spark's send call since the hold was taken reports its own outcome. + listed.status == PaymentStatus.FAILED && isHeldFrom(listed) -> Unit + // The send's own outcome is claimed, so Spark's event for the same payment reports nothing more. + isOwn -> if (reportedSendIds.add(listed.id)) listed.toNodeEvent()?.let { _nodeEvents.emit(it) } + // An earlier attempt's failure ends the send at its expiry, so it claims no payment. + else -> listed.toNodeEvent()?.let { _nodeEvents.emit(it) } + } } SparkLightningSend.Unavailable -> Unit } return true } + private suspend fun takeUncertainSend( + paymentHash: String, + uncertain: UncertainSend, + send: SparkLightningSend, + ): Boolean { + val key = paymentHash.lowercase() + val isFailed = send == SparkLightningSend.NotFound || + send is SparkLightningSend.Found && send.status == PaymentStatus.FAILED + // Both copies go under the restore lock, so a sync never takes back a hold settled here. A send enters Spark's + // send call under the same lock, so a retry's saved send is never dropped here. + return holdRestoreMutex.withLock { + uncertainSends.remove(key, uncertain).also { + if (!it) return@also + cacheStore.removeSparkUncertainSend(paymentHash) + if (isFailed && !sendsInFlight.containsKey(key)) cacheStore.removeSparkSendHash(paymentHash) + } + } + } + /** A send whose outcome Spark didn't report: when it failed, and when its invoice expires, in epoch seconds. */ - private data class UncertainSend(val failedAt: ULong, val expiresAt: ULong) + private data class UncertainSend(val startedAt: ULong, val failedAt: ULong, val expiresAt: ULong) /** Takes back the sends whose outcome Spark didn't report before a restart, so a sync can still settle them. */ - private suspend fun restoreUncertainSends() { + private suspend fun restoreUncertainSends() = holdRestoreMutex.withLock { val cache = cacheStore.data.first() cache.sparkUncertainSends.forEach { (hash, failedAt) -> + // A send still in Spark's send call is settled by its result. + if (sendsInFlight.containsKey(hash)) return@forEach val expiresAt = cache.sparkSendExpiries[hash]?.toULong() ?: ULong.MAX_VALUE - uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), expiresAt)) + uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), failedAt.toULong(), expiresAt)) } } @@ -745,6 +841,10 @@ class SparkRepo @Inject constructor( } claimJobs.remove(txid)?.cancel() setDepositClaim(txid, SparkDepositClaim.Later) + releaseEarlyClaimCap(txid) + } + + private fun releaseEarlyClaimCap(txid: String) { val vout = earlyClaimVouts.remove(txid) ?: return // Tried again while another claim of the deposit, such as Spark's own sync, leaves the cap in place. scope.launch { @@ -761,6 +861,10 @@ class SparkRepo @Inject constructor( private suspend fun claimInstantly(txid: String, ceilingSats: ULong) { var isSeen = false + // Once Spark waits for the early claim, the user's ceiling stays on the deposit as its cap and Spark claims it + // by itself when the provider offers it within the cap, so the poll only watches for the claim and asks the + // provider nothing more; an offer above the cap is never charged and the deposit is claimed at maturity. + var isWaiting = false repeat(CLAIM_POLL_ATTEMPTS) { runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark state", it, context = TAG) } @@ -768,7 +872,9 @@ class SparkRepo @Inject constructor( setDepositClaim(txid, SparkDepositClaim.Claimed) return } - if (_depositClaims.value[txid] != SparkDepositClaim.Adding) { + if (isWaiting && _depositClaims.value[txid] != SparkDepositClaim.Adding) { + if (isClaimStarted(txid)) setDepositClaim(txid, SparkDepositClaim.Adding) + } else if (_depositClaims.value[txid] != SparkDepositClaim.Adding) { val offer = depositClaimOffer(txid) .onFailure { Logger.warn("Failed to quote Spark deposit '$txid'", it, context = TAG) } .getOrNull() @@ -778,7 +884,9 @@ class SparkRepo @Inject constructor( SparkClaimStep.Adding -> SparkDepositClaim.Adding SparkClaimStep.Unavailable -> SparkDepositClaim.Unavailable is SparkClaimStep.Ask -> SparkDepositClaim.Repriced(step.offer) - is SparkClaimStep.ClaimEarly -> claimEarly(step.offer).getOrNull()?.toDepositClaim(step.offer) + is SparkClaimStep.ClaimEarly -> claimEarly(step.offer, ceilingSats).getOrNull() + ?.also { isWaiting = it == SparkEarlyClaim.Waiting } + ?.toDepositClaim(step.offer) } if (claim != null) setDepositClaim(txid, claim) if (claim?.isFinal == true) return @@ -787,6 +895,8 @@ class SparkRepo @Inject constructor( } if (_depositClaims.value[txid] == SparkDepositClaim.Adding) return Logger.warn("Stopped looking for the Instant claim of Spark deposit '$txid'", context = TAG) + // Shown at the normal speed from here, so Spark no longer claims it early within the user's ceiling. + releaseEarlyClaimCap(txid) setDepositClaim(txid, if (isSeen) SparkDepositClaim.Unavailable else SparkDepositClaim.NotSeen) } @@ -798,6 +908,11 @@ class SparkRepo @Inject constructor( _depositClaims.update { if (txid in it) it else it + (txid to SparkDepositClaim.Later) } } + /** Whether Spark no longer lists the deposit in [txid] as unclaimed, so its claim is under way. */ + private suspend fun isClaimStarted(txid: String): Boolean = runSuspendCatching { + sparkService.listUnclaimedDeposits().none { it.txid.equals(txid, ignoreCase = true) } + }.onFailure { Logger.warn("Failed to list unclaimed Spark deposits", it, context = TAG) }.getOrDefault(false) + private fun isClaimed(txid: String): Boolean = _state.value.deposits.any { it.isClaimed && it.txid.equals(txid, ignoreCase = true) } @@ -815,10 +930,16 @@ class SparkRepo @Inject constructor( } } - /** Accepts the early claim of [offer] at its quoted fee. */ - suspend fun claimEarly(offer: SparkClaimOffer.Choice): Result = withContext(bgDispatcher) { + /** + * Accepts the early claim of [offer] for at most [maxFeeSats], the fee the user accepted. Spark keeps it as the cap + * when it waits, so a later offer within it is claimed too. + */ + suspend fun claimEarly( + offer: SparkClaimOffer.Choice, + maxFeeSats: ULong = offer.earlyFeeSats, + ): Result = withContext(bgDispatcher) { earlyClaimVouts[offer.txid] = offer.vout - runSuspendCatching { sparkService.claimDeposit(offer.txid, offer.vout, offer.earlyFeeSats) } + runSuspendCatching { sparkService.claimDeposit(offer.txid, offer.vout, maxFeeSats) } .map { SparkEarlyClaim.from(it) } .recoverCatching { if (it is SdkException.DepositClaimInProgress) SparkEarlyClaim.Claimed else throw it } .onSuccess { @@ -931,7 +1052,7 @@ class SparkRepo @Inject constructor( * its own withdrawal apart, also while Spark's list lacks one after a restart. */ suspend fun withdrawalTxidsTo(address: String): Set = withContext(bgDispatcher) { - val listed = sparkService.listPayments().mapNotNull { payment -> + val listed = listPayments().mapNotNull { payment -> (payment.details as? PaymentDetails.Withdraw)?.takeIf { it.destinationAddress == address }?.txId } val recorded = cacheStore.data.first().sentSparkWithdrawals.filter { it.address == address }.map { it.txid } @@ -946,7 +1067,7 @@ class SparkRepo @Inject constructor( if (!isSent) return@withContext false if (cacheStore.data.first().sentSparkWithdrawals.any { it.txid == txid }) return@withContext true if (!_state.value.isReady) return@withContext false - runSuspendCatching { sparkService.listPayments() } + runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments for '$txid'", it, context = TAG) } .getOrDefault(emptyList()) .any { (it.details as? PaymentDetails.Withdraw)?.txId == txid } @@ -967,7 +1088,7 @@ class SparkRepo @Inject constructor( it.address == address && it.amountSats == amountSats && it.txid !in earlierTxids }?.let { return@withContext SparkWithdrawalOutcome.Sent(it.txid) } if (!_state.value.hasSynced || isWithdrawing) return@withContext SparkWithdrawalOutcome.Unknown - val attempts = sparkService.listPayments().filter { payment -> + val attempts = listPayments().filter { payment -> val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@filter false withdraw.destinationAddress == address && payment.amount.toLong().toULong() == amountSats && withdraw.txId !in earlierTxids @@ -1145,16 +1266,64 @@ class SparkRepo @Inject constructor( suspend fun mergeRemoteExitBackup(remote: SparkExitBackupV1?): Result = withContext(bgDispatcher) { runSuspendCatching { if (remote != null && remote.network == sparkService.networkName) { - val merged = sparkService.importExitState(remote.exitState) + val merged = runSuspendCatching { sparkService.importExitState(remote.exitState) }.getOrElse { + // Spark checks the version and parses the payload without the operators, so this one never passes. + throw if (it is SdkException.InvalidInput) SparkError.ExitStateUnimportable(it) else it + } Logger.info("Merged stored Spark exit data: '${merged.importedLeaves}' leaves", context = TAG) } hasMergedRemoteExitState = true } } + /** + * Stops merging stored exit data Spark can never import, which the caller kept apart, so the next upload replaces + * it. A staged restore is dropped only when it holds that same [exitState]; other staged data still imports. + */ + suspend fun skipUnimportableRemoteExitState(exitState: String?) { + if (exitState != null) deleteStagedExitState(exitState) + hasMergedRemoteExitState = true + } + + /** Tries the import of restored exit data again while connected, and says what became of it. */ + suspend fun importStagedExitState(): StagedExitImport = withContext(bgDispatcher) { + val file = File(Env.sparkExitRestorePath(walletIndex)) + if (!file.exists()) return@withContext StagedExitImport.NothingStaged + val network = sparkService.networkName + if (!sparkService.isConnected || network == null) return@withContext StagedExitImport.Pending + val staged = file.readText() + importRestoredExitState(walletIndex).fold( + onSuccess = { StagedExitImport.Imported }, + onFailure = { + if (it is SdkException.InvalidInput) { + StagedExitImport.Rejected(staged, network) + } else { + StagedExitImport.Pending + } + }, + ) + } + + /** + * Drops restored exit data Spark rejected, once the backup set a copy of it aside, unless newer data came. The + * stored backup is merged again before the next upload, as that copy may be older than it. + */ + suspend fun discardStagedExitState(exitState: String) { + hasMergedRemoteExitState = false + deleteStagedExitState(exitState) + } + + /** Deletes staged exit data that still holds [exitState], under the lock staging and import take. */ + private suspend fun deleteStagedExitState(exitState: String) = exitImportMutex.withLock { + val staged = File(Env.sparkExitRestorePath(walletIndex)) + if (staged.exists() && staged.readText() == exitState) staged.delete() + } + /** * Puts a restored exit data backup back: at once while Spark is connected, otherwise right after it connects, - * before it is used, so a restored wallet can exit on-chain even while the Spark operators are unreachable. + * before it is used, so a restored wallet can exit on-chain even while the Spark operators are unreachable. The + * wallet's start waits for the restore, so the restore connects Spark itself and fails when Spark can't import the + * data; one that can't connect keeps the data staged for Spark's start. */ suspend fun restoreExitBackup(backup: SparkExitBackupV1, walletIndex: Int): Result = withContext(bgDispatcher) { @@ -1163,15 +1332,36 @@ class SparkRepo @Inject constructor( Logger.warn("Skipped Spark exit data from network '${backup.network}'", context = TAG) return@runSuspendCatching } - File(Env.sparkExitRestorePath(walletIndex)).writeText(backup.exitState) + exitImportMutex.withLock { File(Env.sparkExitRestorePath(walletIndex)).writeText(backup.exitState) } + if (sparkService.isSupported && !sparkService.isConnected) connectForRestore(walletIndex) if (sparkService.isConnected) importRestoredExitState(walletIndex).getOrThrow() } } - private suspend fun importRestoredExitState(walletIndex: Int): Result { + /** Collects Spark's events once and returns once subscribed, so no event of a connect made after it is lost. */ + private suspend fun collectEvents() { + if (isCollectingEvents.compareAndSet(false, true)) { + scope.launch { + sparkService.events.onSubscription { eventsSubscribed.complete(Unit) }.collect { onSdkEvent(it) } + } + } + eventsSubscribed.await() + } + + private suspend fun connectForRestore(walletIndex: Int) { + // Spark's listener drops events no one collects, and the wallet's start collects them only after the restore. + // The sends held before the restore are taken back first, so its events settle them. + restoreUncertainSends() + collectEvents() + runSuspendCatching { sparkService.connect(walletIndex, exitStore(walletIndex).isActive()) } + .onSuccess { if (it) _exitStateGeneration.update { generation -> generation + 1 } } + .onFailure { Logger.warn("Failed to connect Spark to import restored exit data", it, context = TAG) } + } + + private suspend fun importRestoredExitState(walletIndex: Int): Result = exitImportMutex.withLock { val file = File(Env.sparkExitRestorePath(walletIndex)) - if (!file.exists()) return Result.success(Unit) - return runSuspendCatching { sparkService.importExitState(file.readText()) } + if (!file.exists()) return@withLock Result.success(Unit) + runSuspendCatching { sparkService.importExitState(file.readText()) } .onSuccess { file.delete() Logger.info( @@ -1193,7 +1383,7 @@ class SparkRepo @Inject constructor( val info = sparkService.getInfo() info.lastSyncError?.let { Logger.warn("Failed to sync Spark, balances may be stale: '$it'", context = TAG) } val unclaimed = sparkService.listUnclaimedDeposits() - val payments = sparkService.listPayments() + val payments = listPayments() val claimedPayments = payments .filter { it.method == PaymentMethod.DEPOSIT && it.status == PaymentStatus.COMPLETED } val claimed = claimedPayments @@ -1245,7 +1435,7 @@ class SparkRepo @Inject constructor( ).withBroadcastDeposits() } markClaimedDeposits(claimed) - payments + payments.decidingRows() .filter { it.id in unsavedPayments || (it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0) } .forEach { recordActivity(it) } // Off the refresh, so a slow Electrum server never holds a send that waits for it. @@ -1344,13 +1534,37 @@ class SparkRepo @Inject constructor( */ suspend fun settledSendEvent(paymentHash: String): Event? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null - runSuspendCatching { sparkService.listPayments() } + // Read before the list, so a hold its success event ends while the list is read still keeps it pending. + val heldStart = sendHoldStart(paymentHash.lowercase()) + runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() ?.latestSend(paymentHash) + // A send in doubt or in Spark's send call is pending until Spark settles it, so a listed failure, which + // may be an earlier attempt's, settles nothing yet. + ?.takeUnless { it.status == PaymentStatus.FAILED && isHeldFrom(it, heldStart) } ?.toNodeEvent() } + /** + * Whether [failure] leaves its send pending: while it is in Spark's send call, whose result settles it, or in doubt + * and Spark dates the failure more than [OWN_FAILURE_CLOCK_MARGIN_SECS] before the send started, as an earlier + * attempt's. + */ + private suspend fun isHeldFrom(failure: Payment, heldStart: ULong? = null): Boolean { + val hash = failure.sendHash()?.lowercase() ?: return false + if (sendsInFlight.containsKey(hash)) return true + val startedAt = listOfNotNull(heldStart, sendHoldStart(hash)).maxOrNull() ?: return false + return failure.timestamp.safe() + OWN_FAILURE_CLOCK_MARGIN_SECS.safe() < startedAt + } + + private suspend fun hasOwnFailure(paymentHash: String, listing: List? = null): Boolean { + val failure = (listing ?: runSuspendCatching { listPayments() }.getOrNull()) + ?.latestSend(paymentHash) + ?.takeIf { it.status == PaymentStatus.FAILED } ?: return false + return !isHeldFrom(failure) + } + /** * False while Spark is supported but not connected or not yet synced, since its payment list is read from local * storage that a restored wallet fills only on its first sync, so a missing payment proves nothing until then. @@ -1367,7 +1581,7 @@ class SparkRepo @Inject constructor( if (!canListPayments()) return@withContext null val unlisted = unexpiredStartedSends() val uncertain = uncertainSendHashes() - val payments = runSuspendCatching { sparkService.listPayments() } + val payments = runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrElse { return@withContext null } val listed = payments @@ -1396,8 +1610,10 @@ class SparkRepo @Inject constructor( suspend fun lightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { val hash = paymentHash.lowercase() val isUnlistedHeld = hash in unexpiredStartedSends() + // Read before the list, so a hold its success event ends while the list is read still keeps it pending. + val wasUncertain = sendHoldStart(hash) != null val send = listedLightningSend(paymentHash) - val isUncertain = hash in uncertainSendHashes() + val isUncertain = wasUncertain || sendHoldStart(hash) != null val isHeld = when (send) { SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> isUncertain || isUnlistedHeld is SparkLightningSend.Found -> isUncertain && send.status == PaymentStatus.FAILED @@ -1405,11 +1621,17 @@ class SparkRepo @Inject constructor( if (isHeld) SparkLightningSend.Found(PaymentStatus.PENDING, null) else send } + private suspend fun sendHoldStart(hash: String): ULong? = + uncertainSends[hash]?.startedAt ?: cacheStore.data.first().sparkUncertainSends[hash]?.toULong() + /** Spark's listed record of the Lightning send with [paymentHash], as [lightningSend] reads it before its holds. */ - private suspend fun listedLightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { + private suspend fun listedLightningSend( + paymentHash: String, + listing: List? = null, + ): SparkLightningSend = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext SparkLightningSend.NotFound if (!canListPayments()) return@withContext SparkLightningSend.Unavailable - val payments = runSuspendCatching { sparkService.listPayments() } + val payments = listing ?: runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrElse { return@withContext SparkLightningSend.Unavailable } payments.latestSend(paymentHash) @@ -1450,7 +1672,7 @@ class SparkRepo @Inject constructor( val unlisted = unexpiredStartedSends() // Before Spark's first sync its local list can be empty although a restored send is live. val payments = if (sparkService.isSupported && canListPayments()) { - runSuspendCatching { sparkService.listPayments() } + runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() } else { @@ -1499,12 +1721,13 @@ class SparkRepo @Inject constructor( bolt11: String, invoiceCreatedAt: Long?, invoiceExpiresAt: Long?, + isFailedUnsent: Boolean = true, ) { val restoredAt = cacheStore.data.first().sparkRestoredAt ?: return val isHeld = sparkService.isSupported && (invoiceCreatedAt ?: 0L) < restoredAt && (invoiceExpiresAt == null || clock.now().epochSeconds < invoiceExpiresAt) - if (!isHeld || isUnsentPerOperators(bolt11)) return + if (!isHeld || isUnsentPerOperators(bolt11, isFailedUnsent)) return Logger.warn("Refused a send of a pre-restore invoice the Spark operators can't show unsent", context = TAG) throw SparkError.RestoredInvoiceUnverified() } @@ -1512,14 +1735,15 @@ class SparkRepo @Inject constructor( /** * Whether the Spark operators confirm this wallet never sent [bolt11] over Lightning, and it can't have been paid * by a direct Spark transfer, which they don't see: false when they show a send completed or pending, or can't be - * asked. A failed one counts as unsent, as they show it failed only once every attempt at the hash was returned. + * asked. A failed one counts as unsent when [isFailedUnsent], as they show it failed only once every attempt at the + * hash was returned. */ - private suspend fun isUnsentPerOperators(bolt11: String): Boolean { + private suspend fun isUnsentPerOperators(bolt11: String, isFailedUnsent: Boolean = true): Boolean { if (!sparkService.isConnected) return false val status = runSuspendCatching { sparkService.lightningSendStatus(bolt11) } .onFailure { Logger.warn("Failed to fetch Spark's send status", it, context = TAG) } .getOrElse { return false } - if (status != null && status != PaymentStatus.FAILED) { + if (status != null && (status != PaymentStatus.FAILED || !isFailedUnsent)) { Logger.info("Found a '$status' Spark operator send of the pre-restore invoice", context = TAG) return false } @@ -1564,8 +1788,14 @@ class SparkRepo @Inject constructor( val details = it.details as? PaymentDetails.Lightning it.paymentType == SparkPaymentType.SEND && details != null && matches(details) } - // A retry of a failed send shares its hash, so the outcome that settles it wins. - .minByOrNull { SEND_STATUS_PRIORITY.indexOf(it.status) } + // A retry of a failed send shares its hash, so the outcome that settles it wins, then the latest attempt. + .minWithOrNull(compareBy({ SEND_STATUS_PRIORITY.indexOf(it.status) }, { -it.timestamp.toLong() })) + + /** Drops each send another attempt on its invoice decides, so one Activity row shows the deciding outcome. */ + private fun List.decidingRows(): List = filter { + val hash = (it.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash + it.paymentType != SparkPaymentType.SEND || hash == null || latestSend(hash)?.id == it.id + } /** Payment hashes of the Lightning payments Spark received. */ suspend fun receivedLightningPaymentHashes(): Set = @@ -1589,7 +1819,7 @@ class SparkRepo @Inject constructor( private suspend fun lightningPaymentStatuses(filter: (Payment) -> Boolean): Map>? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null - runSuspendCatching { sparkService.listPayments() } + runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() ?.filter(filter) @@ -1603,7 +1833,7 @@ class SparkRepo @Inject constructor( private suspend fun lightningPaymentHashes(filter: (Payment) -> Boolean): Set? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null - runSuspendCatching { sparkService.listPayments() } + runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() ?.filter(filter) @@ -1617,7 +1847,7 @@ class SparkRepo @Inject constructor( */ private suspend fun seedRestoredSendHashes() { if (cacheStore.data.first().sparkHistoryUnseededSince == null || !canListPayments()) return - runSuspendCatching { sparkService.listPayments() } + runSuspendCatching { listPayments() } .onSuccess { seedSendHashes(it) } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } } @@ -1649,11 +1879,24 @@ class SparkRepo @Inject constructor( // A list read while a withdrawal was in flight, or before one ended, may lack it, so it settles no journal. val sendsEndedBefore = withdrawalSendsEnded.get() val wasWithdrawing = isWithdrawing + // A send held after the list was read may be missing from it, so only the holds before it settle from it. + val heldBefore = uncertainSends.toMap() // Read before the list, as one read before Spark's first sync can lack its restored sends. val isSynced = canListPayments() - val payments = sparkService.listPayments() + val payments = listPayments() if (isSynced) seedSendHashes(payments) - val isSaved = payments.map { recordActivity(it) }.all { it } + val isSaved = payments.decidingRows().map { recordActivity(it) }.all { it } + // A held send that this list shows settled, as by its own failure, ends here, so its hold never waits on + // another read of Spark's list. + if (isSynced) { + heldBefore.forEach { (hash, held) -> + trySettleUncertainSend( + hash, + listing = payments, + held = held + ) + } + } releaseFailedSends(payments, recordsBefore, inFlightBefore) if (!settleJournal || wasWithdrawing || isWithdrawing || withdrawalSendsEnded.get() != sendsEndedBefore) { return isSaved @@ -1726,7 +1969,7 @@ class SparkRepo @Inject constructor( // A retry can start while the list is recorded, so the release reads Spark's sends again first. val recordsBeforeCurrent = sendRecords.get() val inFlightBeforeCurrent = sendsInFlight.keys.toSet() - val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return + val current = runSuspendCatching { listPayments() }.getOrNull() ?: return val liveCurrent = sendsInFlight.keys + inFlightBeforeCurrent + recordedSince(recordsBeforeCurrent) + uncertainSendHashes() failed @@ -1737,6 +1980,27 @@ class SparkRepo @Inject constructor( private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys + private suspend fun listPayments(): List = sparkService.listPayments().onEach { noteFailure(it) } + + private fun noteFailure(payment: Payment) { + val hash = payment.sendHash(PaymentStatus.FAILED)?.lowercase() ?: return + sendFailedAt.merge(hash, payment.timestamp) { old, new -> maxOf(old, new) } + } + + /** + * When a send of [paymentHash] starting now counts as started: past every failure Spark dated for it by more than + * [OWN_FAILURE_CLOCK_MARGIN_SECS], so an earlier attempt's failure never reads as this send's own. Refused when + * Spark's list can't be read, as it may hold a failure unknown to this process; nothing has gone out yet. + */ + private suspend fun sendStartedAt(paymentHash: String): Long { + runSuspendCatching { listPayments() }.onFailure { + throw SparkError.SendRefused("Spark could not list its payments to date the send", it) + } + val now = clock.now().epochSeconds.toULong() + val failedAt = sendFailedAt[paymentHash.lowercase()] ?: return now.toLong() + return maxOf(now, failedAt.safe() + (OWN_FAILURE_CLOCK_MARGIN_SECS + 1uL).safe()).toLong() + } + /** The payment hash of this send, at [status] when given. */ private fun Payment.sendHash(status: PaymentStatus? = null): String? = (details as? PaymentDetails.Lightning) ?.takeIf { paymentType == SparkPaymentType.SEND && (status == null || this.status == status) } @@ -1750,7 +2014,9 @@ class SparkRepo @Inject constructor( if (hasSyncedSince(null)) _state.update { it.copy(hasSynced = true) } seedRestoredSendHashes() refresh() - // A send whose outcome stayed unknown past its polling settles on a later sync. + // A send whose outcome stayed unknown past its polling settles on a later sync, also one only + // saved, as when its caller was cancelled inside Spark's send call. + restoreUncertainSends() uncertainSends.keys.toList().forEach { trySettleUncertainSend(it) } // A journal left open past its grace period would block every later withdrawal until a restart. // Spark emits Synced after a sync that never reached it too, so only one since the journal @@ -1778,21 +2044,42 @@ class SparkRepo @Inject constructor( } private suspend fun onPayment(payment: Payment) { + noteFailure(payment) // The event carries its outcome, so a failed balance read never holds back its settlement. runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } - recordActivity(payment, settlesJournal = false) - // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. - payment.sendHash()?.let { - uncertainSends.remove(it.lowercase()) - cacheStore.removeSparkUncertainSend(it) - } + // An earlier attempt's failure, or one during Spark's send call, leaves the send pending until its own outcome, + // its call's result or its invoice's expiry settles it. + payment.sendHash(PaymentStatus.FAILED)?.takeIf { isHeldFrom(payment) }?.let { + trySettleUncertainSend(it, isFailureEvent = true) + return + } + // A failure of an attempt that Spark's list shows another attempt deciding, as pending, paid or a later + // failure, settles nothing. payment.sendHash(PaymentStatus.FAILED)?.let { hash -> - val latest = listedLightningSend(hash) - val isReleased = latest == SparkLightningSend.NotFound || - (latest as? SparkLightningSend.Found)?.status == PaymentStatus.FAILED - if (isReleased) cacheStore.removeSparkSendHash(hash) + val deciding = runSuspendCatching { listPayments() }.getOrNull()?.latestSend(hash) + if (deciding != null && deciding.id != payment.id) return } + recordActivity(payment, settlesJournal = false) + val isRetried = payment.sendHash()?.let { hash -> + val isFailed = payment.status == PaymentStatus.FAILED + val isReleased = isFailed && listedLightningSend(hash).let { + it == SparkLightningSend.NotFound || (it as? SparkLightningSend.Found)?.status == PaymentStatus.FAILED + } + // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. A send + // enters Spark's send call under the same lock, so a retry started since the checks above keeps its hold + // and saved send, and reports its own outcome. + holdRestoreMutex.withLock { + if (isFailed && isHeldFrom(payment)) return@withLock true + uncertainSends.remove(hash.lowercase()) + cacheStore.removeSparkUncertainSend(hash) + if (isReleased) cacheStore.removeSparkSendHash(hash) + false + } + } ?: false + if (isRetried) return + // The poll may have reported this payment's outcome already. + if (payment.sendHash() != null && !reportedSendIds.add(payment.id)) return payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } @@ -1808,6 +2095,11 @@ class SparkRepo @Inject constructor( return true } val id = lightning.htlcDetails.paymentHash + // A send in doubt or in Spark's send call shows as pending until Spark settles it, whatever an earlier attempt + // on its invoice failed with. + if (payment.status == PaymentStatus.FAILED && isHeldFrom(payment)) { + return true + } // A failed read would drop the stored note, contact and seen time, so the write waits for the next refresh. val stored = activityRepo.get().getActivity(id).getOrElse { unsavedPayments.add(payment.id) @@ -1830,7 +2122,10 @@ class SparkRepo @Inject constructor( } // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true - val activity = LightningActivity.create( + // A failure, possibly an earlier attempt's, only fails the send's row, which keeps its own details. + val failedRow = existing?.takeIf { payment.status == PaymentStatus.FAILED && it.txType == PaymentType.SENT } + if (failedRow?.status == PaymentState.FAILED) return true + val activity = failedRow?.copy(status = PaymentState.FAILED) ?: LightningActivity.create( id = id, txType = when (payment.paymentType) { SparkPaymentType.SEND -> PaymentType.SENT @@ -2279,3 +2574,15 @@ fun SparkEarlyClaim.toDepositClaim(offer: SparkClaimOffer.Choice): SparkDepositC is SparkEarlyClaim.Repriced -> SparkDepositClaim.Repriced(offer.copy(earlyFeeSats = requiredFeeSats)) SparkEarlyClaim.Declined -> SparkDepositClaim.Unavailable } + +/** What became of restored exit data waiting for Spark to import it. */ +sealed interface StagedExitImport { + data object NothingStaged : StagedExitImport + data object Imported : StagedExitImport + + /** Spark is not connected, or the import failed for a reason that may pass. */ + data object Pending : StagedExitImport + + /** Spark can never import [exitState], restored for [network]. */ + data class Rejected(val exitState: String, val network: String) : StagedExitImport +} diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 594bc11371..e37a421ef9 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -360,6 +360,9 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me class WipeInProgress : SparkError("Spark wallet cannot connect while the wallet is wiped") class WipeFailed(path: String) : SparkError("Failed to delete Spark storage at '$path'") + /** Stored exit data Spark can never import: an exit state version it doesn't support, or one it can't read. */ + class ExitStateUnimportable(cause: Throwable? = null) : SparkError("Spark can't import the exit data", cause) + /** What the withdrawal leaves after its fee is below the on-chain dust limit. */ class WithdrawalTooSmall : SparkError("Spark balance is too small to withdraw after its fee") diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 9afdb12174..3ffc0a4355 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -1421,11 +1421,13 @@ private fun NavGraphBuilder.home( val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle() val lightningActivities by activityListViewModel.lightningActivities.collectAsStateWithLifecycle() + val hasRetainedMove by walletViewModel.hasRetainedMove.collectAsStateWithLifecycle() SpendingWalletScreen( channels = lightningState.channels, hasSparkBalance = sparkState.shownSpendingSats > 0uL, - canMoveToSpark = MoveToSparkMath.canMove(lightningState.channels, sparkState), + // A move left while it ran keeps its way back to its result, also once nothing is left to move. + canMoveToSpark = hasRetainedMove || MoveToSparkMath.canMove(lightningState.channels, sparkState), onMoveToSparkClick = { navController.navigateTo(Routes.MoveToSpark) }, lightningActivities = lightningActivities ?: persistentListOf(), onAllActivityButtonClick = { navController.navigateToAllActivity(activityListViewModel::clearFilters) }, diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt index 232f3f352a..7aa7471eef 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt @@ -323,7 +323,9 @@ class SparkFundingViewModel @Inject constructor( } val walletId = shown.hwWalletId if (walletId == null) { - send(quote) + // A max transfer can reach spending with a higher Instant claim fee than the one swiped, so the early + // claim approves at most the fee shown, and asks first for more. + send(quote.copy(instantFeeSats = minOf(quote.instantFeeSats, shownQuote.instantFeeSats))) return@launch } _uiState.update { it.copy(isSending = false) } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt index 6128329df6..8cea520cee 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt @@ -57,6 +57,7 @@ import to.bitkit.ext.UiDateStyle import to.bitkit.ext.contact import to.bitkit.ext.create import to.bitkit.ext.ellipsisMiddle +import to.bitkit.ext.isMoveToSpark import to.bitkit.ext.isSent import to.bitkit.ext.isTransfer import to.bitkit.ext.rawId @@ -180,6 +181,8 @@ fun ActivityDetailScreen( val settings = settingsViewModel ?: return@Box val hideBalance by settings.hideBalance.collectAsStateWithLifecycle() val isPaykitEnabled by settings.isPaykitEnabled.collectAsStateWithLifecycle() + val moveHashes by app.moveToSparkHashes.collectAsStateWithLifecycle(initialValue = emptySet()) + val isMoveToSpark = item.isMoveToSpark(moveHashes) val copyToastTitle = stringResource(R.string.common__copied) val tags by detailViewModel.tags.collectAsStateWithLifecycle() @@ -232,10 +235,10 @@ fun ActivityDetailScreen( ) { AppTopBar( titleText = stringResource( - if (isCpfpChild) { - R.string.wallet__activity_boost_fee - } else { - item.getScreenTitleRes() + when { + isCpfpChild -> R.string.wallet__activity_boost_fee + isMoveToSpark -> R.string.wallet__activity_move_to_spark + else -> item.getScreenTitleRes() } ), onBackClick = onBackClick, @@ -257,6 +260,7 @@ fun ActivityDetailScreen( isCpfpChild = isCpfpChild, isHardware = uiState.isHardwareActivity, isSparkWithdrawal = isSparkWithdrawal, + isMoveToSpark = isMoveToSpark, showContactActions = isPaykitEnabled && (!uiState.isHardwareActivity || assignedContact != null), boostTxDoesExist = boostTxDoesExist, @@ -351,6 +355,7 @@ private fun ActivityDetailContent( isCpfpChild: Boolean = false, isHardware: Boolean = false, isSparkWithdrawal: Boolean = false, + isMoveToSpark: Boolean = false, showContactActions: Boolean = true, boostTxDoesExist: ImmutableMap = persistentMapOf(), onCopy: (String) -> Unit, @@ -428,6 +433,7 @@ private fun ActivityDetailContent( size = 48.dp, isCpfpChild = isCpfpChild, isHardware = isHardware, + isMoveToSpark = isMoveToSpark, ) } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt index 1127c8c768..396524d9ec 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt @@ -42,6 +42,7 @@ fun ActivityIcon( size: Dp = 32.dp, isCpfpChild: Boolean = false, isHardware: Boolean = false, + isMoveToSpark: Boolean = false, contact: PubkyProfile? = null, ) { val isLightning = activity is Activity.Lightning @@ -61,6 +62,14 @@ fun ActivityIcon( ) } + isMoveToSpark && status == PaymentState.SUCCEEDED -> CircularIcon( + icon = painterResource(R.drawable.ic_transfer), + iconColor = Colors.Purple, + backgroundColor = Colors.Purple16, + size = size, + modifier = modifier.testTag("MoveToSparkIcon"), + ) + contact != null -> PubkyContactAvatar( profile = contact, size = size, diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt index c204cc0fc9..25c5658fa9 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt @@ -31,6 +31,7 @@ import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.PaymentType import to.bitkit.R +import to.bitkit.ext.isMoveToSpark import to.bitkit.ext.isSent import to.bitkit.ext.isTransfer import to.bitkit.ext.timestamp @@ -86,6 +87,9 @@ fun ActivityRow( is Activity.Onchain -> item.v1.txId }.lowercase() val receiptStatus = receiptStatuses[paymentId].takeIf { item.txType() == PaymentType.RECEIVED } + val moveHashes by appViewModel?.moveToSparkHashes?.collectAsStateWithLifecycle(initialValue = emptySet()) + ?: remember { mutableStateOf(emptySet()) } + val isMoveToSpark = item.isMoveToSpark(moveHashes) val status: PaymentState? = when (item) { is Activity.Lightning -> item.v1.status @@ -103,11 +107,13 @@ fun ActivityRow( val isTransfer = item.isTransfer() val activityListViewModel = activityListViewModel var isCpfpChild by remember { mutableStateOf(false) } - val resolvedTitle = title.takeIf { - shouldUseContactActivityTitle(item, status, isTransfer, isCpfpChild) + val resolvedTitle = if (isMoveToSpark) { + stringResource(R.string.wallet__activity_move_to_spark) + } else { + title.takeIf { shouldUseContactActivityTitle(item, status, isTransfer, isCpfpChild) } } val resolvedContact = contact.takeIf { - shouldUseContactActivityTitle(item, status, isTransfer, isCpfpChild) + !isMoveToSpark && shouldUseContactActivityTitle(item, status, isTransfer, isCpfpChild) } LaunchedEffect(item) { @@ -124,6 +130,7 @@ fun ActivityRow( size = 40.dp, isCpfpChild = isCpfpChild, isHardware = isHardware, + isMoveToSpark = isMoveToSpark, contact = resolvedContact, ) HorizontalSpacer(16.dp) @@ -141,6 +148,11 @@ fun ActivityRow( ) val context = LocalContext.current val subtitleText = when (item) { + is Activity.Lightning if isMoveToSpark -> when (item.v1.status) { + PaymentState.FAILED -> stringResource(R.string.wallet__activity_failed) + PaymentState.PENDING -> stringResource(R.string.wallet__activity_pending) + PaymentState.SUCCEEDED -> activityTimeText(timestamp) + } is Activity.Lightning -> item.v1.message.ifEmpty { activityTimeText(timestamp) } is Activity.Onchain -> { when { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt index a07fec6376..4ee0519042 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt @@ -65,6 +65,7 @@ class LightningConnectionsViewModel @Inject constructor( private val activityRepo: ActivityRepo, private val sparkRepo: SparkRepo, private val sparkExitRepo: SparkExitRepo, + private val moveToSparkManager: MoveToSparkManager, private val healthRepo: HealthRepo, ) : ViewModel() { @@ -113,9 +114,13 @@ class LightningConnectionsViewModel @Inject constructor( lightningRepo.lastKnownChannels, sparkRepo.state, sparkExitRepo.state, - healthRepo.healthState.map { it.internet == HealthState.READY }.distinctUntilChanged(), - ) { lightningState, channels, sparkState, exitState, isOnline -> - ConnectionsSnapshot(lightningState, channels, sparkState, exitState, isOnline) + combine( + moveToSparkManager.hasRetainedMove, + healthRepo.healthState.map { it.internet == HealthState.READY }.distinctUntilChanged(), + ::Pair, + ), + ) { lightningState, channels, sparkState, exitState, (hasRetainedMove, isOnline) -> + ConnectionsSnapshot(lightningState, channels, sparkState, exitState, hasRetainedMove, isOnline) }.collect { snapshot -> val (lightningState, channels, sparkState) = snapshot val isNodeRunning = lightningState.nodeLifecycleState.isRunning() @@ -133,7 +138,9 @@ class LightningConnectionsViewModel @Inject constructor( localBalance = calculateLocalBalance(channels).safe() + sparkState.shownSpendingSats.safe(), remoteBalance = channels.calculateRemoteBalance(), // The cached channels outlive a stopped node; the move reads the live ones. - canMoveToSpark = MoveToSparkMath.canMove(lightningState.channels, sparkState), + // A move left while it ran keeps its way back to its result, also once nothing is left to move. + canMoveToSpark = snapshot.hasRetainedMove || + MoveToSparkMath.canMove(lightningState.channels, sparkState), spark = sparkState.toUi( lightningRepo, snapshot.exitState.showsResult, @@ -330,6 +337,7 @@ private data class ConnectionsSnapshot( val channels: List, val sparkState: SparkState, val exitState: SparkExitState, + val hasRetainedMove: Boolean, val isOnline: Boolean, ) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt new file mode 100644 index 0000000000..657ed31caf --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt @@ -0,0 +1,174 @@ +package to.bitkit.ui.settings.lightning + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import to.bitkit.async.appScope +import to.bitkit.di.BgDispatcher +import to.bitkit.ext.filterOpen +import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.MoveToSparkError +import to.bitkit.repositories.MoveToSparkMath +import to.bitkit.repositories.MoveToSparkOutcome +import to.bitkit.repositories.MoveToSparkRepo +import to.bitkit.repositories.WalletRepo +import java.util.concurrent.atomic.AtomicInteger +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Holds the Move to Spark screen's state for the app's lifetime, so a move and its outcome outlive the screen: leaving + * while the payment is under way no longer stops the wait, and opening the screen again shows that move. + */ +@Singleton +class MoveToSparkManager @Inject constructor( + @BgDispatcher bgDispatcher: CoroutineDispatcher, + private val moveToSparkRepo: MoveToSparkRepo, + private val lightningRepo: LightningRepo, + private val walletRepo: WalletRepo, +) { + companion object { + private const val TAG = "MoveToSparkManager" + } + + private val scope = appScope(bgDispatcher, TAG) + + private val _uiState = MutableStateFlow(MoveToSparkUiState.Quoting) + val uiState: StateFlow = _uiState.asStateFlow() + + /** Counts quotes, moves and resets; a quote or move writes its result only while it is still the latest. */ + private val generation = AtomicInteger(0) + private val latestScreen = AtomicInteger(0) + private var quoteJob: Job? = null + private var moveJob: Job? = null + + private val _hasRetainedMove = MutableStateFlow(false) + + /** + * A move was started and its outcome is still the screen's, so opening the screen again keeps it and its entry + * points stay, also once no balance is left to move. + */ + val hasRetainedMove: StateFlow = _hasRetainedMove.asStateFlow() + + private var keepsOutcome: Boolean + get() = _hasRetainedMove.value + set(value) = _hasRetainedMove.update { value } + + /** A swiped payment that has not settled yet; leaving the screen keeps it, so it is never quoted over. */ + @Volatile + private var isMoveInFlight = false + + /** + * Opens the screen: quotes a new move, unless one is quoting or a move is running or still shows its outcome. + * Returns the screen's token for [reset]. + */ + fun start(): Int { + val screen = latestScreen.incrementAndGet() + if (!keepsOutcome && quoteJob?.isActive != true) quote() + return screen + } + + /** + * Forgets the last move once its [screen] is left, unless its payment is still in flight or a newer screen opened + * before this one closed. + */ + fun reset(screen: Int) { + if (screen != latestScreen.get() || isMoveInFlight) return + generation.incrementAndGet() + quoteJob?.cancel() + keepsOutcome = false + _uiState.update { MoveToSparkUiState.Quoting } + } + + /** Drops the move, its outcome and any quote when the wallet is wiped, so the next wallet starts on a new quote. */ + fun resetForWipe() { + generation.incrementAndGet() + quoteJob?.cancel() + moveJob?.cancel() + keepsOutcome = false + isMoveInFlight = false + _uiState.update { MoveToSparkUiState.Quoting } + } + + /** Quotes moving [targetSats], or everything the channels can send. */ + fun quote(targetSats: ULong? = null) { + val quoteGeneration = generation.incrementAndGet() + keepsOutcome = false + _uiState.update { MoveToSparkUiState.Quoting } + quoteJob?.cancel() + quoteJob = scope.launch { + val quoted = moveToSparkRepo.quote(targetSats).fold( + onSuccess = { MoveToSparkUiState.Confirm(it) }, + onFailure = { it.toUiState() }, + ) + if (generation.get() == quoteGeneration) _uiState.update { quoted } + } + } + + fun move() { + val confirm = _uiState.value as? MoveToSparkUiState.Confirm ?: return + if (confirm.isMoving) return + val quote = confirm.quote + val moveGeneration = generation.incrementAndGet() + keepsOutcome = true + isMoveInFlight = true + _uiState.update { MoveToSparkUiState.Confirm(quote, isMoving = true) } + moveJob = scope.launch { + try { + moveToSparkRepo.move(quote).fold( + onSuccess = { outcome -> + val settled = (outcome as? MoveToSparkOutcome.InFlight)?.let { + async(start = CoroutineStart.UNDISPATCHED) { moveToSparkRepo.awaitSettled(it) } + } + val done = done(outcome) + if (generation.get() == moveGeneration) _uiState.update { done } + settled?.await()?.let { showLateOutcome(it, moveGeneration) } + }, + onFailure = { error -> + if (generation.get() == moveGeneration) _uiState.update { error.toUiState() } + }, + ) + } finally { + if (generation.get() == moveGeneration) isMoveInFlight = false + } + } + } + + private suspend fun done(outcome: MoveToSparkOutcome): MoveToSparkUiState.Done { + walletRepo.syncNodeAndWallet() + val hasRest = MoveToSparkMath.hasMovableBalance(moveToSparkRepo.movableSats()) + return MoveToSparkUiState.Done(outcome, emptiedChannelId(), hasRest) + } + + private suspend fun showLateOutcome(settled: Result, moveGeneration: Int) { + if (generation.get() != moveGeneration || !uiState.value.isInFlight()) return + val late = settled.fold( + onSuccess = { done(it) }, + onFailure = { MoveToSparkUiState.Failed(MoveToSparkFailure.UNKNOWN) }, + ) + _uiState.update { if (generation.get() == moveGeneration && it.isInFlight()) late else it } + } + + private fun MoveToSparkUiState.isInFlight(): Boolean = + this is MoveToSparkUiState.Done && outcome is MoveToSparkOutcome.InFlight + + /** The channel to close after the move, when exactly one is open; with several, the user picks in Connections. */ + private fun emptiedChannelId(): String? = lightningRepo.lightningState.value.channels.filterOpen() + .singleOrNull()?.channelId + + private fun Throwable.toUiState(): MoveToSparkUiState = when (this) { + is MoveToSparkError.TooLarge -> MoveToSparkUiState.TooLarge( + amountSats = amountSats, + smallerSats = MoveToSparkMath.smallerAmount(amountSats), + ) + is MoveToSparkError.NothingToMove -> MoveToSparkUiState.Failed(MoveToSparkFailure.NOTHING_TO_MOVE) + is MoveToSparkError.SparkUnavailable -> MoveToSparkUiState.Failed(MoveToSparkFailure.SPARK_UNAVAILABLE) + else -> MoveToSparkUiState.Failed(MoveToSparkFailure.UNKNOWN) + } +} diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt index b84ca7b74d..d883139998 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt @@ -2,102 +2,28 @@ package to.bitkit.ui.settings.lightning import androidx.compose.runtime.Immutable import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.CoroutineStart -import kotlinx.coroutines.async -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import to.bitkit.ext.filterOpen -import to.bitkit.repositories.LightningRepo -import to.bitkit.repositories.MoveToSparkError -import to.bitkit.repositories.MoveToSparkMath import to.bitkit.repositories.MoveToSparkOutcome import to.bitkit.repositories.MoveToSparkQuote -import to.bitkit.repositories.MoveToSparkRepo -import to.bitkit.repositories.WalletRepo import javax.inject.Inject +/** The Move to Spark screen's view of [MoveToSparkManager], which keeps a move running after the screen closes. */ @HiltViewModel class MoveToSparkViewModel @Inject constructor( - private val moveToSparkRepo: MoveToSparkRepo, - private val lightningRepo: LightningRepo, - private val walletRepo: WalletRepo, + private val manager: MoveToSparkManager, ) : ViewModel() { - private val _uiState = MutableStateFlow(MoveToSparkUiState.Quoting) - val uiState = _uiState.asStateFlow() + val uiState = manager.uiState - private var moveGeneration = 0 - - init { - quote() - } + private val screen = manager.start() /** Quotes moving [targetSats], or everything the channels can send. */ - fun quote(targetSats: ULong? = null) { - _uiState.update { MoveToSparkUiState.Quoting } - viewModelScope.launch { - moveToSparkRepo.quote(targetSats).fold( - onSuccess = { quote -> _uiState.update { MoveToSparkUiState.Confirm(quote) } }, - onFailure = { error -> _uiState.update { error.toUiState() } }, - ) - } - } - - fun move() { - val confirm = _uiState.value as? MoveToSparkUiState.Confirm ?: return - if (confirm.isMoving) return - val quote = confirm.quote - _uiState.update { MoveToSparkUiState.Confirm(quote, isMoving = true) } - val generation = ++moveGeneration - viewModelScope.launch { - moveToSparkRepo.move(quote).fold( - onSuccess = { outcome -> - val settled = (outcome as? MoveToSparkOutcome.InFlight)?.let { - async(start = CoroutineStart.UNDISPATCHED) { moveToSparkRepo.awaitSettled(it) } - } - val done = done(outcome) - _uiState.update { done } - settled?.await()?.let { showLateOutcome(it, generation) } - }, - onFailure = { error -> _uiState.update { error.toUiState() } }, - ) - } - } - - private suspend fun done(outcome: MoveToSparkOutcome): MoveToSparkUiState.Done { - walletRepo.syncNodeAndWallet() - val hasRest = MoveToSparkMath.hasMovableBalance(moveToSparkRepo.movableSats()) - return MoveToSparkUiState.Done(outcome, emptiedChannelId(), hasRest) - } - - private suspend fun showLateOutcome(settled: Result, generation: Int) { - if (generation != moveGeneration || !uiState.value.isInFlight()) return - val late = settled.fold( - onSuccess = { done(it) }, - onFailure = { MoveToSparkUiState.Failed(MoveToSparkFailure.UNKNOWN) }, - ) - _uiState.update { if (generation == moveGeneration && it.isInFlight()) late else it } - } - - private fun MoveToSparkUiState.isInFlight(): Boolean = - this is MoveToSparkUiState.Done && outcome is MoveToSparkOutcome.InFlight + fun quote(targetSats: ULong? = null) = manager.quote(targetSats) - /** The channel to close after the move, when exactly one is open; with several, the user picks in Connections. */ - private fun emptiedChannelId(): String? = lightningRepo.lightningState.value.channels.filterOpen() - .singleOrNull()?.channelId + fun move() = manager.move() - private fun Throwable.toUiState(): MoveToSparkUiState = when (this) { - is MoveToSparkError.TooLarge -> MoveToSparkUiState.TooLarge( - amountSats = amountSats, - smallerSats = MoveToSparkMath.smallerAmount(amountSats), - ) - is MoveToSparkError.NothingToMove -> MoveToSparkUiState.Failed(MoveToSparkFailure.NOTHING_TO_MOVE) - is MoveToSparkError.SparkUnavailable -> MoveToSparkUiState.Failed(MoveToSparkFailure.SPARK_UNAVAILABLE) - else -> MoveToSparkUiState.Failed(MoveToSparkFailure.UNKNOWN) + override fun onCleared() { + manager.reset(screen) } } diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index a89ae3e49f..51cdac5b48 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -795,6 +795,7 @@ fun SendSheet( ) }, onPaymentSuccess = { paymentHash, amountWithFee -> + // A success shown before the send went pending is the same payment, so it shows again. appViewModel.onSendSuccess( NewTransactionSheetDetails( type = NewTransactionSheetType.LIGHTNING, @@ -802,6 +803,7 @@ fun SendSheet( paymentHashOrTxId = paymentHash, sats = amountWithFee, ), + allowDuplicateHash = true, ) }, onPaymentError = { failure -> diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index e238d7eee7..ef1abdcbac 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -26,6 +26,7 @@ import to.bitkit.repositories.WatchOnlyAccountRepo import to.bitkit.services.CoreService import to.bitkit.services.MigrationService import to.bitkit.services.PaykitSdkService +import to.bitkit.ui.settings.lightning.MoveToSparkManager import to.bitkit.utils.AppError import to.bitkit.utils.Logger import javax.inject.Inject @@ -58,6 +59,7 @@ class WipeWalletUseCase @Inject constructor( private val paykitReceiptRepo: PaykitReceiptRepo, private val connectionRecovery: WalletConnectionRecovery, private val wakeRepo: WakeRepo, + private val moveToSparkManager: Provider, ) { private val wipeMutex = Mutex() @@ -125,6 +127,7 @@ class WipeWalletUseCase @Inject constructor( blocktankRepo.resetState() activityRepo.resetState() hwWalletRepo.resetState() + moveToSparkManager.get().resetForWipe() resetWalletState() step("mark migration checked") { migrationService.markMigrationChecked() } return if (keychainWiped) Result.success(Unit) else Result.failure(WipeIncomplete()) diff --git a/app/src/main/java/to/bitkit/viewmodels/ActivityListViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/ActivityListViewModel.kt index a75003aa5a..f5ad42cfb2 100644 --- a/app/src/main/java/to/bitkit/viewmodels/ActivityListViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/ActivityListViewModel.kt @@ -21,6 +21,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update @@ -28,6 +29,7 @@ import kotlinx.coroutines.launch import to.bitkit.data.SettingsStore import to.bitkit.di.BgDispatcher import to.bitkit.ext.isFromHardwareWallet +import to.bitkit.ext.isMoveToSpark import to.bitkit.ext.isReplacedSentTransaction import to.bitkit.ext.isTransfer import to.bitkit.ext.rawId @@ -40,6 +42,7 @@ import to.bitkit.models.PubkyProfile import to.bitkit.models.WalletScope import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.HwWalletRepo +import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.PubkyRepo import to.bitkit.ui.screens.wallets.activity.components.ActivityTab import to.bitkit.utils.Logger @@ -49,6 +52,7 @@ import javax.inject.Inject class ActivityListViewModel @Inject constructor( @BgDispatcher private val bgDispatcher: CoroutineDispatcher, private val activityRepo: ActivityRepo, + private val moveToSparkRepo: MoveToSparkRepo, private val hwWalletRepo: HwWalletRepo, pubkyRepo: PubkyRepo, settingsStore: SettingsStore, @@ -226,9 +230,12 @@ class ActivityListViewModel @Inject constructor( return null } + val moveHashes = moveToSparkRepo.moveHashes.first() val filteredByTab = when (filters.tab) { - ActivityTab.OTHER -> activities.filter { it.isTransfer() } - ActivityTab.SENT, ActivityTab.RECEIVED -> activities.filterNot { it.isTransfer() } + ActivityTab.OTHER -> activities.filter { it.isTransfer() || it.isMoveToSpark(moveHashes) } + ActivityTab.SENT, ActivityTab.RECEIVED -> activities.filterNot { + it.isTransfer() || it.isMoveToSpark(moveHashes) + } else -> activities } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 81e87c67b2..7ab6f964c6 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7988,6 +7988,7 @@ class AppViewModel @Inject constructor( if (incomingPaymentRequest != null) refreshIncomingPaykitPaymentRequests() setSendEffect(SendEffect.NavigateToPending(pendingHash, displayAmountSats.toLong())) lnurlComment?.let { activityRepo.setLightningMessageIfEmpty(paymentHash, it) } + resolveSettledPendingSend(pendingHash) return@onFailure } releasePrivatePaymentListIfNeeded(contactPaymentContext) @@ -8007,6 +8008,27 @@ class AppViewModel @Inject constructor( } } + /** Resolves a pending send whose outcome was handled before it was tracked, which no later event resolves. */ + private suspend fun resolveSettledPendingSend(paymentHash: String) { + val event = lightningRepo.settledSparkSendEvent(paymentHash) ?: return + if (!pendingPaymentRepo.isPending(paymentHash)) return + when (event) { + is Event.PaymentSuccessful if event.paymentHash == paymentHash -> { + // The send screen may have moved on to another payment meanwhile, so only this send's contact counts. + syncContactForActivity(paymentHash, isPendingOnly = true) + pendingPaymentRepo.resolve(PendingPaymentResolution.Success(paymentHash, amountWithFeeSats = null)) + } + + is Event.PaymentFailed if event.paymentHash == paymentHash -> { + releaseFailedSwapHold(paymentHash) + clearPendingContactPaymentContext(paymentHash) + pendingPaymentRepo.resolve(PendingPaymentResolution.Failure(paymentHash, event.reason)) + } + + else -> Unit + } + } + private suspend fun savePendingLnurlComment(invoice: LightningInvoice, paymentHash: String): String? { val state = _sendUiState.value if (state.lnurl !is LnurlParams.LnurlPay || state.comment.isBlank()) return null @@ -8906,6 +8928,8 @@ class AppViewModel @Inject constructor( /** Receipt status by the payment's hash, txid or USDT transfer id, lowercase. */ val paykitReceiptStatuses get() = paykitReceiptRepo.statuses + val moveToSparkHashes get() = moveToSparkRepo.moveHashes + fun retryPaykitReceipt(paymentId: String) = viewModelScope.launch(bgDispatcher) { paykitReceiptRepo.retry(paymentId) } @@ -9601,17 +9625,19 @@ class AppViewModel @Inject constructor( private fun syncContactForActivity( paymentHashOrTxId: String, walletId: String = WalletScope.default, + isPendingOnly: Boolean = false, ) { val contactContext = synchronized(contactPaymentContextLock) { val pendingContext = pendingContactPaymentContexts.remove(paymentHashOrTxId) - val context = pendingContext ?: activeContactPaymentContext + val context = pendingContext ?: activeContactPaymentContext.takeUnless { isPendingOnly } if (pendingContext == null && context != null) { activeContactPaymentContext = null } if (preparedContactPaymentContext == context) preparedContactPaymentContext = null context } - isSubmittingPaymentRequest = false + // A pending send settling later leaves the send under way alone. + if (!isPendingOnly) isSubmittingPaymentRequest = false contactContext ?: return viewModelScope.launch { diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 5e507ea248..0b6c46ff54 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -58,6 +58,7 @@ import to.bitkit.repositories.WipeInProgressError import to.bitkit.services.BoltzService import to.bitkit.services.MigrationService import to.bitkit.ui.onboarding.LOADING_MS +import to.bitkit.ui.settings.lightning.MoveToSparkManager import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError import to.bitkit.utils.Logger @@ -84,6 +85,7 @@ class WalletViewModel @Inject constructor( private val connectionRecovery: WalletConnectionRecovery, private val pubkySwapsRouteRepo: PubkySwapsRouteRepo, sparkRepo: SparkRepo, + moveToSparkManager: MoveToSparkManager, ) : ViewModel() { companion object { private const val TAG = "WalletViewModel" @@ -104,6 +106,7 @@ class WalletViewModel @Inject constructor( val lightningState = lightningRepo.lightningState val sparkState = sparkRepo.state + val hasRetainedMove = moveToSparkManager.hasRetainedMove val walletState = walletRepo.walletState val balanceState = walletRepo.balanceState diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 6c21b02553..dbf2910d98 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -167,6 +167,31 @@ قابل للاستخدام أرصدة Lightning ارتفاع أرشفة مراقب القناة + المبلغ + سينتقل رصيدك إلى Spark عبر Lightning، وهي أقل طريقة رسومًا للإبقاء عليه في الإنفاق. رسوم التوجيه أدناه هي أقصى ما تدفعه. + النقل إلى\n<accent>Spark</accent> + جزء من رصيدك على Spark الآن. انقل الباقي بالطريقة نفسها، ثم أغلق الاتصال الذي فرغ. + رصيدك على Spark الآن. أغلق الاتصال الذي فرغ لإعادة احتياطيه إلى المدخرات. + تم النقل إلى\n<accent>Spark</accent> + لم يعد في اتصالات Lightning الخاصة بك رصيد للنقل. + Spark غير جاهز للاستلام بعد. حاول مرة أخرى بعد قليل. + تعذّر\n<accent>النقل</accent> + حدث خطأ أثناء تجهيز النقل. حاول مرة أخرى. + رسوم التوجيه + الدفعة في طريقها وستظهر في Spark بمجرد اكتمالها. إذا فشلت، يبقى المبلغ في اتصالك. + جارٍ النقل إلى\n<accent>Spark</accent> + يغلق Blocktank اتصالات Lightning الخاصة به. انقل رصيدك إلى Spark الآن: إنه الخيار الأقل رسومًا، ويبقى في الإنفاق. + اتصالك\n<accent>يُغلق</accent> + انقل النصف + انقل الآن + انقل الباقي + النقل إلى Spark + جارٍ البحث عن مسار ورسومه… + اسحب للنقل + أغلق الاتصال بدلًا من ذلك لإعادة الرصيد إلى المدخرات. + يمكنك نقله على أجزاء أصغر. + %1$s كبير جدًا بحيث لا يمكن توجيهه إلى Spark في دفعة واحدة. + المبلغ\n<accent>كبير جدًا</accent> حد HTLC الصادر التالي الحد الأدنى لـ HTLC الصادر التالي قبل أن تتمكن من تحويل الأموال من رصيد مدخراتك، تحتاج إلى إرسال Bitcoin إلى محفظة Bitkit الخاصة بك. @@ -209,8 +234,19 @@ تحويل\n<accent>إلى المدخرات</accent> يرجى الانتظار، جارٍ تحويل أموالك. يجب أن يستغرق هذا <accent>±10 ثوانٍ.</accent> الأموال\n<accent>قيد التحويل</accent> + فشل\n<accent>التحويل</accent> تعذّر التحويل إلى المدخرات وقت مزامنة درجات تحديد المسار + موافقة + <accent>رسوم التحويل السريع الآن ₿ {amount}.</accent> وافق للوصول إلى أموالك بسرعة، أو انتظر نحو 30 دقيقة. + تغيّرت رسوم\n<accent>التحويل السريع</accent> + جارٍ الإضافة إلى رصيد الإنفاق + تغيّرت رسوم التحويل السريع + استخدام سرعة التحويل العادية + رائع! + يرجى الانتظار، تحويل أموالك قيد التنفيذ. يستغرق هذا <accent>بضع دقائق.</accent> + يرجى الانتظار، تحويل أموالك قيد التنفيذ. يستغرق هذا <accent>نحو 30 دقيقة.</accent> + التحويل السريع\n<accent>غير متاح</accent> متابعة استخدام Bitkit جارٍ معالجة الدفع الدفع ناجح @@ -238,6 +274,7 @@ اكتمل\n<accent>التحويل</accent> عناوين رسوم الطوارئ السابقة استخدمت التحويلات القسرية السابقة عناوين رسوم الطوارئ هذه. تبقى العملات المتروكة في أحدها ملكك: أنفقها بعبارة الاسترداد ومسار الاشتقاق الخاص بها. + مسار الاشتقاق نقل مشغّلو Spark مبلغ {amount} على السلسلة ولم يعد على Spark. لا يزال بإمكان المشغّلين الإفراج عنه لك. يبقى {amount} على Spark. تعذّر استرداد أي شيء. @@ -331,17 +368,20 @@ المدخرات غير كافية المبلغ الذي يمكنك تحويله إلى رصيد الإنفاق محدود حاليًا بـ ₿ {amount}. الحد الأقصى لرصيد الإنفاق - حوّل أكثر من ₿ {amount} لتغطية رسوم إضافته إلى رصيد الإنفاق. - المبلغ صغير جدًا + يلزم حد أدنى قدره ₿ {amount} لإعداد رصيد الإنفاق. + الحد الأدنى لرصيد المدخرات 25% تحويل\n<accent>إلى الإنفاق</accent> إلى الإنفاق + تعذّر على Bitkit الحصول على رسوم هذا التحويل. تحقق من اتصالك وحاول مرة أخرى. تقديري أقصى الرسوم أعلى بمقدار {amount} لأن معدلات الرسوم أو رصيد مدخراتك تغيّر أثناء وجودك في هذه الشاشة. اسحب مرة أخرى للتأكيد. تغيّرت الرسوم جاهز خلال دقائق رسوم الخدمة + أقصى مبلغ يمكنك تحويله الآن هو {amount}، لأن معدلات الرسوم أو رصيد مدخراتك تغيّر أثناء وجودك في هذه الشاشة. اسحب مرة أخرى للتأكيد. + تغيّر المبلغ رسوم الشبكة جاهز خلال 30 دقيقة تقريبًا تعذّر على Bitkit الحصول على الرسوم الحالية لهذا التحويل. تحقق من اتصالك وحاول مرة أخرى. @@ -351,7 +391,7 @@ حوّل الأموال إلى رصيد الإنفاق للاستمتاع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار. تحويل\n<accent>إلى الإنفاق</accent> رصيد الإنفاق - Transfer\n<accent>speed</accent> + سرعة\n<accent>التحويل</accent> الحالة الدعم إجمالي احتياطي قنوات Anchor @@ -990,6 +1030,7 @@ {count, plural, one {إدخال} other {إدخالات (#)}} الفاتورة ملاحظة الفاتورة + النقل إلى Spark الشهر القادم لا يوجد نشاط بعد استلم بعض الأموال للبدء @@ -1069,6 +1110,7 @@ زِد الرسوم المخصصة وحاول مرة أخرى. ملاحظة تم استلام Bitcoin + لا يستطيع Bitkit التأكد من أن هذه الفاتورة لم تُدفع قبل استعادة محفظتك. يرجى طلب فاتورة جديدة. انقطع اتصال النظير. فشل إرسال الإيصال جارٍ إرسال الإيصال @@ -1080,7 +1122,7 @@ تم نسخ الفاتورة إلى الحافظة فاتورة Lightning ملاحظة اختيارية للدافع - استمتع بمعاملات فورية ورخيصة\nمع الأصدقاء والعائلة\nوالتجار. + استمتع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار. استلم على <accent>رصيد الإنفاق</accent> عرض التفاصيل عرض رمز QR @@ -1131,6 +1173,7 @@ الرصيد الاحتياطي ليس لدى جهة الاتصال هذه أي طريقة دفع يمكن لـ Bitkit استخدامها الآن. لا يمكن الدفع لجهة الاتصال هذه + لا يزال سحب سابق من رصيد الإنفاق قيد التسوية. حاول مرة أخرى بعد اكتماله. لم تعد التحويلات إلى رصيد الإنفاق متاحة. يتحقق Bitkit أولًا من الشبكة، ثم يعيد عملات هذا التحويل إلى محفظتك حتى لا يتأكد التحويل الأصلي أبدًا. يكلّف ذلك رسوم شبكة. QuickPay جارٍ دفع\n<accent>الفاتورة...</accent> @@ -1375,7 +1418,7 @@ بدأ التحويل وهو <accent>قيد التسوية على السلسلة</accent>. سيتم تحديث رصيد مدخراتك تلقائيًا عند اكتماله. التحويل\n<accent>في الطريق</accent> تعذّر نقل رصيدك المدعوم بـ Spark إلى المدخرات ويبقى في رصيد الإنفاق. - تعذّر نقل رصيد Spark إلى المدخرات ويبقى في رصيد الإنفاق. اتصالاتك قيد النقل إلى المدخرات. + أموال قنواتك في طريقها إلى المدخرات، لكن رصيد Spark الخاص بك تعذّر نقله ويبقى في رصيد الإنفاق. <accent>جارٍ الاتصال</accent>\nبالشبكة يرجى إعادة توصيل جهازك، يبدو أنه غير متصل بهاتفك. إعادة توصيل الجهاز 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 dde5edbdc1..5f7d70d29d 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -174,6 +174,31 @@ Es utilizable Saldos Lightning Altura de archivo del monitor de canal + Monto + Tu saldo pasa a Spark por Lightning, la forma de menor comisión para mantenerlo en Gastos. La comisión de enrutamiento de abajo es lo máximo que pagas. + Mover a\n<accent>Spark</accent> + Una parte de tu saldo ya está en Spark. Mueve el resto de la misma manera y luego cierra la conexión vacía. + Tu saldo ya está en Spark. Cierra la conexión vacía para devolver su reserva a Ahorros. + Movido a\n<accent>Spark</accent> + Tus conexiones Lightning ya no tienen saldo para mover. + Spark aún no está listo para recibir. Inténtalo de nuevo en un momento. + No se pudo\n<accent>mover</accent> + Algo salió mal al preparar el movimiento. Inténtalo de nuevo. + Comisión de enrutamiento + El pago está en camino y aparecerá en Spark cuando se complete. Si falla, el monto permanece en tu conexión. + Moviendo a\n<accent>Spark</accent> + Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción de menor comisión y se queda en Gastos. + Tu conexión\n<accent>se está cerrando</accent> + Mover la mitad + Mover ahora + Mover el resto + Mover a Spark + Buscando una ruta y su comisión… + Desliza para mover + Mejor cierra la conexión para devolver el saldo a Ahorros. + Puedes moverlo en partes más pequeñas. + %1$s es demasiado grande para enrutarse a Spark en un solo pago. + Monto\n<accent>demasiado grande</accent> Límite del próximo HTLC saliente Mínimo del próximo HTLC saliente Para transferir fondos a su saldo de ahorros, primero tiene que enviar bitcoin a su billetera Bitkit. @@ -216,8 +241,19 @@ Transferir\n<accent>a ahorros</accent> Espera un momento, tu transferencia está en proceso. Tomará aproximadamente <accent>10 segundos.</accent> Fondos\n<accent>en proceso</accent> + Transferencia\n<accent>fallida</accent> No se pudo transferir a ahorros Hora de sincronización de puntuaciones de ruta + Aprobar + <accent>La comisión de transferencia rápida ahora es ₿ {amount}.</accent> Aprueba para acceder a tus fondos rápidamente, o espera ±30 min. + Cambió la comisión de\n<accent>transferencia rápida</accent> + Agregando al saldo para gastos + Cambió la comisión de transferencia rápida + Usando velocidad de transferencia normal + ¡Genial! + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos minutos.</accent> + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos 30 minutos.</accent> + Transferencia rápida\n<accent>no disponible</accent> Continuar Usando Bitkit Procesando pago Pago Efectuado @@ -245,6 +281,7 @@ Transferencia\n<accent>completada</accent> Direcciones de comisiones de emergencia anteriores Las transferencias forzadas anteriores usaron estas direcciones de comisiones de emergencia. Las monedas que queden en una siguen siendo tuyas: gástalas con tu frase de recuperación y su ruta de derivación. + Ruta de derivación Los operadores de Spark movieron {amount} on-chain y ya no está en Spark. Los operadores aún pueden liberártelo. {amount} se queda en Spark. No se pudo recuperar nada. @@ -338,17 +375,20 @@ Ahorros insuficientes El monto que puedes transferir a tu saldo para gastar está limitado a ₿ {amount}. Saldo máximo de gastos - Transfiere más de ₿ {amount} para cubrir las comisiones de agregarlo a tu saldo para gastos. - Monto demasiado bajo + Se necesita un mínimo de ₿ {amount} para configurar tu saldo para gastos. + Mínimo del saldo de ahorros 25% Transferir\n<accent>a gastos</accent> Hacia Gastos + Bitkit no pudo obtener las comisiones de esta transferencia. Revisa tu conexión e inténtalo de nuevo. est. máx. Las comisiones son {amount} más altas porque las tarifas o su saldo de ahorros cambiaron mientras estaba en esta pantalla. Deslice de nuevo para confirmar. Las comisiones cambiaron Listo en unos minutos Comisión de servicio + Lo máximo que puedes transferir ahora es {amount}, porque las tarifas o tu saldo de ahorros cambiaron mientras estabas en esta pantalla. Desliza de nuevo para confirmar. + El monto cambió Comisiones de red Listo en unos 30 minutos Bitkit no pudo obtener las comisiones actuales de esta transferencia. Revisa tu conexión e inténtalo de nuevo. @@ -358,7 +398,7 @@ Transfiera fondos a su saldo de gastos para disfrutar de transacciones baratas e instantáneas con amigos y comercios. Transferir\n<accent>a gastos</accent> Saldo para gastos - Transfer\n<accent>speed</accent> + Velocidad de\n<accent>transferencia</accent> Estatus Soporte Reserva total de canales ancla @@ -1015,6 +1055,7 @@ {count, plural, one {ENTRADA} many {ENTRADAS (#)} other {ENTRADAS (#)}} Factura Nota de factura + Mover a Spark Mes siguiente Aún no hay actividad Reciba algunos fondos para empezar @@ -1099,6 +1140,7 @@ Aumente la tasa e inténtelo de nuevo. Nota Bitcoin recibido + Bitkit no puede confirmar que esta factura no se pagó antes de que restauraras tu billetera. Solicita una factura nueva. Par desconectado. Error al enviar el recibo Enviando recibo @@ -1110,7 +1152,7 @@ Factura copiada en el portapapeles Factura Lightning Nota opcional para el pagador - Disfruta transacciones instantáneas\ny baratas con amigos, familia\ny comercios. + Disfruta transacciones instantáneas y baratas con amigos, familia y comercios. Recibe en <accent>saldo de gastos</accent> Ver detalles Mostrar código QR @@ -1162,6 +1204,7 @@ Saldo de reserva Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. No se puede pagar a este contacto + Un retiro anterior de tu saldo para gastos aún se está liquidando. Inténtalo de nuevo cuando termine. Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero revisa la red y luego devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. Este pago está tardando un poco más de lo esperado. Puede seguir utilizando Bitkit. Pago pendiente @@ -1405,7 +1448,7 @@ Su transferencia se inició y se está <accent>liquidando onchain</accent>. Su saldo de ahorros se actualizará automáticamente cuando termine. Transferencia\n<accent>en camino</accent> Tu saldo con tecnología de Spark no pudo pasar a ahorros y se queda en tu saldo de gastos. - Tu saldo de Spark no pudo pasar a ahorros y se queda en tu saldo de gastos. Tus conexiones se están pasando a ahorros. + Los fondos de tus canales se están moviendo a ahorros, pero tu saldo de Spark no se pudo mover y permanece en tu saldo para gastos. <accent>Conectando</accent>\na la red Vuelva a conectar su dispositivo de hardware; parece que está desconectado de su teléfono. Reconectar dispositivo de hardware diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 5736b9778e..200e4ed905 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -171,6 +171,31 @@ És utilitzable Saldos Lightning Alçada d\'arxiu del monitor de canal + Import + El teu saldo passa a Spark per Lightning, la manera amb menys comissió de mantenir-lo a despesa. La comissió d\'encaminament de sota és el màxim que pagues. + Mou a\n<accent>Spark</accent> + Una part del teu saldo ja és a Spark. Mou la resta de la mateixa manera i després tanca la connexió buida. + El teu saldo ja és a Spark. Tanca la connexió buida per retornar-ne la reserva als estalvis. + Mogut a\n<accent>Spark</accent> + Les teves connexions Lightning ja no tenen saldo per moure. + Spark encara no està a punt per rebre. Torna-ho a provar d\'aquí a un moment. + No s\'ha pogut\n<accent>moure</accent> + Alguna cosa ha fallat en preparar el moviment. Torna-ho a provar. + Comissió d\'encaminament + El pagament està en camí i apareixerà a Spark quan es completi. Si falla, l\'import es queda a la teva connexió. + Movent a\n<accent>Spark</accent> + Blocktank tanca les seves connexions Lightning. Mou ara el teu saldo a Spark: és l\'opció amb menys comissió i es queda a despesa. + La teva connexió\n<accent>es tanca</accent> + Mou la meitat + Mou ara + Mou la resta + Moure a Spark + Cercant una ruta i la seva comissió… + Desplaça per moure + Tanca la connexió per retornar el saldo als estalvis. + Pots moure\'l en parts més petites. + %1$s és massa gran per encaminar-se a Spark en un sol pagament. + Import\n<accent>massa gran</accent> Límit del pròxim HTLC de sortida Mínim del pròxim HTLC de sortida Abans de poder transferir fons del teu saldo d\'estalvis, has d\'enviar bitcoin a la teva cartera Bitkit. @@ -213,8 +238,19 @@ Transferir\n<accent>a estalvis</accent> Si us plau, espera, la transferència de fons està en curs. Hauria de trigar <accent>±10 segons.</accent> Fons\n<accent>en transferència</accent> + Transferència\n<accent>fallida</accent> No s\'ha pogut transferir als estalvis Temps de sincronització de puntuacions de rutes + Aprova + <accent>La comissió de la transferència ràpida ara és ₿ {amount}.</accent> Aprova per accedir als teus fons ràpidament, o espera ±30 min. + Ha canviat la comissió de\n<accent>transferència ràpida</accent> + Afegint al saldo de despesa + Ha canviat la comissió de transferència ràpida + Usant velocitat de transferència normal + Genial! + Espera, la transferència dels teus fons està en curs. Hauria de trigar <accent>uns minuts.</accent> + Espera, la transferència dels teus fons està en curs. Hauria de trigar <accent>uns 30 minuts.</accent> + Transferència ràpida\n<accent>no disponible</accent> Continua utilitzant Bitkit Processant pagament Pagament realitzat amb èxit @@ -242,6 +278,7 @@ Transferència\n<accent>completada</accent> Adreces de comissions d\'emergència anteriors Les transferències forçoses anteriors van utilitzar aquestes adreces de comissions d\'emergència. Les monedes que quedin en una continuen sent teves: gasta-les amb la teva frase de recuperació i el seu camí de derivació. + Camí de derivació Els operadors de Spark han mogut {amount} on-chain i no és a Spark. Els operadors encara te\'l poden alliberar. {amount} es queda a Spark. No s\'ha pogut recuperar res. @@ -335,17 +372,20 @@ Estalvis insuficients L\'import que pots transferir al teu saldo de despesa està limitat a ₿ {amount}. Màxim del saldo de despesa - Transfereix més de ₿ {amount} perquè cobreixi les comissions d\'afegir-ho al teu saldo de despesa. - Import massa baix + Cal un mínim de ₿ {amount} per configurar el teu saldo de despesa. + Mínim del saldo d\'estalvis 25% Transferir\n<accent>a despesa</accent> A despesa + Bitkit no ha pogut obtenir les comissions d\'aquesta transferència. Comprova la connexió i torna-ho a provar. est. màx. Les tarifes són {amount} més altes perquè les taxes de tarifa o el teu saldo d\'estalvis han canviat mentre eres en aquesta pantalla. Torna a desplaçar per confirmar. Les tarifes han canviat A punt en pocs minuts Tarifes de servei + El màxim que pots transferir ara és {amount}, perquè les tarifes o el teu saldo d\'estalvis han canviat mentre eres en aquesta pantalla. Torna a desplaçar per confirmar. + L\'import ha canviat Tarifes de xarxa Llest en uns 30 minuts Bitkit no ha pogut obtenir les comissions actuals d\'aquesta transferència. Comprova la connexió i torna-ho a provar. @@ -355,7 +395,7 @@ Transfereix fons al teu saldo de despesa per gaudir de transaccions instantànies i barates amb amics, família i comerciants. Transferir\n<accent>a despesa</accent> Saldo de despesa - Transfer\n<accent>speed</accent> + Velocitat de\n<accent>transferència</accent> Estat Suport Reserva total de canals Anchor @@ -1009,6 +1049,7 @@ {count, plural, one {ENTRADA} other {ENTRADES (#)}} Factura Nota de la factura + Moure a Spark Mes següent Encara no hi ha cap activitat Rebi alguns fons per començar @@ -1093,6 +1134,7 @@ Augmenta la tarifa personalitzada i torna-ho a provar. Nota Rebut Bitcoin + Bitkit no pot confirmar que aquesta factura no es va pagar abans que restauressis la cartera. Sol·licita una factura nova. Parell desconnectat. No s\'ha pogut enviar el rebut S\'està enviant el rebut @@ -1104,7 +1146,7 @@ Factura copiada al porta-retalls Factura Lightning Nota opcional per al pagador - Gaudeix de transaccions instantànies i barates\namb amics, família\ni comerciants. + Gaudeix de transaccions instantànies i barates amb amics, família i comerciants. Rebre al <accent>saldo de despesa</accent> Mostrar detalls Mostra el codi QR @@ -1156,6 +1198,7 @@ Saldo de reserva Aquest contacte no té cap mètode de pagament que Bitkit pugui fer servir ara. No es pot pagar aquest contacte + Una retirada anterior del teu saldo de despesa encara s\'està liquidant. Torna-ho a provar quan es completi. Les transferències al saldo de despesa ja no estan disponibles. Bitkit primer comprova la xarxa i després retorna les monedes d\'aquesta transferència a la teva cartera perquè la transferència original no es pugui confirmar mai. Això té una comissió de xarxa. Pagament pendent QuickPay @@ -1399,7 +1442,7 @@ La teva transferència s\'ha iniciat i <accent>s\'està liquidant onchain</accent>. El teu saldo d\'estalvis s\'actualitzarà automàticament quan es completi. Transferència\n<accent>en camí</accent> El teu saldo amb tecnologia de Spark no s\'ha pogut moure als estalvis i es queda al teu saldo de despesa. - El saldo de Spark no s\'ha pogut moure a estalvis i es queda al saldo de despesa. Les teves connexions s\'estan movent a estalvis. + Els fons dels teus canals es mouen als estalvis, però el teu saldo de Spark no s\'ha pogut moure i es queda al teu saldo de despesa. <accent>Connectant</accent>\na la xarxa Torna a connectar el teu dispositiu de maquinari; sembla que s\'ha desconnectat del telèfon. Torna a connectar el dispositiu diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index e4627f480d..3f33af27d0 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -174,6 +174,31 @@ Je použitelný? Lightning zůstatky Archivní výška monitoru kanálu + Částka + Váš zůstatek se přesune do Spark přes Lightning, což je nejlevnější způsob, jak ho ponechat ve výdajích. Poplatek za směrování níže je nejvíc, co zaplatíte. + Přesun do\n<accent>Spark</accent> + Část vašeho zůstatku je nyní ve Spark. Zbytek přesuňte stejným způsobem a pak zavřete vyprázdněné spojení. + Váš zůstatek je nyní ve Spark. Zavřete vyprázdněné spojení, aby se jeho rezerva vrátila do úspor. + Přesunuto do\n<accent>Spark</accent> + Vaše spojení Lightning už nemají žádný zůstatek k přesunu. + Spark ještě není připraven přijímat. Zkuste to za chvíli znovu. + Přesun se\n<accent>nezdařil</accent> + Při přípravě přesunu se něco pokazilo. Zkuste to znovu. + Poplatek za směrování + Platba je na cestě a po dokončení se zobrazí ve Spark. Pokud selže, částka zůstane ve vašem spojení. + Přesun do\n<accent>Spark</accent> + Blocktank zavírá svá spojení Lightning. Přesuňte svůj zůstatek do Spark hned: je to nejlevnější možnost a zůstane ve výdajích. + Vaše spojení\n<accent>se zavírá</accent> + Přesunout polovinu + Přesunout hned + Přesunout zbytek + Přesun do Spark + Hledání trasy a jejího poplatku… + Přejetím přesunout + Místo toho zavřete spojení, aby se zůstatek vrátil do úspor. + Můžete ho přesunout po menších částech. + %1$s je příliš velká částka na směrování do Spark jednou platbou. + Částka je\n<accent>příliš velká</accent> Limit dalšího odchozího HTLC Min dalšího odchozího HTLC Než budete moci převést prostředky ze svého zůstatku na spořicím účtu, musíte poslat bitcoiny do peněženky Bitkit. @@ -216,8 +241,19 @@ Převést\n<accent>do úspor</accent> Počkejte prosím, probíhá převod finančních prostředků. To by mělo trvat <accent>±10 sekund.</accent> Finanční prostředky\n<accent>v převodu</accent> + Převod\n<accent>se nezdařil</accent> Převod do úspor se nezdařil Čas synchronizace skóre hledání cest + Schválit + <accent>Poplatek za rychlý převod je nyní ₿ {amount}.</accent> Schvalte pro rychlý přístup k prostředkům, nebo počkejte ±30 min. + Poplatek za rychlý převod\n<accent>se změnil</accent> + Přidávání do zůstatku pro výdaje + Poplatek za rychlý převod se změnil + Použití běžné rychlosti převodu + Skvělé! + Počkejte prosím, převod vašich prostředků probíhá. Mělo by to trvat <accent>několik minut.</accent> + Počkejte prosím, převod vašich prostředků probíhá. Mělo by to trvat <accent>asi 30 minut.</accent> + Rychlý převod\n<accent>není dostupný</accent> Pokračujte v používání Bitkit Zpracování platby Platba úspěšně proběhla @@ -245,6 +281,7 @@ Převod\n<accent>dokončen</accent> Dřívější adresy pro nouzové poplatky Dřívější vynucené převody používaly tyto adresy pro nouzové poplatky. Mince, které na nich zůstaly, jsou stále vaše: utratíte je pomocí své obnovovací fráze a její derivační cesty. + Derivační cesta {amount} přesunuli operátoři Sparku on-chain a není na Spark. Operátoři vám je stále mohou uvolnit. {amount} zůstává na Spark. Nic se nepodařilo získat zpět. @@ -338,17 +375,20 @@ Nedostatečné úspory Částka, kterou můžete převést na svůj disponibilní zůstatek, je v současné době omezena na ₿ {amount}. Maximální disponibilní zůstatek - Převeď více než ₿ {amount}, aby to pokrylo poplatky za přidání do zůstatku pro výdaje. - Příliš malá částka + K nastavení zůstatku pro výdaje je potřeba minimálně ₿ {amount}. + Minimální zůstatek úspor 25% Převést\n<accent>do výdajů</accent> Do výdajů + Bitkit nedokázal získat poplatky za tento převod. Zkontrolujte připojení a zkuste to znovu. odh. max. Poplatky jsou o {amount} vyšší, protože se během zobrazení této obrazovky změnily sazby poplatků nebo zůstatek vašich úspor. Pro potvrzení přejeďte znovu. Poplatky se změnily Hotovo za pár minut Poplatky za služby + Nejvíc, co nyní můžete převést, je {amount}, protože se během zobrazení této obrazovky změnily sazby poplatků nebo zůstatek vašich úspor. Pro potvrzení přejeďte znovu. + Částka se změnila Síťové poplatky Připraveno asi za 30 minut Bitkit nedokázal získat aktuální poplatky za tento převod. Zkontroluj připojení a zkus to znovu. @@ -358,7 +398,7 @@ Převeďte peníze na svůj disponibilní zůstatek a využívejte okamžité a levné transakce s přáteli, rodinou a obchodníky. Převést\n<accent>do výdajů</accent> Disponibilní zůstatek - Transfer\n<accent>speed</accent> + Rychlost\n<accent>převodu</accent> Status Podpora Celková rezerva kotevních kanálů @@ -1013,6 +1053,7 @@ {count, plural, one {INPUT} few {VSTUPY (#)} many {VSTUPY (#)} other {VSTUPY (#)}} Faktura Poznámka k faktuře + Přesun do Spark Další měsíc Zatím žádná aktivita Získejte finanční prostředky, abyste mohli začít @@ -1097,6 +1138,7 @@ Zvyšte vlastní poplatek a zkuste to znovu. Poznámka bitcoin přijatý + Bitkit nemůže potvrdit, že tato faktura nebyla zaplacena před obnovením vaší peněženky. Požádejte prosím o novou fakturu. Peer odpojen. Odeslání potvrzení selhalo Odesílání potvrzení @@ -1108,7 +1150,7 @@ Faktura zkopírovaná do schránky Lightningová faktura Nepovinná poznámka pro plátce - Užívejte si okamžité a levné\ntransakce s přáteli, rodinou\na obchodníky. + Užívejte si okamžité a levné transakce s přáteli, rodinou a obchodníky. Přijímat na disponibilní zůstatek Zobrazit podrobnosti Zobrazit QR kód @@ -1160,6 +1202,7 @@ Zůstatek rezervy Tento kontakt nemá žádnou platební metodu, kterou by Bitkit mohl nyní použít. Tomuto kontaktu nelze zaplatit + Dřívější výběr z vašeho zůstatku pro výdaje se stále vypořádává. Zkuste to znovu, až se dokončí. Převody na útratový zůstatek už nejsou dostupné. Bitkit nejprve zkontroluje síť a pak vrátí mince tohoto převodu do vaší peněženky, aby se původní převod nikdy nepotvrdil. Stojí to síťový poplatek. Tato platba trvá o něco déle, než se očekávalo. Bitkit můžete používat i nadále. Platba čeká na vyřízení @@ -1403,7 +1446,7 @@ Váš převod byl zahájen a <accent>vypořádává se on-chain</accent>. Zůstatek vašich úspor se po dokončení automaticky aktualizuje. Převod\n<accent>je na cestě</accent> Váš zůstatek ve Spark se nepodařilo přesunout do úspor a zůstává ve výdajovém zůstatku. - Zůstatek Spark se nepodařilo přesunout do úspor a zůstává ve výdajovém zůstatku. Vaše spojení se přesouvají do úspor. + Prostředky z vašich kanálů se přesouvají do úspor, ale váš zůstatek ve Spark se nepodařilo přesunout a zůstává ve zůstatku pro výdaje. <accent>Připojování</accent>\nk síti Připojte prosím znovu své hardwarové zařízení, zdá se, že je od telefonu odpojené. Znovu připojte hardwarové zařízení diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 24631a0cb8..bae085bd48 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -102,7 +102,43 @@ Anderes Wallet verwenden Von HW-Wallet übertragen Am einfachsten ist es, deine Bitkit-Ersparnisse zu verwenden oder Bitcoin von einer anderen Wallet zu senden. + Betrag + Dein Guthaben wird über Lightning zu Spark verschoben, der gebührengünstigsten Möglichkeit, es in den Ausgaben zu behalten. Die Routing-Gebühr unten ist das Maximum, das du zahlst. + Zu\n<accent>Spark</accent> verschieben + Ein Teil deines Guthabens ist jetzt auf Spark. Verschiebe den Rest auf dieselbe Weise und schließe dann die geleerte Verbindung. + Dein Guthaben ist jetzt auf Spark. Schließe die geleerte Verbindung, um ihre Reserve zurück aufs Sparkonto zu holen. + Zu\n<accent>Spark</accent> verschoben + Deine Lightning-Verbindungen haben kein Guthaben mehr zum Verschieben. + Spark ist noch nicht bereit zum Empfangen. Versuche es gleich noch einmal. + Verschieben\n<accent>fehlgeschlagen</accent> + Beim Vorbereiten des Verschiebens ist etwas schiefgelaufen. Versuche es erneut. + Routing-Gebühr + Die Zahlung ist unterwegs und erscheint in Spark, sobald sie abgeschlossen ist. Schlägt sie fehl, bleibt der Betrag in deiner Verbindung. + Verschiebe zu\n<accent>Spark</accent> + Blocktank schließt seine Lightning-Verbindungen. Verschiebe dein Guthaben jetzt zu Spark: Das ist die gebührengünstigste Option, und es bleibt in den Ausgaben. + Deine Verbindung\n<accent>wird geschlossen</accent> + Hälfte verschieben + Jetzt verschieben + Rest verschieben + Zu Spark verschieben + Route und Gebühr werden gesucht… + Swipe zum Verschieben + Schließe stattdessen die Verbindung, um das Guthaben aufs Sparkonto zurückzuholen. + Du kannst es in kleineren Teilen verschieben. + %1$s ist zu groß, um in einer Zahlung zu Spark geroutet zu werden. + Betrag\n<accent>zu groß</accent> + Übertragung\n<accent>fehlgeschlagen</accent> Übertragung auf das Sparkonto fehlgeschlagen + Genehmigen + <accent>Die Gebühr für die schnelle Übertragung beträgt jetzt ₿ {amount}.</accent> Genehmige, um schnell auf deine Gelder zuzugreifen, oder warte ±30 Min. + Gebühr für schnelle Übertragung\n<accent>geändert</accent> + Zum Ausgabenguthaben hinzufügen + Gebühr für schnelle Übertragung geändert + Normale Übertragungsgeschwindigkeit wird verwendet + Super! + Bitte warte, die Übertragung deiner Gelder läuft. Das sollte <accent>einige Minuten</accent> dauern. + Bitte warte, die Übertragung deiner Gelder läuft. Das sollte <accent>etwa 30 Minuten</accent> dauern. + Schnelle Übertragung\n<accent>nicht verfügbar</accent> Spark Einlösegebühr %1$d/3 Bestätigungen @@ -127,6 +163,7 @@ Übertragung\n<accent>abgeschlossen</accent> Frühere Adressen für Notfallgebühren Frühere forcierte Übertragungen haben diese Adressen für Notfallgebühren verwendet. Coins, die bei einer verbleiben, gehören weiterhin dir: Gib sie mit deiner Wiederherstellungsphrase und ihrem Ableitungspfad aus. + Ableitungspfad {amount} wurde von den Spark-Betreibern on-chain verschoben und ist nicht auf Spark. Die Betreiber können es dir weiterhin freigeben. {amount} bleibt auf Spark. Es konnte nichts zurückgeholt werden. @@ -219,8 +256,11 @@ Von Sparkonto übertragen Manuelle Einrichtung <accent>zu den Ausgaben</accent> + Bitkit konnte die Gebühren für diese Übertragung nicht abrufen. Prüfe deine Verbindung und versuche es erneut. ca. max. + Du kannst jetzt höchstens {amount} übertragen, weil sich die Gebührensätze oder dein Sparguthaben geändert haben, während du auf diesem Bildschirm warst. Wische erneut, um zu bestätigen. + Betrag geändert Bereit in etwa 30 Minuten Übertrage Guthaben Bitte\n<accent>bestätige</accent> @@ -230,8 +270,8 @@ Trezor Connect öffnen 25% Maximaler Ausgabensaldo - Überweise mehr als ₿ {amount}, damit die Gebühren für dein Ausgabenguthaben gedeckt sind. - Betrag zu klein + Mindestens ₿ {amount} sind nötig, um dein Ausgabenguthaben einzurichten. + Mindestguthaben Sparkonto Der Betrag, den du auf dein Ausgabenkonto übertragen kannst, ist derzeit auf ₿ {amount} begrenzt. Netzgebühren Bitkit konnte die aktuellen Gebühren für diese Überweisung nicht abrufen. Prüfe deine Verbindung und versuche es erneut. @@ -285,7 +325,7 @@ Unzureichendes Sparguthaben Sparkonto Ausgabenguthaben - Transfer\n<accent>speed</accent> + Übertragungs-\n<accent>geschwindigkeit</accent> Empfangskapazität Lightning Node LDK Node ID @@ -380,7 +420,7 @@ Gesamt Onchain ÜBERTRAGUNG LÄUFT Los geht\'s - Spending\n<accent>Balance</accent> + Ausgaben-\n<accent>guthaben</accent> Bitte warte bis sich Bitkit mit dem Zahlungsnetzwerk verbunden hat (±10 Sekunden). Bitte warte bis sich Bitkit mit dem Bitcoin-Netzwerk verbunden hat (±10 Sekunden). Wallet-Guthaben @@ -975,6 +1015,7 @@ Zieladresse Ins Netzwerk {network} Netzübergreifende Zustellung verfolgen + Zu Spark verschieben Wallet Aktivität Kontakte @@ -984,6 +1025,7 @@ Einstellungen App Status Support + Bitkit kann nicht bestätigen, dass diese Rechnung nicht bezahlt wurde, bevor du deine Wallet wiederhergestellt hast. Bitte fordere eine neue Rechnung an. Beleg konnte nicht gesendet werden Beleg wird gesendet Beleg gesendet @@ -992,6 +1034,7 @@ Bitcoin senden Dieser Kontakt hat derzeit keine Zahlungsmethode, die Bitkit nutzen kann. Zahlung an diesen Kontakt nicht möglich + Eine frühere Auszahlung von deinem Ausgabenguthaben wird noch abgewickelt. Versuche es erneut, sobald sie abgeschlossen ist. Überweisungen auf dein Ausgabenguthaben sind nicht mehr verfügbar. Bitkit prüft zuerst das Netzwerk und schickt die Coins dieser Überweisung dann zurück in deine Wallet, damit die ursprüngliche Überweisung nie bestätigt wird. Dafür fällt eine Netzwerkgebühr an. An Kontakt @@ -1099,7 +1142,7 @@ QR-Code anzeigen Lightning-Gelder empfangen Empfangen auf <accent>Ausgabenguthaben</accent> - Genieße sofortige und günstige\nTransaktionen mit Freunden, Familie\nund Händlern. + Genieße sofortige und günstige Transaktionen mit Freunden, Familie und Händlern. Details anzeigen Auto Sparkonto @@ -1400,7 +1443,7 @@ Deine Übertragung wurde gestartet und wird <accent>onchain abgewickelt</accent>. Dein Sparguthaben wird automatisch aktualisiert, sobald sie abgeschlossen ist. Übertragung\n<accent>unterwegs</accent> Dein Spark-Guthaben konnte nicht auf dein Sparkonto verschoben werden und bleibt in deinem Ausgabenguthaben. - Dein Spark-Guthaben konnte nicht in die Ersparnisse verschoben werden und bleibt im Ausgabenguthaben. Deine Verbindungen werden in die Ersparnisse verschoben. + Deine Kanalgelder werden aufs Sparkonto verschoben, aber dein Spark-Guthaben konnte nicht verschoben werden und bleibt in deinem Ausgabenguthaben. <accent>Verbinde</accent>\nmit Netzwerk Bitte verbinde dein Hardware-Gerät erneut, es scheint von deinem Telefon getrennt zu sein. Hardware-Gerät neu verbinden diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 790f3fc748..bc73f69bcc 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -154,7 +154,7 @@ Αναγκαστική μεταφορά Δεν ήταν δυνατή η έναρξη της μεταφοράς. Θέλεις να επιβάλεις αυτή τη μεταφορά; Δεν θα μπορείς να χρησιμοποιήσεις αυτά τα κεφάλαια για ±14 ημέρες (!) Αναγκαστική\n<accent>μεταφορά</accent> - Μεταφορά από αποταμιεύσεις + Μεταφορά από Αποταμιεύσεις Χρήση άλλου πορτοφολιού Μεταφορά από πορτοφόλι HW Υπόλοιπο δαπανών @@ -167,6 +167,31 @@ Είναι χρησιμοποιήσιμο Υπόλοιπα Lightning Ύψος αρχειοθέτησης παρακολούθησης καναλιού + Ποσό + Το υπόλοιπό σου μεταφέρεται στο Spark μέσω Lightning, τον τρόπο με τα χαμηλότερα τέλη για να παραμείνει στις Δαπάνες. Τα τέλη δρομολόγησης παρακάτω είναι το μέγιστο που πληρώνεις. + Μεταφορά στο\n<accent>Spark</accent> + Μέρος του υπολοίπου σου βρίσκεται πλέον στο Spark. Μετάφερε το υπόλοιπο με τον ίδιο τρόπο και μετά κλείσε την άδεια σύνδεση. + Το υπόλοιπό σου βρίσκεται πλέον στο Spark. Κλείσε την άδεια σύνδεση για να επιστρέψει το απόθεμά της στις Αποταμιεύσεις. + Μεταφέρθηκε στο\n<accent>Spark</accent> + Οι συνδέσεις Lightning σου δεν έχουν πλέον υπόλοιπο για μεταφορά. + Το Spark δεν είναι ακόμη έτοιμο να λάβει. Δοκίμασε ξανά σε λίγο. + Αδυναμία\n<accent>μεταφοράς</accent> + Κάτι πήγε στραβά κατά την προετοιμασία της μεταφοράς. Δοκίμασε ξανά. + Τέλη δρομολόγησης + Η πληρωμή βρίσκεται καθ\'οδόν και θα εμφανιστεί στο Spark μόλις διακανονιστεί. Αν αποτύχει, το ποσό παραμένει στη σύνδεσή σου. + Μεταφορά στο\n<accent>Spark</accent> + Το Blocktank κλείνει τις συνδέσεις Lightning του. Μετάφερε τώρα το υπόλοιπό σου στο Spark: είναι η επιλογή με τα χαμηλότερα τέλη και παραμένει στις Δαπάνες. + Η σύνδεσή σου\n<accent>κλείνει</accent> + Μεταφορά του μισού + Μεταφορά τώρα + Μεταφορά του υπολοίπου + Μεταφορά στο Spark + Αναζήτηση διαδρομής και των τελών της… + Σύρε για μεταφορά + Κλείσε αντί γι\' αυτό τη σύνδεση για να επιστρέψει το υπόλοιπο στις Αποταμιεύσεις. + Μπορείς να το μεταφέρεις σε μικρότερα μέρη. + Το %1$s είναι πολύ μεγάλο για να δρομολογηθεί στο Spark με μία πληρωμή. + Πολύ μεγάλο\n<accent>ποσό</accent> Όριο επόμενου εξερχόμενου HTLC Ελάχιστο επόμενο εξερχόμενο HTLC Πριν μπορέσεις να μεταφέρεις κεφάλαια από το υπόλοιπο αποταμιεύσεων, πρέπει να στείλεις bitcoin στο πορτοφόλι Bitkit. @@ -209,8 +234,19 @@ Μεταφορά\n<accent>σε αποταμιεύσεις</accent> Περίμενε, η μεταφορά κεφαλαίων σου είναι σε εξέλιξη. Αυτό θα διαρκέσει <accent>±10 δευτερόλεπτα.</accent> Κεφάλαια\n<accent>σε μεταφορά</accent> + Η μεταφορά\n<accent>απέτυχε</accent> Η μεταφορά στις αποταμιεύσεις απέτυχε Χρόνος συγχρονισμού βαθμολογιών εύρεσης διαδρομής + Έγκριση + <accent>Τα τέλη γρήγορης μεταφοράς είναι τώρα ₿ {amount}.</accent> Έγκρινε για γρήγορη πρόσβαση στα κεφάλαιά σου ή περίμενε ±30 λεπτά. + Τα τέλη γρήγορης μεταφοράς\n<accent>άλλαξαν</accent> + Προσθήκη στο υπόλοιπο δαπανών + Τα τέλη γρήγορης μεταφοράς άλλαξαν + Χρήση κανονικής ταχύτητας μεταφοράς + Φοβερό! + Περίμενε, η μεταφορά των κεφαλαίων σου βρίσκεται σε εξέλιξη. Θα διαρκέσει <accent>λίγα λεπτά.</accent> + Περίμενε, η μεταφορά των κεφαλαίων σου βρίσκεται σε εξέλιξη. Θα διαρκέσει <accent>περίπου 30 λεπτά.</accent> + Η γρήγορη μεταφορά\n<accent>δεν είναι διαθέσιμη</accent> Συνέχισε να χρησιμοποιείς το Bitkit Επεξεργασία πληρωμής Επιτυχής πληρωμή @@ -238,6 +274,7 @@ Η μεταφορά\n<accent>ολοκληρώθηκε</accent> Προηγούμενες διευθύνσεις έκτακτων τελών Οι προηγούμενες αναγκαστικές μεταφορές χρησιμοποίησαν αυτές τις διευθύνσεις έκτακτων τελών. Τα νομίσματα που έμειναν σε μία παραμένουν δικά σας: ξοδέψτε τα με τη φράση ανάκτησής σας και τη διαδρομή παραγωγής της. + Διαδρομή παραγωγής {amount} μεταφέρθηκαν on-chain από τους διαχειριστές του Spark και δεν βρίσκονται στο Spark. Οι διαχειριστές μπορούν ακόμα να σας τα αποδεσμεύσουν. {amount} παραμένουν στο Spark. Δεν ήταν δυνατή η ανάκτηση τίποτα. @@ -331,17 +368,20 @@ Ανεπαρκείς αποταμιεύσεις Το ποσό που μπορείς να μεταφέρεις στο υπόλοιπο δαπανών περιορίζεται προς το παρόν σε ₿ {amount}. Μέγιστο υπόλοιπο δαπανών - Μετέφερε περισσότερα από ₿ {amount}, ώστε να καλύπτονται οι χρεώσεις για την προσθήκη στο υπόλοιπο δαπανών σου. - Πολύ μικρό ποσό + Απαιτείται ελάχιστο ποσό ₿ {amount} για τη ρύθμιση του υπολοίπου δαπανών σου. + Ελάχιστο υπόλοιπο αποταμίευσης 25% Μεταφορά\n<accent>σε δαπάνες</accent> Σε δαπάνες + Το Bitkit δεν μπόρεσε να λάβει τα τέλη για αυτή τη μεταφορά. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. εκτ. μέγ. Τα τέλη είναι {amount} υψηλότερα, επειδή τα ποσοστά τελών ή το υπόλοιπο αποταμιεύσεων άλλαξαν ενώ ήσουν σε αυτή την οθόνη. Σύρε ξανά για επιβεβαίωση. Τα τέλη άλλαξαν Έτοιμο σε λίγα λεπτά Τέλη υπηρεσίας + Το μέγιστο που μπορείς να μεταφέρεις είναι τώρα {amount}, επειδή άλλαξαν τα επίπεδα τελών ή το υπόλοιπο αποταμίευσής σου ενώ ήσουν σε αυτή την οθόνη. Σύρε ξανά για επιβεβαίωση. + Το ποσό άλλαξε Τέλη δικτύου Έτοιμο σε περίπου 30 λεπτά Το Bitkit δεν μπόρεσε να λάβει τις τρέχουσες χρεώσεις για αυτή τη μεταφορά. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. @@ -351,7 +391,7 @@ Μετέφερε κεφάλαια στο υπόλοιπο δαπανών για να απολαύσεις άμεσες και φθηνές συναλλαγές με φίλους, οικογένεια και εμπόρους. Μεταφορά\n<accent>σε δαπάνες</accent> Υπόλοιπο δαπανών - Transfer\n<accent>speed</accent> + Ταχύτητα\n<accent>μεταφοράς</accent> Κατάσταση Υποστήριξη Συνολικό αποθεματικό anchor καναλιών @@ -991,6 +1031,7 @@ {count, plural, one {ΕΙΣΟΔΟΣ} other {ΕΙΣΟΔΟΙ (#)}} Τιμολόγιο Σημείωση τιμολογίου + Μεταφορά στο Spark Επόμενος μήνας Καμία δραστηριότητα ακόμα Λάβε κεφάλαια για να ξεκινήσεις @@ -1074,6 +1115,7 @@ Αύξησε το προσαρμοσμένο τέλος και δοκίμασε ξανά. Σημείωση Ελήφθησαν Bitcoin + Το Bitkit δεν μπορεί να επιβεβαιώσει ότι αυτό το τιμολόγιο δεν πληρώθηκε πριν επαναφέρεις το πορτοφόλι σου. Ζήτησε νέο τιμολόγιο. Ο ομότιμος αποσυνδέθηκε. Η αποστολή της απόδειξης απέτυχε Αποστολή απόδειξης @@ -1085,7 +1127,7 @@ Το τιμολόγιο αντιγράφηκε στο πρόχειρο Τιμολόγιο Lightning Προαιρετική σημείωση προς τον πληρωτή - Απόλαυσε άμεσες και φθηνές\nσυναλλαγές με φίλους, οικογένεια\nκαι εμπόρους. + Απόλαυσε άμεσες και φθηνές συναλλαγές με φίλους, οικογένεια και εμπόρους. Λήψη σε <accent>υπόλοιπο δαπανών</accent> Εμφάνιση λεπτομερειών Εμφάνιση κωδικού QR @@ -1136,6 +1178,7 @@ Αποθεματικό υπόλοιπο Αυτή η επαφή δεν έχει τρόπο πληρωμής που μπορεί να χρησιμοποιήσει το Bitkit αυτή τη στιγμή. Δεν είναι δυνατή η πληρωμή αυτής της επαφής + Μια προηγούμενη ανάληψη από το υπόλοιπο δαπανών σου διακανονίζεται ακόμη. Δοκίμασε ξανά μόλις ολοκληρωθεί. Οι μεταφορές στο υπόλοιπο δαπανών δεν είναι πλέον διαθέσιμες. Το Bitkit ελέγχει πρώτα το δίκτυο και μετά επιστρέφει τα νομίσματα αυτής της μεταφοράς στο πορτοφόλι σας, ώστε η αρχική μεταφορά να μην επιβεβαιωθεί ποτέ. Αυτό έχει χρέωση δικτύου. QuickPay Πληρωμή\n<accent>τιμολογίου...</accent> @@ -1381,7 +1424,7 @@ Η μεταφορά σου ξεκίνησε και <accent>εκκαθαρίζεται onchain</accent>. Το υπόλοιπο αποταμιεύσεων θα ενημερωθεί αυτόματα μόλις ολοκληρωθεί. Η μεταφορά\n<accent>είναι καθ\' οδόν</accent> Το υπόλοιπό σας στο Spark δεν μεταφέρθηκε στις αποταμιεύσεις και παραμένει στο υπόλοιπο δαπανών. - Το υπόλοιπο Spark δεν μεταφέρθηκε στις αποταμιεύσεις και παραμένει στο υπόλοιπο δαπανών. Οι συνδέσεις σας μεταφέρονται στις αποταμιεύσεις. + Τα κεφάλαια του καναλιού σου μεταφέρονται στις αποταμιεύσεις, αλλά το υπόλοιπό σου στο Spark δεν μπόρεσε να μεταφερθεί και παραμένει στο υπόλοιπο δαπανών σου. <accent>Σύνδεση</accent>\nστο δίκτυο Σύνδεσε ξανά τη συσκευή υλικού σου, φαίνεται ότι αποσυνδέθηκε από το τηλέφωνό σου. Επανασύνδεση συσκευής υλικού diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 6854976c7c..c17a93ab16 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -160,7 +160,7 @@ Fuerzar transferencia No se ha podido iniciar la transferencia. ¿Desea forzar esta transferencia? No podrá utilizar estos fondos durante ±14 días (!) Forzar\n<accent>Transferencia</accent> - Transferir desde Ahorros + Transferir desde Ahorro Usar otro monedero Transferir desde billetera HW Saldo de gastos @@ -173,6 +173,31 @@ ¿Es utilizable? Saldos Lightning Altura de archivo del monitor de canales + Importe + Tu saldo se mueve a Spark por Lightning, la forma de menor comisión de mantenerlo en Gasto. La comisión de enrutamiento de abajo es lo máximo que pagas. + Mover a\n<accent>Spark</accent> + Una parte de tu saldo ya está en Spark. Mueve el resto de la misma forma y luego cierra la conexión vacía. + Tu saldo ya está en Spark. Cierra la conexión vacía para devolver su reserva a Ahorro. + Movido a\n<accent>Spark</accent> + Tus conexiones Lightning ya no tienen saldo que mover. + Spark aún no está listo para recibir. Inténtalo de nuevo en un momento. + No se pudo\n<accent>mover</accent> + Algo salió mal al preparar el movimiento. Inténtalo de nuevo. + Comisión de enrutamiento + El pago está en camino y aparecerá en Spark cuando se liquide. Si falla, el importe permanece en tu conexión. + Moviendo a\n<accent>Spark</accent> + Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción de menor comisión y se mantiene en Gasto. + Tu conexión\n<accent>se está cerrando</accent> + Mover la mitad + Mover ahora + Mover el resto + Mover a Spark + Buscando una ruta y su comisión… + Desliza para mover + Cierra la conexión en su lugar para devolver el saldo a Ahorro. + Puedes moverlo en partes más pequeñas. + %1$s es demasiado grande para enrutarse a Spark en un solo pago. + Importe\n<accent>demasiado grande</accent> Límite del siguiente HTLC saliente Mínimo del siguiente HTLC saliente Antes de que pueda transferir fondos a su saldo de ahorros, tiene que enviar bitcoin a su monedero Bitkit. @@ -215,8 +240,19 @@ Transferir\n<accent>a ahorros</accent> Por favor espera, tu transferencia de fondos está en curso. Debería tardar <accent>±10 segundos.</accent> Fondos\n<accent>en transferencia</accent> + Transferencia\n<accent>fallida</accent> No se pudo transferir a ahorros Hora de sincronización de puntuaciones de rutas + Aprobar + <accent>La comisión de transferencia rápida ahora es ₿ {amount}.</accent> Aprueba para acceder a tus fondos rápidamente, o espera ±30 min. + Comisión de transferencia rápida\n<accent>modificada</accent> + Añadiendo al saldo de gasto + Comisión de transferencia rápida modificada + Usando velocidad de transferencia normal + ¡Genial! + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos minutos.</accent> + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos 30 minutos.</accent> + Transferencia rápida\n<accent>no disponible</accent> Continuar Usando Bitkit Procesando Pago Pago exitoso @@ -244,6 +280,7 @@ Transferencia\n<accent>completada</accent> Direcciones de comisiones de emergencia anteriores Las transferencias forzadas anteriores usaron estas direcciones de comisiones de emergencia. Las monedas que queden en una siguen siendo tuyas: gástalas con tu frase de recuperación y su ruta de derivación. + Ruta de derivación Los operadores de Spark han movido {amount} on-chain y ya no está en Spark. Los operadores aún pueden liberártelo. {amount} se queda en Spark. No se pudo recuperar nada. @@ -337,17 +374,20 @@ Ahorros Insuficientes La cantidad que puedes transferir a tu saldo de gasto está actualmente limitada a ₿ {amount}. Máximo del saldo de gasto - Transfiera más de ₿ {amount} para cubrir las comisiones de añadirlo a su saldo para gastos. - Importe demasiado bajo + Se necesita un mínimo de ₿ {amount} para configurar tu saldo de gasto. + Saldo mínimo de ahorro 25% Transferir\n<accent>a gasto</accent> A gasto + Bitkit no pudo obtener las comisiones de esta transferencia. Revisa tu conexión e inténtalo de nuevo. est. máx. Las comisiones son {amount} más altas porque las tasas de comisión o tu saldo de ahorro cambiaron mientras estabas en esta pantalla. Desliza de nuevo para confirmar. Las comisiones han cambiado Listo en unos minutos Comisión de servicio + Lo máximo que puedes transferir ahora es {amount}, porque las tarifas de comisión o tu saldo de ahorro cambiaron mientras estabas en esta pantalla. Desliza de nuevo para confirmar. + Importe modificado Comisión de red Listo en unos 30 minutos Bitkit no pudo obtener las comisiones actuales de esta transferencia. Compruebe su conexión e inténtelo de nuevo. @@ -357,7 +397,7 @@ Transfiera fondos a su saldo de gasto para disfrutar de transacciones baratas e instantáneas con amigos, familia y comerciantes. Transferir\n<accent>a gasto</accent> Saldo para gastos - Transfer\n<accent>speed</accent> + Velocidad de\n<accent>transferencia</accent> Estatus Soporte Reserva total de canales ancla @@ -1011,6 +1051,7 @@ {count, plural, one {ENTRADA} many {ENTRADAS (#)} other {ENTRADAS (#)}} Factura Nota de la factura + Mover a Spark Mes siguiente Aún no hay actividad Reciba algunos fondos para empezar @@ -1094,6 +1135,7 @@ Aumenta la comisión personalizada e inténtalo de nuevo. Nota Bitcoin recibido + Bitkit no puede confirmar que esta factura no se pagó antes de restaurar tu monedero. Solicita una nueva factura. Par desconectado. Error al enviar el recibo Enviando recibo @@ -1105,7 +1147,7 @@ Factura copiada al portapapeles Factura Lightning Nota opcional para el pagador - Disfruta de transacciones instantáneas y baratas\ncon amigos, familia\ny comerciantes. + Disfruta de transacciones instantáneas y baratas con amigos, familia y comercios. Recibe en el <accent>saldo de gasto</accent> Mostrar detalles Mostrar código QR @@ -1157,6 +1199,7 @@ Saldo de reserva Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. No se puede pagar a este contacto + Un retiro anterior de tu saldo de gasto aún se está liquidando. Inténtalo de nuevo cuando termine. Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero comprueba la red y después devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. QuickPay Pagando\n<accent>factura...</accent> @@ -1397,7 +1440,7 @@ Tu transferencia se ha iniciado y se está <accent>liquidando en cadena</accent>. Tu saldo de ahorro se actualizará automáticamente cuando se complete. Transferencia\n<accent>en camino</accent> Tu saldo con tecnología de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. - Tu saldo de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. Tus conexiones se están pasando a ahorros. + Los fondos de tu canal se están moviendo a ahorro, pero tu saldo de Spark no se pudo mover y permanece en tu saldo de gasto. <accent>Conectando</accent>\na la red Vuelve a conectar tu dispositivo de hardware; parece que se ha desconectado de tu teléfono. Reconecta el dispositivo de hardware diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 0e1a5b9e4e..fca79cbad8 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -140,6 +140,31 @@ HTLC de entrada mínimo Saldos Lightning Altura de archivo del monitor de canal + Monto + Tu saldo se mueve a Spark por Lightning, la forma de menor comisión de mantenerlo en Gasto. La comisión de enrutamiento de abajo es lo máximo que pagas. + Mover a\n<accent>Spark</accent> + Una parte de tu saldo ya está en Spark. Mueve el resto de la misma forma y luego cierra la conexión vacía. + Tu saldo ya está en Spark. Cierra la conexión vacía para devolver su reserva a Ahorro. + Movido a\n<accent>Spark</accent> + Tus conexiones Lightning ya no tienen saldo que mover. + Spark aún no está listo para recibir. Inténtalo de nuevo en un momento. + No se pudo\n<accent>mover</accent> + Algo salió mal al preparar el movimiento. Inténtalo de nuevo. + Comisión de enrutamiento + El pago está en camino y aparecerá en Spark cuando se liquide. Si falla, el monto permanece en tu conexión. + Moviendo a\n<accent>Spark</accent> + Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción de menor comisión y se mantiene en Gasto. + Tu conexión\n<accent>se está cerrando</accent> + Mover la mitad + Mover ahora + Mover el resto + Mover a Spark + Buscando una ruta y su comisión… + Desliza para mover + Cierra la conexión en su lugar para devolver el saldo a Ahorro. + Puedes moverlo en partes más pequeñas. + %1$s es demasiado grande para enrutarse a Spark en un solo pago. + Monto\n<accent>demasiado grande</accent> Límite del siguiente HTLC saliente Mínimo del siguiente HTLC saliente Antes de que pueda transferir fondos a su saldo de ahorros, tiene que enviar bitcoin a su monedero Bitkit. @@ -157,8 +182,19 @@ Transfiere tu saldo de gastos a tus ahorros para guardar tu Bitcoin a largo plazo y asegurar tu futuro. Por favor espera, la transferencia de tus fondos está en progreso. Esto debería llevar <accent>±10 segundos.</accent> Fondos\n<accent>en transferencia</accent> + Transferencia\n<accent>fallida</accent> No se pudo transferir a ahorros Hora de sincronización de puntuaciones de rutas + Aprobar + <accent>La comisión de transferencia rápida ahora es ₿ {amount}.</accent> Aprueba para acceder a tus fondos rápidamente, o espera ±30 min. + Comisión de transferencia rápida\n<accent>modificada</accent> + Añadiendo al saldo de gasto + Comisión de transferencia rápida modificada + Usando velocidad de transferencia normal + ¡Genial! + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos minutos.</accent> + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos 30 minutos.</accent> + Transferencia rápida\n<accent>no disponible</accent> Continuar Usando Bitkit Pago Exitoso Procesando Pago @@ -186,6 +222,7 @@ Transferencia\n<accent>completada</accent> Direcciones de comisiones de emergencia anteriores Las transferencias forzadas anteriores usaron estas direcciones de comisiones de emergencia. Las monedas que queden en una siguen siendo tuyas: gástalas con tu frase de recuperación y su ruta de derivación. + Ruta de derivación Los operadores de Spark movieron {amount} on-chain y ya no está en Spark. Los operadores aún pueden liberártelo. {amount} se queda en Spark. No se pudo recuperar nada. @@ -276,15 +313,18 @@ Gastable onchain La cantidad que puedes transferir a tu saldo de gastos está actualmente limitada a ₿ {amount}. Máximo del Saldo de Gastos - Transfiere más de ₿ {amount} para cubrir las comisiones de añadirlo a tu saldo para gastos. - Importe demasiado bajo + Se necesita un mínimo de ₿ {amount} para configurar tu saldo de gasto. + Saldo mínimo de ahorro Transferir\n<accent>a gastos</accent> A gastos + Bitkit no pudo obtener las comisiones de esta transferencia. Revisa tu conexión e inténtalo de nuevo. est. máx. Las comisiones son {amount} más altas porque las tasas de comisión o su saldo de ahorro cambiaron mientras estaba en esta pantalla. Deslice de nuevo para confirmar. Las comisiones han cambiado Listo en unos minutos + Lo máximo que puedes transferir ahora es {amount}, porque las tarifas de comisión o tu saldo de ahorro cambiaron mientras estabas en esta pantalla. Desliza de nuevo para confirmar. + Monto modificado Listo en unos 30 minutos Reserva total de canales ancla Total Lightning @@ -297,7 +337,7 @@ Saldo de\n<accent>Gasto</accent> Saldo de gastos Rellene su <accent>saldo de gastos</accent> - Transferir desde Ahorros + Transferir desde Ahorro Transferir fondos Por favor,\n<accent>confirme</accent> Deslizar para transferir @@ -335,7 +375,7 @@ Ahorros Insuficientes Ahorro Saldo para gastos - Transfer\n<accent>speed</accent> + Velocidad de\n<accent>transferencia</accent> Capacidad de recepción Nodo Lightning ID del nodo LDK @@ -972,6 +1012,7 @@ Destino A la red {network} Seguir la entrega entre redes + Mover a Spark Actividad Contactos Perfil @@ -981,6 +1022,7 @@ Estado de la App Soporte Monedero + Bitkit no puede confirmar que esta factura no se pagó antes de restaurar tu monedero. Solicita una nueva factura. Error al enviar el recibo Enviando recibo Recibo enviado @@ -990,6 +1032,7 @@ Enviar Bitcoin Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. No se puede pagar a este contacto + Un retiro anterior de tu saldo de gasto aún se está liquidando. Inténtalo de nuevo cuando termine. Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero comprueba la red y después devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. Para Contactar @@ -1084,14 +1127,14 @@ Factura bitcoin Factura Lightning Nota opcional para el pagador - Disfruta de transacciones\ninstantáneas y baratas con\namigos, familia y comerciantes. + Disfruta de transacciones instantáneas y baratas con amigos, familia y comercios. Recibir en <accent>saldo de gastos</accent> Mostrar Detalles Mostrar código QR Auto Ahorros Gastos - Recibir fondos de Lightning + Recibir fondos Lightning Actividad Mostrar todo Aún no hay actividad @@ -1396,7 +1439,7 @@ Su transferencia se ha iniciado y se está <accent>liquidando onchain</accent>. Su saldo de ahorro se actualizará automáticamente cuando se complete. Transferencia\n<accent>en camino</accent> Tu saldo con tecnología de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. - Tu saldo de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. Tus conexiones se están pasando a ahorros. + Los fondos de tu canal se están moviendo a ahorro, pero tu saldo de Spark no se pudo mover y permanece en tu saldo de gasto. <accent>Conectando</accent>\na la red Vuelva a conectar su dispositivo de hardware; parece que se ha desconectado de su teléfono. Reconecte el dispositivo de hardware diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 1d14c19336..6348b5c2d1 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -101,7 +101,43 @@ Utiliser un autre portefeuille Transfert depuis le portefeuille HW Le plus simple est d\'utiliser vos économies Bitkit ou d\'envoyer des bitcoins depuis un autre portefeuille. + Montant + Votre solde passe vers Spark via Lightning, le moyen le moins cher de le garder dans Dépenses. Les frais de routage ci-dessous sont le maximum que vous payez. + Passer à\n<accent>Spark</accent> + Une partie de votre solde est maintenant sur Spark. Déplacez le reste de la même façon, puis fermez la connexion vidée. + Votre solde est maintenant sur Spark. Fermez la connexion vidée pour rendre sa réserve à l\'épargne. + Passé à\n<accent>Spark</accent> + Vos connexions Lightning n\'ont plus de solde à déplacer. + Spark n\'est pas encore prêt à recevoir. Réessayez dans un instant. + Impossible de\n<accent>déplacer</accent> + Une erreur s\'est produite lors de la préparation du transfert. Réessayez. + Frais de routage + Le paiement est en route et apparaîtra dans Spark une fois réglé. En cas d\'échec, le montant reste dans votre connexion. + Passage à\n<accent>Spark</accent> + Blocktank ferme ses connexions Lightning. Déplacez dès maintenant votre solde vers Spark : c\'est l\'option la moins chère, et il reste dans Dépenses. + Votre connexion\n<accent>se ferme</accent> + Déplacer la moitié + Déplacer maintenant + Déplacer le reste + Passer à Spark + Recherche d\'une route et de ses frais… + Glissez pour déplacer + Fermez plutôt la connexion pour rendre le solde à l\'épargne. + Vous pouvez le déplacer en plusieurs parties plus petites. + %1$s est trop élevé pour être acheminé vers Spark en un seul paiement. + Montant\n<accent>trop élevé</accent> + Transfert\n<accent>échoué</accent> Impossible de transférer vers l\'épargne + Approuver + <accent>Les frais de transfert rapide sont maintenant de ₿ {amount}.</accent> Approuvez pour accéder rapidement à vos fonds, ou attendez ±30 min. + Frais de transfert rapide\n<accent>modifiés</accent> + Ajout au solde dépenses + Frais de transfert rapide modifiés + Vitesse de transfert normale utilisée + Génial ! + Veuillez patienter, le transfert de vos fonds est en cours. Cela devrait prendre <accent>quelques minutes.</accent> + Veuillez patienter, le transfert de vos fonds est en cours. Cela devrait prendre <accent>environ 30 minutes.</accent> + Transfert rapide\n<accent>indisponible</accent> Spark Frais de réclamation %1$d/3 confirmations @@ -126,6 +162,7 @@ Transfert\n<accent>terminé</accent> Anciennes adresses de frais d\'urgence Les transferts forcés précédents ont utilisé ces adresses de frais d\'urgence. Les pièces restées à l\'une d\'elles vous appartiennent toujours : dépensez-les avec votre phrase de récupération et son chemin de dérivation. + Chemin de dérivation {amount} a été déplacé on-chain par les opérateurs Spark et n\'est pas sur Spark. Les opérateurs peuvent encore vous le libérer. {amount} reste sur Spark. Rien n\'a pu être récupéré. @@ -215,11 +252,14 @@ Votre solde de dépenses utilise Spark, géré par Lightspark, Breez et Flashnet. Sa sécurité repose sur au moins un opérateur agissant honnêtement. Les opérateurs peuvent suspendre l\'accès, et retirer sans leur coopération vous oblige à lancer une sortie on-chain. Solde Dépenses Financez votre <accent>solde Dépenses</accent> - Transfert depuis l\'épargne + Transférer depuis l\'épargne Configuration manuelle Transfert \n<accent>Dépenses</accent> + Bitkit n\'a pas pu obtenir les frais de ce transfert. Vérifiez votre connexion et réessayez. est. max + Le maximum que vous pouvez transférer est désormais {amount}, car les taux de frais ou votre solde d\'épargne ont changé pendant que vous étiez sur cet écran. Glissez à nouveau pour confirmer. + Montant modifié Prêt dans environ 30 minutes Transfert de fonds Veuillez\n<accent>confirmer</accent> @@ -229,8 +269,8 @@ Ouvrir Trezor Connect 25% Seuil Maximum Épargne - Transférez plus de ₿ {amount} pour couvrir les frais d\'ajout à votre solde de dépenses. - Montant trop faible + Un minimum de ₿ {amount} est nécessaire pour configurer votre solde dépenses. + Solde d\'épargne minimum Le montant que vous pouvez transférer vers votre solde de dépenses est actuellement limité à ₿ {amount}. Frais de réseau Bitkit n\'a pas pu obtenir les frais actuels de ce transfert. Vérifiez votre connexion et réessayez. @@ -284,7 +324,7 @@ Épargne insuffisante Épargner Solde Dépenses - Transfer\n<accent>speed</accent> + Vitesse de\n<accent>transfert</accent> Capacité de réception Heure de l\'instantané Rapid Gossip Sync Heure de synchronisation des scores de routage @@ -976,6 +1016,7 @@ Adresse de destination Vers le réseau {network} Suivre la livraison inter-réseaux + Passer à Spark Wallet Activité Contacts @@ -985,6 +1026,7 @@ Config Statut de l\'application Assistance + Bitkit ne peut pas confirmer que cette facture n\'a pas été payée avant la restauration de votre portefeuille. Veuillez demander une nouvelle facture. Échec de l\'envoi du reçu Envoi du reçu Reçu envoyé @@ -993,6 +1035,7 @@ Envoyer des bitcoins Ce contact n\'a aucun moyen de paiement que Bitkit peut utiliser pour le moment. Impossible de payer ce contact + Un retrait précédent de votre solde dépenses est encore en cours de règlement. Réessayez une fois terminé. Les transferts vers le solde de dépenses ne sont plus disponibles. Bitkit vérifie d\'abord le réseau, puis renvoie les pièces de ce transfert vers votre portefeuille afin que le transfert d\'origine ne soit jamais confirmé. Cela coûte des frais de réseau. Pour Contact @@ -1203,7 +1246,7 @@ Pair déconnecté. Erreur de démarrage de Lightning Recevoir des fonds Lightning - Profitez de transactions instantanées\net peu coûteuses avec vos amis, votre\nfamille et les commerçants. + Profitez de transactions instantanées et peu coûteuses avec vos amis, votre famille et les commerçants. Recevoir sur le <accent>solde dépenses</accent> Afficher les détails Auto @@ -1399,7 +1442,7 @@ Votre transfert a été initié et est <accent>en cours de règlement on-chain</accent>. Votre solde d\'épargne se mettra à jour automatiquement une fois terminé. Transfert\n<accent>en cours</accent> Votre solde basé sur Spark n\'a pas pu être transféré vers l\'épargne et reste dans votre solde de dépenses. - Votre solde Spark n\'a pas pu être transféré vers l\'épargne et reste dans votre solde de dépenses. Vos connexions sont en cours de transfert vers l\'épargne. + Les fonds de votre canal passent à l\'épargne, mais votre solde Spark n\'a pas pu être déplacé et reste dans votre solde dépenses. <accent>Connexion</accent>\nau réseau Veuillez reconnecter votre appareil matériel, il semble être déconnecté de votre téléphone. Reconnecter l\'appareil matériel diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index e5783d5bd7..0502937533 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -159,7 +159,7 @@ Trasferimento Forzato Non è stato possibile avviare il trasferimento. Vuoi forzare questo trasferimento? Non postrai utilizzare questi fondi per ±14 giorni (!) Trasferimento\n<accent>forzoso</accent> - Trasferimento da risparmio + Trasferisci dai Risparmi Usa un altro portafoglio Trasferimento da wallet HW Conto di Spesa @@ -172,6 +172,31 @@ È utilizzabile? Saldi Lightning Altezza Archivio Monitor Canali + Importo + Il tuo saldo passa a Spark tramite Lightning, il modo con le commissioni più basse per tenerlo nel conto Spesa. La commissione di instradamento qui sotto è il massimo che paghi. + Sposta su\n<accent>Spark</accent> + Una parte del tuo saldo è ora su Spark. Sposta il resto allo stesso modo, poi chiudi la connessione svuotata. + Il tuo saldo è ora su Spark. Chiudi la connessione svuotata per restituire la sua riserva ai Risparmi. + Spostato su\n<accent>Spark</accent> + Le tue connessioni Lightning non hanno più saldo da spostare. + Spark non è ancora pronto a ricevere. Riprova tra un momento. + Impossibile\n<accent>spostare</accent> + Qualcosa è andato storto durante la preparazione dello spostamento. Riprova. + Commissione di instradamento + Il pagamento è in corso e comparirà su Spark una volta completato. Se fallisce, l\'importo resta nella tua connessione. + Spostamento su\n<accent>Spark</accent> + Blocktank sta chiudendo le sue connessioni Lightning. Sposta subito il tuo saldo su Spark: è l\'opzione con le commissioni più basse e resta nel conto Spesa. + La tua connessione\n<accent>si sta chiudendo</accent> + Sposta Metà + Sposta Ora + Sposta Il Resto + Sposta Su Spark + Ricerca di un percorso e della sua commissione… + Swipe Per Spostare + Chiudi invece la connessione per restituire il saldo ai Risparmi. + Puoi spostarlo in parti più piccole. + %1$s è troppo grande per essere instradato su Spark in un solo pagamento. + Importo\n<accent>troppo grande</accent> Limite HTLC in Uscita Successivo HTLC Min in Uscita Successivo Prima di poter trasferire fondi dal tuo conto di risparmio, devi inviare bitcoin al tuo portafoglio Bitkit. @@ -214,8 +239,19 @@ Trasferisci\n<accent>ai risparmi</accent> Attendi, il trasferimento dei fondi e\' in corso. Dovrebbe richiedere <accent>circa 10 secondi.</accent> Fondi\n<accent>in trasferimento</accent> + Trasferimento\n<accent>non riuscito</accent> Impossibile trasferire ai risparmi Tempo Sincronizzazione Punteggi Pathfinding + Approva + <accent>La commissione per il trasferimento rapido è ora ₿ {amount}.</accent> Approva per accedere subito ai tuoi fondi, oppure attendi ±30 min. + Commissione trasferimento rapido\n<accent>modificata</accent> + Aggiunta al saldo di spesa + Commissione trasferimento rapido modificata + Uso della velocità di trasferimento normale + Fantastico! + Attendi, il trasferimento dei tuoi fondi è in corso. Dovrebbe richiedere <accent>qualche minuto.</accent> + Attendi, il trasferimento dei tuoi fondi è in corso. Dovrebbe richiedere <accent>circa 30 minuti.</accent> + Trasferimento rapido\n<accent>non disponibile</accent> Continua ad utilizzare Bitkit Elaborazione del pagamento Pagamento Riuscito @@ -243,6 +279,7 @@ Trasferimento\n<accent>completato</accent> Indirizzi precedenti delle commissioni di emergenza I precedenti trasferimenti forzati usavano questi indirizzi per le commissioni di emergenza. Le monete rimaste su uno di essi restano tue: spendile con la tua frase di recupero e il relativo percorso di derivazione. + Percorso di derivazione {amount} è stato spostato on-chain dagli operatori Spark e non è su Spark. Gli operatori possono ancora sbloccarlo per te. {amount} resta su Spark. Non è stato possibile recuperare nulla. @@ -336,17 +373,20 @@ Risparmi insufficienti L\'importo che puoi trasferire al tuo conto di spesa e\' attualmente limitato a ₿ {amount}. Massimo Conto di Spesa - Trasferisci più di ₿ {amount}, così copre le commissioni per aggiungerlo al tuo conto di spesa. - Importo troppo basso + È necessario un minimo di ₿ {amount} per configurare il tuo saldo di spesa. + Saldo minimo dei risparmi 25% Trasferisci\n<accent>alle spese</accent> Alle spese + Bitkit non è riuscito a ottenere le commissioni per questo trasferimento. Controlla la connessione e riprova. stim. max Le commissioni sono aumentate di {amount} perché i tassi di commissione o il saldo dei tuoi risparmi sono cambiati mentre eri su questa schermata. Scorri di nuovo per confermare. Commissioni cambiate Pronto in pochi minuti Commissioni servizio + Il massimo che puoi trasferire ora è {amount}, perché le tariffe delle commissioni o il tuo saldo dei risparmi sono cambiati mentre eri su questa schermata. Scorri di nuovo per confermare. + Importo modificato Commissioni rete Pronto in circa 30 minuti Bitkit non è riuscito a ottenere le commissioni attuali per questo trasferimento. Controlla la connessione e riprova. @@ -356,7 +396,7 @@ Trasferisci fondi al tuo conto di spesa per usufruire di transazioni istantanee ed economiche con amici, familiari e commercianti. Trasferisci\n<accent>alle spese</accent> Conto di spesa - Transfer\n<accent>speed</accent> + Velocità di\n<accent>trasferimento</accent> Stato Supporto Riserva Totale Canali Anchor @@ -1011,6 +1051,7 @@ {count, plural, one {INGRESSO} many {INGRESSI (#)} other {ENTRATE (#)}} Invoice Nota invoice + Sposta su Spark Mese prossimo Nessuna attività ancora Ricevi dei fondi per iniziare @@ -1095,6 +1136,7 @@ Aumenta la commissione personalizzata e riprova. Note Bitcoin ricevuti + Bitkit non può confermare che questa fattura non sia stata pagata prima del ripristino del tuo wallet. Richiedi una nuova fattura. Peer disconnesso. Invio della ricevuta non riuscito Invio della ricevuta @@ -1106,7 +1148,7 @@ Fattura copiata negli appunti Lightning invoice Nota opzionale per chi paga - Goditi transazioni istantanee\ned economiche con amici, familiari\ne commercianti. + Goditi transazioni istantanee ed economiche con amici, familiari ed esercenti. Ricevi sul <accent>conto di spesa</accent> Mostra Dettagli Visualizza QR Code @@ -1158,6 +1200,7 @@ Saldo di Riserva Questo contatto non ha alcun metodo di pagamento che Bitkit possa usare ora. Impossibile pagare questo contatto + Un precedente prelievo dal tuo saldo di spesa è ancora in fase di regolamento. Riprova al termine. I trasferimenti al saldo di spesa non sono più disponibili. Bitkit controlla prima la rete, poi rimanda le monete di questo trasferimento al tuo wallet, così il trasferimento originale non potrà mai essere confermato. Questo costa una commissione di rete. Questo pagamento sta richiedendo un po\' più tempo del previsto. Puoi continuare a utilizzare Bitkit. Pagamento in sospeso @@ -1402,7 +1445,7 @@ Il tuo trasferimento è stato avviato ed è <accent>in regolamento on-chain</accent>. Il saldo dei tuoi risparmi si aggiornerà automaticamente al termine. Trasferimento\n<accent>in corso</accent> Il tuo saldo basato su Spark non ha potuto spostarsi nei risparmi e resta nel tuo saldo di spesa. - Il saldo Spark non è stato spostato nei risparmi e resta nel saldo di spesa. Le tue connessioni stanno passando ai risparmi. + I fondi del tuo canale vengono spostati nei risparmi, ma il tuo saldo Spark non è stato spostato e resta nel tuo saldo di spesa. <accent>Connessione</accent>\nalla rete Ricollega il tuo dispositivo hardware, sembra essere disconnesso dal telefono. Ricollega il Dispositivo Hardware diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index cc4cc8433b..668f99f52f 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -171,6 +171,31 @@ Is bruikbaar Lightning-saldi Kanaalmonitor archiveringshoogte + Bedrag + Je saldo gaat via Lightning naar Spark, de goedkoopste manier om het in je bestedingssaldo te houden. De routeringskosten hieronder zijn het maximum dat je betaalt. + Verplaatsen naar\n<accent>Spark</accent> + Een deel van je saldo staat nu op Spark. Verplaats de rest op dezelfde manier en sluit daarna de lege verbinding. + Je saldo staat nu op Spark. Sluit de lege verbinding om de reserve terug te zetten naar spaargeld. + Verplaatst naar\n<accent>Spark</accent> + Je Lightning-verbindingen hebben geen saldo meer om te verplaatsen. + Spark is nog niet klaar om te ontvangen. Probeer het zo opnieuw. + Verplaatsen\n<accent>mislukt</accent> + Er ging iets mis bij het voorbereiden van de verplaatsing. Probeer opnieuw. + Routeringskosten + De betaling is onderweg en verschijnt in Spark zodra ze is afgerond. Als ze mislukt, blijft het bedrag in je verbinding. + Verplaatsen naar\n<accent>Spark</accent> + Blocktank sluit zijn Lightning-verbindingen. Verplaats je saldo nu naar Spark: dat is de goedkoopste optie en het blijft in je bestedingssaldo. + Je verbinding\n<accent>wordt gesloten</accent> + Helft verplaatsen + Nu verplaatsen + Rest verplaatsen + Verplaatsen naar Spark + Route en kosten zoeken… + Veeg om te verplaatsen + Sluit in plaats daarvan de verbinding om het saldo terug te zetten naar spaargeld. + Je kunt het in kleinere delen verplaatsen. + %1$s is te groot om in één betaling naar Spark te routeren. + Bedrag\n<accent>te groot</accent> Volgende uitgaande HTLC-limiet Volgende uitgaande HTLC min Voordat je geld van je spaargeld kunt overboeken, moet je bitcoin naar je Bitkit-wallet sturen. @@ -213,8 +238,19 @@ Overboeken\n<accent>naar spaargeld</accent> Even geduld, je geld wordt overgeboekt. Dit duurt <accent>±10 seconden.</accent> Geld\n<accent>in overboeking</accent> + Overboeking\n<accent>mislukt</accent> Kon niet naar spaargeld overboeken Pathfinding scores synchronisatietijd + Goedkeuren + <accent>De kosten voor snel overboeken zijn nu ₿ {amount}.</accent> Keur goed om snel bij je geld te komen, of wacht ±30 min. + Kosten snel overboeken\n<accent>gewijzigd</accent> + Toevoegen aan bestedingssaldo + Kosten snel overboeken gewijzigd + Normale overboekingssnelheid gebruiken + Geweldig! + Even geduld, je geld wordt overgeboekt. Dit duurt <accent>een paar minuten.</accent> + Even geduld, je geld wordt overgeboekt. Dit duurt <accent>ongeveer 30 minuten.</accent> + Snel overboeken\n<accent>niet beschikbaar</accent> Doorgaan met Bitkit Betaling verwerken Betaling succesvol @@ -242,6 +278,7 @@ Overboeking\n<accent>voltooid</accent> Eerdere adressen voor noodkosten Eerdere geforceerde overboekingen gebruikten deze adressen voor noodkosten. Coins die op een adres zijn achtergebleven blijven van jou: besteed ze met je herstelzin en het afleidingspad. + Afleidingspad {amount} is door de Spark-beheerders on-chain verplaatst en staat niet op Spark. De beheerders kunnen het nog steeds aan je vrijgeven. {amount} blijft op Spark. Er kon niets worden teruggehaald. @@ -335,17 +372,20 @@ Onvoldoende spaargeld Het bedrag dat je kunt overboeken naar je bestedingssaldo is momenteel beperkt tot ₿ {amount}. Maximum bestedingssaldo - Boek meer dan ₿ {amount} over, zodat de kosten om het aan je bestedingssaldo toe te voegen gedekt zijn. - Bedrag te klein + Er is minimaal ₿ {amount} nodig om je bestedingssaldo in te stellen. + Minimaal spaarsaldo 25% Overboeken\n<accent>naar bestedingssaldo</accent> Naar bestedingssaldo + Bitkit kon de kosten voor deze overboeking niet ophalen. Controleer je verbinding en probeer opnieuw. ca. max De vergoedingen zijn {amount} hoger, omdat de vergoedingstarieven of uw spaargeld zijn gewijzigd terwijl u op dit scherm was. Veeg opnieuw om te bevestigen. Vergoedingen gewijzigd Klaar binnen enkele minuten Servicevergoedingen + Het maximale bedrag dat je kunt overboeken is nu {amount}, omdat de tarieven of je spaarsaldo zijn gewijzigd terwijl je op dit scherm was. Veeg opnieuw om te bevestigen. + Bedrag gewijzigd Netwerkvergoedingen Klaar in ongeveer 30 minuten Bitkit kon de huidige kosten voor deze overboeking niet ophalen. Controleer je verbinding en probeer het opnieuw. @@ -355,7 +395,7 @@ Boek geld over naar je bestedingssaldo voor directe en goedkope transacties met vrienden, familie en winkeliers. Overboeken\n<accent>naar bestedingssaldo</accent> Bestedingssaldo - Transfer\n<accent>speed</accent> + Overboekings\n<accent>snelheid</accent> Status Ondersteuning Totale ankerkanalen reserve @@ -1006,6 +1046,7 @@ {count, plural, one {INVOER} other {INVOEREN (#)}} Factuur Factuurnotitie + Verplaatsen naar Spark Volgende maand Nog geen activiteit Ontvang wat geld om te beginnen @@ -1090,6 +1131,7 @@ Verhoog de aangepaste vergoeding en probeer het opnieuw. Notitie Bitcoin ontvangen + Bitkit kan niet bevestigen dat deze factuur niet is betaald voordat je je wallet herstelde. Vraag een nieuwe factuur aan. Peer niet verbonden. Ontvangstbewijs verzenden mislukt Ontvangstbewijs verzenden @@ -1101,7 +1143,7 @@ Factuur gekopieerd naar klembord Lightning-factuur Optionele notitie voor betaler - Geniet van directe en goedkope\ntransacties met vrienden, familie\nen winkeliers. + Geniet van directe en goedkope transacties met vrienden, familie en winkeliers. Ontvangen op <accent>bestedingssaldo</accent> Details tonen QR-code tonen @@ -1153,6 +1195,7 @@ Reservesaldo Dit contact heeft nu geen betaalmethode die Bitkit kan gebruiken. Kan dit contact niet betalen + Een eerdere opname van je bestedingssaldo wordt nog verwerkt. Probeer het opnieuw zodra die is voltooid. Overboekingen naar je bestedingssaldo zijn niet meer beschikbaar. Bitkit controleert eerst het netwerk en stuurt de munten van deze overboeking dan terug naar je wallet, zodat de oorspronkelijke overboeking nooit bevestigd wordt. Dit kost netwerkkosten. Deze betaling duurt iets langer dan verwacht. U kunt Bitkit blijven gebruiken. Betaling Onderweg @@ -1398,7 +1441,7 @@ Uw overboeking is gestart en wordt <accent>on-chain afgehandeld</accent>. Uw spaargeld wordt automatisch bijgewerkt zodra deze is voltooid. Overboeking\n<accent>onderweg</accent> Je saldo via Spark kon niet naar spaargeld en blijft in je bestedingssaldo. - Je Spark-saldo kon niet naar sparen en blijft in je bestedingssaldo. Je verbindingen gaan naar sparen. + Je kanaalfondsen worden naar spaargeld overgeboekt, maar je Spark-saldo kon niet worden verplaatst en blijft in je bestedingssaldo. <accent>Verbinden</accent>\nmet netwerk Verbind uw hardwareapparaat opnieuw, de verbinding met uw telefoon lijkt verbroken. Hardwareapparaat opnieuw verbinden diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index b9b6e5cf83..de3c7af7e1 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -103,7 +103,43 @@ Użyj innego portfela Prześlij z portfela HW Najłatwiejszą opcją jest użycie oszczędności Bitkit lub wysłanie bitcoinów z innego portfela. + Kwota + Twoje saldo przechodzi do Spark przez Lightning, najtańszym sposobem na zachowanie go w Wydatkach. Opłata za routing poniżej to maksimum, jakie zapłacisz. + Przenieś do\n<accent>Spark</accent> + Część Twojego salda jest już w Spark. Przenieś resztę w ten sam sposób, a potem zamknij opróżnione połączenie. + Twoje saldo jest już w Spark. Zamknij opróżnione połączenie, aby zwrócić jego rezerwę do Oszczędności. + Przeniesiono do\n<accent>Spark</accent> + Twoje połączenia Lightning nie mają już salda do przeniesienia. + Spark nie jest jeszcze gotowy do odbioru. Spróbuj ponownie za chwilę. + Nie udało się\n<accent>przenieść</accent> + Coś poszło nie tak podczas przygotowywania przeniesienia. Spróbuj ponownie. + Opłata za routing + Płatność jest w drodze i pojawi się w Spark po rozliczeniu. Jeśli się nie powiedzie, kwota pozostanie w Twoim połączeniu. + Przenoszenie do\n<accent>Spark</accent> + Blocktank zamyka swoje połączenia Lightning. Przenieś teraz saldo do Spark: to najtańsza opcja i środki pozostają w Wydatkach. + Twoje połączenie\n<accent>się zamyka</accent> + Przenieś połowę + Przenieś teraz + Przenieś resztę + Przenieś do Spark + Szukanie trasy i opłaty… + Przesuń, aby przenieść + Zamiast tego zamknij połączenie, aby zwrócić saldo do Oszczędności. + Możesz je przenieść w mniejszych częściach. + Kwota %1$s jest zbyt duża, aby przesłać ją do Spark jedną płatnością. + Kwota\n<accent>zbyt duża</accent> + Transfer\n<accent>nieudany</accent> Nie udało się przesłać do oszczędności + Zatwierdź + <accent>Opłata za szybki transfer wynosi teraz ₿ {amount}.</accent> Zatwierdź, aby szybko uzyskać dostęp do środków, lub poczekaj ±30 min. + Opłata za szybki transfer\n<accent>zmieniona</accent> + Dodawanie do salda wydatków + Opłata za szybki transfer zmieniona + Użycie normalnej szybkości transferu + Świetnie! + Proszę czekać, trwa transfer Twoich środków. Powinno to zająć <accent>kilka minut.</accent> + Proszę czekać, trwa transfer Twoich środków. Powinno to zająć <accent>około 30 minut.</accent> + Szybki transfer\n<accent>niedostępny</accent> Spark Opłata za odbiór %1$d/3 potwierdzeń @@ -128,6 +164,7 @@ Transfer\n<accent>zakończony</accent> Wcześniejsze adresy opłat awaryjnych Wcześniejsze wymuszone transfery używały tych adresów opłat awaryjnych. Monety pozostawione na jednym z nich nadal należą do Ciebie: wydaj je za pomocą frazy odzyskiwania i jej ścieżki derywacji. + Ścieżka derywacji {amount} zostało przeniesione on-chain przez operatorów Spark i nie jest na Spark. Operatorzy wciąż mogą Ci je zwolnić. {amount} pozostaje na Spark. Nie udało się niczego odzyskać. @@ -220,8 +257,11 @@ Prześlij z Oszczędności Konfiguracja ręczna Prześlij \n<accent>na saldo wydatków</accent> + Bitkit nie mógł pobrać opłat za ten transfer. Sprawdź połączenie i spróbuj ponownie. szac. maks. + Maksymalna kwota do przesłania wynosi teraz {amount}, ponieważ stawki opłat lub Twoje saldo oszczędności zmieniły się, gdy byłeś na tym ekranie. Przesuń ponownie, aby potwierdzić. + Kwota zmieniona Gotowe za około 30 minut Prześlij środki Proszę \n<accent>potwierdzić</accent> @@ -231,8 +271,8 @@ Otwórz Trezor Connect 25% Maksymalne saldo wydatków - Prześlij więcej niż ₿ {amount}, aby pokryć opłaty za dodanie do salda wydatków. - Kwota zbyt mała + Do skonfigurowania salda wydatków potrzeba co najmniej ₿ {amount}. + Minimalne saldo oszczędności Kwota, którą można przelać na saldo wydatków, jest obecnie ograniczona do ₿ {amount}. Opłaty sieciowe Bitkit nie mógł pobrać aktualnych opłat za ten przelew. Sprawdź połączenie i spróbuj ponownie. @@ -286,7 +326,7 @@ Niewystarczające oszczędności Oszczędności Saldo wydatków - Transfer\n<accent>speed</accent> + Szybkość\n<accent>transferu</accent> Zdolność odbioru Węzeł Lightning Identyfikator węzła LDK @@ -978,6 +1018,7 @@ Na adres Do sieci {network} Śledź dostarczenie między sieciami + Przenieś do Spark Portfel Aktywność Kontakty @@ -987,6 +1028,7 @@ Ustawienia Status aplikacji Wsparcie + Bitkit nie może potwierdzić, że ta faktura nie została opłacona przed przywróceniem portfela. Poproś o nową fakturę. Nie udało się wysłać potwierdzenia Wysyłanie potwierdzenia Potwierdzenie wysłane @@ -995,6 +1037,7 @@ Wyślij Bitcoin Ten kontakt nie ma teraz metody płatności, której Bitkit może użyć. Nie można zapłacić temu kontaktowi + Wcześniejsza wypłata z Twojego salda wydatków wciąż się rozlicza. Spróbuj ponownie po jej zakończeniu. Przelewy na saldo wydatków nie są już dostępne. Bitkit najpierw sprawdza sieć, a potem odsyła monety z tego przelewu do Twojego portfela, aby pierwotny przelew nigdy nie został potwierdzony. Wiąże się to z opłatą sieciową. Do Kontakt @@ -1209,7 +1252,7 @@ Węzeł rozłączony. Błąd uruchamiania Lightning Odbierz środki Lightning - Ciesz się natychmiastowymi i tanimi\ntransakcjami z przyjaciółmi, rodziną\ni sprzedawcami. + Ciesz się natychmiastowymi i tanimi transakcjami z przyjaciółmi, rodziną i sprzedawcami. Odbierz na <accent>saldo wydatków</accent> Pokaż szczegóły Auto @@ -1402,7 +1445,7 @@ Twój transfer został zainicjowany i jest <accent>rozliczany on-chain</accent>. Saldo oszczędności zaktualizuje się automatycznie po jego zakończeniu. Transfer\n<accent>w drodze</accent> Twoje saldo oparte na Spark nie mogło zostać przeniesione do oszczędności i pozostaje w saldzie wydatków. - Nie udało się przenieść salda Spark do oszczędności; pozostaje w saldzie wydatków. Twoje połączenia są przenoszone do oszczędności. + Środki z Twoich kanałów są przenoszone do Oszczędności, ale Twojego salda Spark nie udało się przenieść i pozostaje ono w saldzie wydatków. <accent>Łączenie</accent>\nz siecią Połącz ponownie urządzenie sprzętowe, wygląda na to, że zostało odłączone od telefonu. Połącz ponownie urządzenie diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index cef87c8aa6..5bbd2d36f3 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -175,6 +175,31 @@ É utilizável Saldos Lightning Altura de Arquivamento do Monitor de Canal + Valor + Seu saldo passa para a Spark através da Lightning, a forma mais barata de o manter nos Gastos. A taxa de roteamento abaixo é o máximo que paga. + Mover para a\n<accent>Spark</accent> + Parte do seu saldo já está na Spark. Mova o resto da mesma forma e depois feche a conexão esvaziada. + Seu saldo já está na Spark. Feche a conexão esvaziada para devolver a reserva dela à poupança. + Movido para a\n<accent>Spark</accent> + Suas conexões Lightning não têm mais saldo para mover. + A Spark ainda não está pronta para receber. Tente novamente em instantes. + Não foi possível\n<accent>mover</accent> + Algo deu errado ao preparar a movimentação. Tente novamente. + Taxa de roteamento + O pagamento está a caminho e aparece na Spark quando for concluído. Se falhar, o valor fica na sua conexão. + Movendo para a\n<accent>Spark</accent> + A Blocktank está fechando as suas conexões Lightning. Mova já seu saldo para a Spark: é a opção mais barata e fica nos Gastos. + Sua conexão\n<accent>está fechando</accent> + Mover metade + Mover agora + Mover o restante + Mover para a Spark + Buscando rota e taxa… + Deslizar Para Mover + Em vez disso, feche a conexão para devolver o saldo à poupança. + Você pode movê-lo em partes menores. + %1$s é grande demais para ser roteado para a Spark num único pagamento. + Valor\n<accent>grande demais</accent> Limite do Próximo HTLC de Saída HTLC de Saída Mín Próximo Antes de transferir fundos de seu saldo de poupança, receba bitcoin na sua carteira Bitkit. @@ -217,8 +242,19 @@ Transferir\n<accent>para poupança</accent> Aguarde, sua transferência de fundos está em andamento. Isso deve levar <accent>±10 segundos.</accent> <accent>Transferindo</accent>\nfundos + Transferência\n<accent>falhou</accent> Não foi possível transferir para a poupança Sincronização de Scores de Roteamento + Aprovar + <accent>A taxa da transferência rápida é agora ₿ {amount}.</accent> Aprove para acessar seus fundos rapidamente ou aguarde ±30 min. + Taxa da transferência rápida\n<accent>alterada</accent> + Adicionando ao saldo de gastos + Taxa da transferência rápida alterada + Usando velocidade de transferência normal + Incrível! + Aguarde, a transferência dos seus fundos está em andamento. Isso deve levar <accent>alguns minutos.</accent> + Aguarde, a transferência dos seus fundos está em andamento. Isso deve levar <accent>cerca de 30 minutos.</accent> + Transferência rápida\n<accent>indisponível</accent> Continuar Usando o Bitkit Processando Pagamento Pagamento Realizado @@ -246,6 +282,7 @@ Transferência\n<accent>concluída</accent> Endereços de taxas de emergência anteriores As transferências forçadas anteriores usaram estes endereços de taxas de emergência. As moedas que ficarem em um deles continuam sendo suas: gaste-as com sua frase de recuperação e o respectivo caminho de derivação. + Caminho de derivação {amount} foi movido on-chain pelos operadores da Spark e não está na Spark. Os operadores ainda podem liberá-lo para você. {amount} fica na Spark. Nada pôde ser recuperado. @@ -339,17 +376,20 @@ Saldo de Poupança Insuficiente O valor que você pode transferir para seu saldo de gastos está atualmente limitado a ₿ {amount}. Saldo de gastos Máximo - Transfira mais de ₿ {amount} para cobrir as taxas de adicioná-la ao seu saldo de gastos. - Valor muito baixo + É necessário um mínimo de ₿ {amount} para configurar seu saldo de gastos. + Saldo mínimo da poupança 25% Transferir\n<accent>para gastos</accent> Para gastos + O Bitkit não conseguiu obter as taxas desta transferência. Verifique sua conexão e tente novamente. est. máx. As taxas estão {amount} mais altas porque as taxas de rede ou seu saldo de poupança mudaram enquanto você estava nesta tela. Deslize novamente para confirmar. Taxas alteradas Pronto em poucos minutos Taxa de serviço + O máximo que pode transferir é agora {amount}, porque as taxas ou seu saldo de poupança mudaram enquanto estava neste ecrã. Deslize novamente para confirmar. + Valor alterado Taxa da rede Pronto em cerca de 30 minutos O Bitkit não conseguiu obter as taxas atuais desta transferência. Verifique sua conexão e tente novamente. @@ -359,7 +399,7 @@ Transfira fundos para seu saldo de gastos para desfrutar de transações instantâneas e baratas com amigos, familiares e comerciantes. Transferir\n<accent>para gastos</accent> Saldo de gastos - Transfer\n<accent>speed</accent> + Velocidade da\n<accent>transferência</accent> Status Suporte Reserva Total de Canais Anchor @@ -1015,6 +1055,7 @@ {count, plural, one {ENTRADA} many {ENTRADAS (#)} other {ENTRADAS (#)}} Invoice Descrição do invoice + Mover para a Spark Próximo mês Nenhuma atividade ainda Receba alguns bitcoins para começar @@ -1099,6 +1140,7 @@ Aumente a taxa personalizada e tente novamente. Nota Bitcoin Recebido + O Bitkit não consegue confirmar que esta fatura não foi paga antes de você restaurar sua carteira. Peça uma nova fatura. Peer desconectado. Falha ao enviar o recibo Enviando recibo @@ -1110,7 +1152,7 @@ Invoice copiado para a área de transferência. Invoice Lightning Comentário opcional para o pagador - Aproveite transações instantâneas\ne baratas com amigos, família\ne comerciantes. + Aproveite transações instantâneas e baratas com amigos, familiares e comerciantes. Receba no <accent>saldo de gastos</accent> Mostrar Detalhes Mostrar código QR @@ -1162,6 +1204,7 @@ Saldo de reserva Este contato não tem nenhum método de pagamento que o Bitkit possa usar agora. Não é possível pagar este contato + Um levantamento anterior do seu saldo de gastos ainda está a ser concluído. Tente novamente quando for concluído. As transferências para o saldo de gastos não estão mais disponíveis. O Bitkit primeiro verifica a rede e depois devolve as moedas desta transferência para sua carteira, para que a transferência original nunca seja confirmada. Isso tem uma taxa de rede. Esse pagamento está demorando mais do que o esperado. Enquanto isso, você pode continuar usando a Bitkit. Pagamento Pendente @@ -1404,7 +1447,7 @@ Sua transferência foi iniciada e está sendo <accent>liquidada onchain</accent>. Seu saldo de poupança será atualizado automaticamente quando ela for concluída. Transferência\n<accent>a caminho</accent> Seu saldo com tecnologia Spark não pôde ser movido para a poupança e continua no saldo de gastos. - Não foi possível mover seu saldo do Spark para a poupança; ele continua no saldo de gastos. Suas conexões estão sendo movidas para a poupança. + Os fundos dos seus canais estão sendo movidos para a poupança, mas seu saldo Spark não pôde ser movido e fica no seu saldo de gastos. <accent>Conectando</accent>\nà rede Reconecte seu dispositivo de hardware, ele parece estar desconectado do seu telefone. Reconectar Dispositivo de Hardware diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 1af2790b77..3d7961678c 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -98,7 +98,43 @@ Transferir de outra carteira Transferir da carteira HW A forma mais fácil é usar as suas poupanças Bitkit ou enviar bitcoin de uma carteira diferente. + Montante + O seu saldo passa para a Spark através da Lightning, a forma mais barata de o manter nos Gastos. A taxa de roteamento abaixo é o máximo que paga. + Mover para a\n<accent>Spark</accent> + Parte do seu saldo já está na Spark. Mova o resto da mesma forma e depois feche a conexão esvaziada. + O seu saldo já está na Spark. Feche a conexão esvaziada para devolver a sua reserva à poupança. + Movido para a\n<accent>Spark</accent> + As suas conexões Lightning já não têm saldo para mover. + A Spark ainda não está pronta para receber. Tente novamente dentro de instantes. + Não foi possível\n<accent>mover</accent> + Algo correu mal ao preparar a movimentação. Tente novamente. + Taxa de roteamento + O pagamento está a caminho e aparece na Spark quando for concluído. Se falhar, o montante fica na sua conexão. + A mover para a\n<accent>Spark</accent> + A Blocktank está a fechar as suas conexões Lightning. Mova já o seu saldo para a Spark: é a opção mais barata e fica nos Gastos. + A sua conexão\n<accent>está a fechar</accent> + Mover metade + Mover agora + Mover o resto + Mover para a Spark + A procurar rota e taxa… + Deslizar Para Mover + Em vez disso, feche a conexão para devolver o saldo à poupança. + Pode movê-lo em partes mais pequenas. + %1$s é demasiado grande para ser encaminhado para a Spark num único pagamento. + Montante\n<accent>demasiado grande</accent> + Transferência\n<accent>falhada</accent> Não foi possível transferir para a poupança + Aprovar + <accent>A taxa da transferência rápida é agora ₿ {amount}.</accent> Aprove para aceder rapidamente aos seus fundos ou aguarde ±30 min. + Taxa da transferência rápida\n<accent>alterada</accent> + A adicionar ao saldo de gastos + Taxa da transferência rápida alterada + A usar velocidade de transferência normal + Fantástico! + Aguarde, a transferência dos seus fundos está em curso. Isto deve demorar <accent>alguns minutos.</accent> + Aguarde, a transferência dos seus fundos está em curso. Isto deve demorar <accent>cerca de 30 minutos.</accent> + Transferência rápida\n<accent>indisponível</accent> Spark Taxa de resgate %1$d/3 confirmações @@ -123,6 +159,7 @@ Transferência\n<accent>concluída</accent> Endereços de taxas de emergência anteriores As transferências forçadas anteriores usaram estes endereços de taxas de emergência. As moedas que ficarem num deles continuam suas: gaste-as com a sua frase de recuperação e o respetivo caminho de derivação. + Caminho de derivação {amount} foi movido on-chain pelos operadores da Spark e não está na Spark. Os operadores ainda o podem libertar para si. {amount} fica na Spark. Não foi possível recuperar nada. @@ -212,11 +249,14 @@ O seu saldo de gastos usa a Spark, operada pela Lightspark, Breez e Flashnet. A sua segurança depende de pelo menos um operador agir com honestidade. Os operadores podem suspender o acesso, e levantar sem a cooperação deles exige que inicie uma saída on-chain. Saldo de Gastos Transfira para seu <accent>saldo de gastos</accent> - Transferir do Saldo de Poupança + Transferir da poupança Configuração manual Transferir\n<accent>para gastos</accent> + A Bitkit não conseguiu obter as taxas desta transferência. Verifique a sua ligação e tente novamente. est. máx. + O máximo que pode transferir é agora {amount}, porque as taxas ou o seu saldo de poupança mudaram enquanto estava neste ecrã. Deslize novamente para confirmar. + Montante alterado Pronto em cerca de 30 minutos Transf. fundos Por favor\n<accent>confirme</accent> @@ -226,8 +266,8 @@ Abrir Trezor Connect 25% Saldo de gastos Máximo - Transfira mais de ₿ {amount} para cobrir as taxas de a adicionar ao seu saldo de gastos. - Montante demasiado baixo + É necessário um mínimo de ₿ {amount} para configurar o seu saldo de gastos. + Saldo mínimo da poupança O valor que você pode transferir para seu saldo de gastos está atualmente limitado a ₿ {amount}. Taxa da rede A Bitkit não conseguiu obter as taxas atuais desta transferência. Verifique a sua ligação e tente novamente. @@ -281,7 +321,7 @@ Saldo de Poupança Insuficiente Poupança Saldo de gastos - Transfer\n<accent>speed</accent> + Velocidade da\n<accent>transferência</accent> Capacidade de recebimento Nó Lightning ID do LDK Node @@ -842,6 +882,7 @@ Single Random Draw Configurações do sistema Idioma + Mover para a Spark Carteira Atividade Contatos @@ -851,6 +892,7 @@ Ajustes Status do Aplicativo Suporte + A Bitkit não consegue confirmar que esta fatura não foi paga antes de restaurar a sua carteira. Peça uma nova fatura. Falha ao enviar o recibo A enviar recibo Recibo enviado @@ -859,6 +901,7 @@ Enviar Bitcoin Este contacto não tem nenhum método de pagamento que a Bitkit possa usar agora. Não é possível pagar a este contacto + Um levantamento anterior do seu saldo de gastos ainda está a ser concluído. Tente novamente quando terminar. As transferências para o saldo de gastos já não estão disponíveis. A Bitkit verifica primeiro a rede e depois devolve as moedas desta transferência à sua carteira, para que a transferência original nunca seja confirmada. Isto tem uma taxa de rede. Para Contato @@ -1058,7 +1101,7 @@ Gastos Mostrar Detalhes Receba no <accent>saldo de gastos</accent> - Aproveite transações instantâneas e baratas\ncom amigos, familiares\ne comerciantes. + Aproveite transações instantâneas e baratas com amigos, familiares e comerciantes. Transação Substituída Sua transação foi substituída por um aumento de taxa Transação Recebida Substituída @@ -1373,7 +1416,7 @@ A sua transferência foi iniciada e está a ser <accent>liquidada on-chain</accent>. O saldo de poupança será atualizado automaticamente quando terminar. Transferência\n<accent>a caminho</accent> O seu saldo com tecnologia Spark não pôde ser movido para a poupança e continua no saldo de gastos. - Não foi possível mover o saldo do Spark para a poupança; continua no saldo de gastos. As suas ligações estão a ser movidas para a poupança. + Os fundos dos seus canais estão a ser movidos para a poupança, mas o seu saldo Spark não pôde ser movido e fica no seu saldo de gastos. <accent>A ligar</accent>\nà rede Volte a ligar o seu dispositivo de hardware; parece estar desligado do telemóvel. Voltar a ligar o dispositivo diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index eeea28e188..26cc6c978c 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -170,7 +170,7 @@ Принудительный Перевод Не удалось инициировать перевод. Хотите выполнить принудительный перевод? Вы не сможете использовать эти средства в течение ±14 дней (!) Принудительный\n<accent>Перевод</accent> - Перевести из Сбережений + Перевести из сбережений Использовать другой кошелёк Перевести с аппаратного кошелька Баланс Расходов @@ -183,6 +183,31 @@ Можно Использовать Балансы Lightning Архивная высота мониторинга канала + Сумма + Ваш баланс переходит в Spark через Lightning — это самый дешёвый способ сохранить его в расходах. Комиссия за маршрутизацию ниже — максимум, который вы заплатите. + Перенос в\n<accent>Spark</accent> + Часть вашего баланса уже в Spark. Перенесите остаток так же, затем закройте опустевшее соединение. + Ваш баланс уже в Spark. Закройте опустевшее соединение, чтобы вернуть его резерв в сбережения. + Перенесено в\n<accent>Spark</accent> + В ваших Lightning-соединениях не осталось баланса для переноса. + Spark пока не готов к получению. Попробуйте ещё раз чуть позже. + Не удалось\n<accent>перенести</accent> + Что-то пошло не так при подготовке переноса. Попробуйте ещё раз. + Комиссия за маршрутизацию + Платёж в пути и появится в Spark после завершения. Если он не пройдёт, сумма останется в вашем соединении. + Перенос в\n<accent>Spark</accent> + Blocktank закрывает свои Lightning-соединения. Перенесите баланс в Spark сейчас: это самый дешёвый вариант, и средства остаются в расходах. + Ваше соединение\n<accent>закрывается</accent> + Перенести половину + Перенести сейчас + Перенести остаток + Перенос в Spark + Поиск маршрута и комиссии… + Проведите для переноса + Вместо этого закройте соединение, чтобы вернуть баланс в сбережения. + Вы можете перенести его меньшими частями. + %1$s слишком много для маршрутизации в Spark одним платежом. + Сумма\n<accent>слишком велика</accent> Лимит след. исходящего HTLC Мин. след. исходящего HTLC Прежде чем вы сможете перевести средства со своего баланса сбережений, вам нужно отправить биткойны в ваш кошелёк Bitkit. @@ -225,8 +250,19 @@ Перевод\n<accent>в Сбережения</accent> Пожалуйста, подождите, ваш перевод средств выполняется. Это займёт <accent>±10 секунд.</accent> Средства\n<accent>в Процессе Перевода</accent> + Перевод\n<accent>не удался</accent> Не удалось перевести в сбережения Время синхронизации оценок маршрутизации + Подтвердить + <accent>Комиссия за быстрый перевод теперь ₿ {amount}.</accent> Подтвердите, чтобы быстро получить доступ к средствам, или подождите ±30 мин. + Комиссия за быстрый перевод\n<accent>изменилась</accent> + Зачисление на баланс расходов + Комиссия за быстрый перевод изменилась + Используется обычная скорость перевода + Отлично! + Пожалуйста, подождите, идёт перевод ваших средств. Это займёт <accent>несколько минут.</accent> + Пожалуйста, подождите, идёт перевод ваших средств. Это займёт <accent>около 30 минут.</accent> + Быстрый перевод\n<accent>недоступен</accent> Продолжить Использование Bitkit Обработка Платежа Платеж Успешен @@ -254,6 +290,7 @@ Перевод\n<accent>завершён</accent> Прежние адреса экстренных комиссий Прежние принудительные переводы использовали эти адреса экстренных комиссий. Монеты на них остаются вашими: потратьте их с помощью фразы восстановления и пути деривации. + Путь деривации {amount} операторы Spark перевели ончейн, и этих средств больше нет в Spark. Операторы всё ещё могут выдать их вам. {amount} остаются в Spark. Ничего не удалось вернуть. @@ -347,17 +384,20 @@ Недостаточно Сбережений Сумма, которую вы можете перевести на баланс расходов, в настоящее время ограничена ₿ {amount}. Максимум Баланса Расходов - Переведите больше ₿ {amount}, чтобы покрыть комиссии за зачисление на баланс расходов. - Слишком маленькая сумма + Для настройки баланса расходов нужно не менее ₿ {amount}. + Минимум баланса сбережений 25% Перевод\n<accent>на Расходы</accent> На Баланс Расходов + Bitkit не удалось получить комиссии за этот перевод. Проверьте соединение и попробуйте ещё раз. прим. макс. Комиссии выросли на {amount}, потому что ставки комиссий или баланс сбережений изменились, пока вы были на этом экране. Проведите ещё раз для подтверждения. Комиссии изменились Готово через несколько минут Сервисные Комиссии + Максимум для перевода теперь {amount}, потому что ставки комиссий или ваш баланс сбережений изменились, пока вы были на этом экране. Проведите ещё раз для подтверждения. + Сумма изменилась Сетевые Комиссии Готово примерно через 30 минут Bitkit не смог получить текущие комиссии за этот перевод. Проверьте соединение и попробуйте снова. @@ -367,7 +407,7 @@ Переведите средства на свой баланс расходов, чтобы наслаждаться мгновенными и недорогими транзакциями с друзьями, семьёй и продавцами. Перевод\n<accent>на Расходы</accent> Баланс Расходов - Transfer\n<accent>speed</accent> + Скорость\n<accent>перевода</accent> Статус Поддержка Общий резерв Anchor каналов @@ -1028,6 +1068,7 @@ {count, plural, one {ВВОД} few {ВВОДЫ (#)} many {ВВОДЫ (#)} other {ВВОДЫ (#)}} Инвойс Заметка инвойса + Перенести в Spark Следующий месяц Пока нет транзакций Получите немного средств, чтобы начать @@ -1112,6 +1153,7 @@ Увеличьте заданную комиссию и попробуйте снова. Заметка Получен Биткоин + Bitkit не может подтвердить, что этот счёт не был оплачен до восстановления вашего кошелька. Запросите новый счёт. Пир отключён. Не удалось отправить квитанцию Отправка квитанции @@ -1123,9 +1165,7 @@ Инвойс скопирован в буфер обмена Лайтнинг инвойс Опциональная заметка для плательщика - Наслаждайтесь мгновенными и недорогими -транзакциями с друзьями, семьёй -и продавцами. + Наслаждайтесь мгновенными и недорогими транзакциями с друзьями, семьёй и продавцами. Получить на <accent>баланс расходов</accent> Показать детали Показать QR-код @@ -1177,6 +1217,7 @@ Резервный баланс У этого контакта сейчас нет способа оплаты, который может использовать Bitkit. Невозможно оплатить этому контакту + Предыдущий вывод с вашего баланса расходов ещё проводится. Попробуйте ещё раз после его завершения. Переводы на баланс расходов больше недоступны. Bitkit сначала проверяет сеть, а затем возвращает монеты этого перевода в ваш кошелёк, чтобы исходный перевод никогда не подтвердился. За это взимается сетевая комиссия. Этот платеж занимает больше времени, чем ожидалось. Вы можете продолжать использовать Bitkit. Платеж в ожидании @@ -1420,7 +1461,7 @@ Ваш перевод инициирован и <accent>проводится в блокчейне</accent>. Баланс сбережений обновится автоматически после завершения. Перевод\n<accent>в пути</accent> Баланс на базе Spark не удалось перевести в сбережения, он остаётся в балансе расходов. - Не удалось перевести баланс Spark в сбережения, он остаётся в балансе расходов. Ваши соединения переводятся в сбережения. + Средства ваших каналов переводятся в сбережения, но баланс Spark перевести не удалось, он остаётся на балансе расходов. <accent>Подключение</accent>\nк сети Переподключите аппаратное устройство: похоже, оно отключилось от телефона. Переподключите Аппаратное Устройство diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f06bfe34c6..829e675a3b 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1516,6 +1516,7 @@ {count, plural, one {INPUT} other {INPUTS (#)}} Invoice Invoice note + Move to Spark Next month No activity yet Receive some funds to get started diff --git a/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt b/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt index 7480bd4112..f429b7d1cd 100644 --- a/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt +++ b/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt @@ -71,6 +71,7 @@ class NotifyPaymentReceivedHandlerTest : BaseUnitTest() { @Before fun setUp() { + whenever { moveToSparkRepo.isMovePayment(any()) }.thenReturn(false) whenever(context.getString(R.string.notification__received__title)).thenReturn("Payment Received") whenever(context.getString(any(), any())).thenReturn("Received amount") whenever(settingsStore.data).thenReturn(settingsData) diff --git a/app/src/test/java/to/bitkit/models/BackupJsonTest.kt b/app/src/test/java/to/bitkit/models/BackupJsonTest.kt index a4c128c0c4..6b757dc4ab 100644 --- a/app/src/test/java/to/bitkit/models/BackupJsonTest.kt +++ b/app/src/test/java/to/bitkit/models/BackupJsonTest.kt @@ -19,6 +19,20 @@ import kotlin.test.assertNull /** Fixtures in `resources/ios-backup` are bitkit-ios `BackupService` output, encoded by Swift's `JSONEncoder`. */ class BackupJsonTest { + @Test + fun `reads move to spark hashes and treats an unreadable value as none`() { + val base = """{"version":1,"createdAt":1,"tagMetadata":[],"cache":{}""" + + val readable = decodeBackup("""$base,"moveToSparkPaymentHashes":["aa","bb"]}""") + val unreadable = decodeBackup("""$base,"moveToSparkPaymentHashes":{"aa":1}}""") + val mixed = decodeBackup("""$base,"moveToSparkPaymentHashes":["aa",1]}""") + + assertEquals(listOf("aa", "bb"), readable.moveToSparkPaymentHashes) + assertEquals(emptyList(), unreadable.moveToSparkPaymentHashes) + assertEquals(emptyList(), mixed.moveToSparkPaymentHashes) + assertNull(decodeBackup("$base}").moveToSparkPaymentHashes) + } + @Test fun `decodes iOS metadata with omitted optionals`() { val backup = decodeBackup(iosFixture("metadata")) diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index a95531fae7..8ebe2f287b 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -97,10 +97,12 @@ import to.bitkit.models.WidgetsBackupV1 import to.bitkit.services.AddressDerivationInfo import to.bitkit.services.LightningService import to.bitkit.services.PaykitSdkService +import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture import to.bitkit.utils.AppError import java.io.File +import java.security.MessageDigest import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.TimeUnit @@ -239,6 +241,7 @@ class BackupRepoTest : BaseUnitTest() { whenever { sparkRepo.restoreExitBackup(any(), any()) }.thenReturn(Result.success(Unit)) whenever { sparkRepo.mergeRemoteExitBackup(anyOrNull()) }.thenReturn(Result.success(Unit)) whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(true) + whenever { sparkRepo.importStagedExitState() }.thenReturn(StagedExitImport.NothingStaged) whenever(sparkRepo.exitStateGeneration).thenReturn(exitStateGeneration) whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) @@ -417,6 +420,230 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `stored spark exit data spark can't import is kept apart and the upload goes through`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v9")) + .toByteArray() + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.mergeRemoteExitBackup(anyOrNull())) + .thenReturn(Result.failure(SparkError.ExitStateUnimportable())) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) + verify(sparkRepo).skipUnimportableRemoteExitState("v9") + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `stored spark exit data that doesn't parse is kept apart and the upload goes through`() = test { + val stored = "not exit data".toByteArray() + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) + verify(sparkRepo, never()).mergeRemoteExitBackup(anyOrNull()) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + + @Test + fun `a rejected spark exit copy already set aside is not uploaded again`() = test { + val stored = "not exit data".toByteArray() + stubUnreadableStoredExit(stored) + val key = BackupRepo.rejectedExitKey(stored) + whenever( + vssBackupClient.getObject(key) + ).thenReturn(Result.success(VssItem(key = key, value = stored, version = 1))) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + verify(vssBackupClient, never()).putObject(argThat { startsWith(BackupRepo.SPARK_EXIT_REJECTED_KEY) }, any()) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + + @Test + fun `each rejected spark exit copy goes under its own digest key and never the plain key`() = test { + val stored = "not exit data".toByteArray() + stubUnreadableStoredExit(stored) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + val digest = MessageDigest.getInstance("SHA-256").digest(stored).joinToString("") { "%02x".format(it) } + verify(vssBackupClient).putObject("${BackupRepo.SPARK_EXIT_REJECTED_KEY}_${digest.take(16)}", stored) + verify(vssBackupClient, never()).putObject(eq(BackupRepo.SPARK_EXIT_REJECTED_KEY), any()) + } + + private suspend fun stubUnreadableStoredExit(stored: ByteArray) { + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + } + + @Test + fun `staged exit data spark rejects is set aside as the stored backup that holds it`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v9")) + .toByteArray() + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) + verify(sparkRepo).discardStagedExitState("v9") + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `staged exit data spark rejects is set aside on its own once the stored backup moved on`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "newer")) + .toByteArray() + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + val kept = argumentCaptor() + verify( + vssBackupClient + ).putObject(argThat { startsWith("${BackupRepo.SPARK_EXIT_REJECTED_KEY}_") }, kept.capture()) + assertEquals( + SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "v9"), + json.decodeFromString(String(kept.firstValue)), + ) + verify(sparkRepo).discardStagedExitState("v9") + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + + @Test + fun `staged exit data spark rejects merges the stored backup another device replaced before the upload`() = test { + val newer = SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "newer") + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success( + VssItem( + key = BackupCategory.SPARK_EXIT.name, + value = json.encodeToString(newer).toByteArray(), + version = 2 + ) + ) + ) + // A merge already ran in this session, before another device stored newer exit data. + mergeFlagFollowsDiscard(hasMerged = true) + whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(sparkRepo).mergeRemoteExitBackup(newer) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `a rejected staged copy dropped before a failed merge still merges on the next upload`() = test { + val newer = SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "other device") + val stored = VssItem( + key = BackupCategory.SPARK_EXIT.name, + value = json.encodeToString(newer).toByteArray(), + version = 2 + ) + mergeFlagFollowsDiscard(hasMerged = true) + whenever(sparkRepo.importStagedExitState()) + .thenReturn(StagedExitImport.Rejected("v9", "regtest"), StagedExitImport.NothingStaged) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + // The copy is set aside and dropped, then the read for the merge fails. + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success(stored), + Result.failure(IllegalStateException("offline")), + Result.success(stored), + ) + assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(sparkRepo).mergeRemoteExitBackup(newer) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `stored exit data replaced while unreadable data was set aside is merged before the upload`() = test { + val unreadable = "not exit data".toByteArray() + val replaced = SparkExitBackupV1(createdAt = 600, network = "regtest", exitState = "other device") + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = unreadable, version = 1)), + Result.success( + VssItem( + key = BackupCategory.SPARK_EXIT.name, + value = json.encodeToString(replaced).toByteArray(), + version = 2 + ) + ), + ) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(unreadable), unreadable) + verify(sparkRepo).mergeRemoteExitBackup(replaced) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + verify(sparkRepo, never()).skipUnimportableRemoteExitState(anyOrNull()) + } + + @Test + fun `a spark exit merge that fails for another reason still blocks the upload`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v1")) + .toByteArray() + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.mergeRemoteExitBackup(anyOrNull())).thenReturn(Result.failure(AppError("not connected"))) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) + + verify(vssBackupClient, never()).putObject(argThat { startsWith(BackupRepo.SPARK_EXIT_REJECTED_KEY) }, any()) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + @Test fun `spark exit backup never replaces a stored one it could not read`() = test { whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) @@ -432,6 +659,20 @@ class BackupRepoTest : BaseUnitTest() { verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } + @Test + fun `a restore sets aside spark exit data it can't read and reports it not restored`() = test { + val stored = "not exit data".toByteArray() + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + + val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertTrue(BackupCategory.SPARK_EXIT in failed) + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) + verify(sparkRepo, never()).restoreExitBackup(any(), any()) + verify(cacheStore, never()).updateBackupStatus(eq(BackupCategory.SPARK_EXIT), any()) + } + @Test fun `a failed spark exit restore is reported as an incomplete restore`() = test { whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) @@ -1941,6 +2182,51 @@ class BackupRepoTest : BaseUnitTest() { assertEquals(mapOf(sparkWalletKey to expected), payload.sparkExitEarlierAddresses) } + @Test + fun `a metadata backup carries the move to spark hashes lowercase and sorted`() = test { + stubMetadataBackupReads() + cacheData.value = cacheData.value.copy(moveToSparkHashes = listOf("bb", "AA")) + val dataCaptor = argumentCaptor() + + sut.triggerBackup(BackupCategory.METADATA) + + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.METADATA.name), dataCaptor.capture()) } + val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) + assertEquals(listOf("aa", "bb"), payload.moveToSparkPaymentHashes) + } + + @Test + fun `a metadata backup leaves the move to spark hashes out with none`() = test { + stubMetadataBackupReads() + val dataCaptor = argumentCaptor() + + sut.triggerBackup(BackupCategory.METADATA) + + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.METADATA.name), dataCaptor.capture()) } + assertFalse("moveToSparkPaymentHashes" in dataCaptor.firstValue.decodeToString()) + } + + @Test + fun `a metadata restore adds the backed-up move to spark hashes to the device's`() = test { + whenever { cacheStore.update(any()) }.thenAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + cacheData.value = cacheData.value.copy(moveToSparkHashes = listOf("dd")) + val envelope = json.encodeToString( + MetadataBackupV1( + createdAt = 123, + tagMetadata = emptyList(), + cache = AppCacheData(moveToSparkHashes = listOf("cc")), + moveToSparkPaymentHashes = listOf("AA"), + ) + ) + stubMetadataRestore(envelope = envelope) + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertEquals(setOf("dd", "cc", "aa"), cacheData.value.moveToSparkHashes.toSet()) + } + @Test fun `a restore lists the backed-up earlier spark exit addresses and keeps the device's`() = test { val store = earlierAddressStore() @@ -3608,4 +3894,14 @@ class BackupRepoTest : BaseUnitTest() { isTrackingEnabled = true, setupState = WatchOnlyAccountSetupState.Authorizing, ) + + private fun mergeFlagFollowsDiscard(hasMerged: Boolean) { + var merged = hasMerged + whenever(sparkRepo.hasMergedRemoteExitState).thenAnswer { merged } + whenever { sparkRepo.discardStagedExitState(any()) }.doSuspendableAnswer { merged = false } + whenever { sparkRepo.mergeRemoteExitBackup(anyOrNull()) }.thenAnswer { + merged = true + Result.success(Unit) + } + } } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 625724b33f..2e60238226 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1986,6 +1986,7 @@ class LightningRepoTest : BaseUnitTest() { feePolicy = FeePolicy.FEES_EXCLUDED, ) whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.listPayments()).thenReturn(emptyList()) val sending = CompletableDeferred() whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { sending.await() } val spark = SparkRepo( diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 5ff73f3f3d..bb2f4f51bb 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -21,8 +21,11 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.data.AppCacheData +import to.bitkit.data.CacheStore import to.bitkit.ext.createChannelDetails import to.bitkit.test.BaseUnitTest +import to.bitkit.test.InMemoryDataStore import to.bitkit.utils.LdkError import kotlin.test.assertEquals import kotlin.test.assertIs @@ -40,6 +43,8 @@ class MoveToSparkRepoTest : BaseUnitTest() { private val lightningState = MutableStateFlow(LightningState()) private val nodeEvents = MutableSharedFlow() private val inFlight = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash", paymentId = "id") + private val cacheStore = CacheStore(InMemoryDataStore(AppCacheData())) + private val quote = MoveToSparkQuote(INVOICE, amountSats = 50_000uL, feeSats = 12uL) private lateinit var sut: MoveToSparkRepo @Before @@ -47,9 +52,11 @@ class MoveToSparkRepoTest : BaseUnitTest() { whenever(lightningRepo.lightningState).thenReturn(lightningState) whenever(sparkRepo.state).thenReturn(sparkState) whenever(lightningRepo.nodeEvents).thenReturn(nodeEvents) - sut = MoveToSparkRepo(testDispatcher, lightningRepo, sparkRepo) + sut = createSut() } + private fun createSut() = MoveToSparkRepo(testDispatcher, lightningRepo, sparkRepo, cacheStore) { "hash" } + private fun sendable(sats: ULong) { val channel = createChannelDetails().copy(isUsable = true, nextOutboundHtlcLimitMsat = sats * 1000uL) lightningState.value = LightningState(channels = persistentListOf(channel)) @@ -223,6 +230,69 @@ class MoveToSparkRepoTest : BaseUnitTest() { assertIs(sut.awaitSettled(inFlight).exceptionOrNull()) } + @Test + fun `an in-flight move whose outcome was missed while the node was down reads it once the node is back`() = test { + // The node can't list its payments at first, and the settling event came before the listener started. + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(null, listOf(nodeSend(PaymentStatus.SUCCEEDED))) + val settled = async(start = CoroutineStart.UNDISPATCHED) { sut.awaitSettled(inFlight) } + + assertEquals(MoveToSparkOutcome.Moved(50_000uL, feeSats = 7uL), settled.await().getOrThrow()) + } + + @Test + fun `move pays over the channels capped at the quoted fee and reports the fee paid`() = test { + whenever( + lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + ).thenReturn(Result.success("id")) + val moving = async { sut.move(quote) } + + nodeEvents.emit(Event.PaymentSuccessful("other", "other_hash", null, 1_000uL)) + nodeEvents.emit(Event.PaymentSuccessful("id", "hash", null, 9_000uL)) + + assertEquals(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL), moving.await().getOrThrow()) + verify(lightningRepo).payInvoiceOverLdk( + bolt11 = INVOICE, + paymentHash = "hash", + sats = 50_000uL, + maxTotalRoutingFeeMsat = 12_000uL, + ) + } + + @Test + fun `move matches a failure without its hash by the payment id`() = test { + whenever( + lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + ).thenReturn(Result.success("id")) + val moving = async { sut.move(quote) } + + nodeEvents.emit(Event.PaymentFailed("other", null, PaymentFailureReason.ROUTE_NOT_FOUND)) + nodeEvents.emit(Event.PaymentFailed("id", null, PaymentFailureReason.PAYMENT_EXPIRED)) + + val error = assertIs(moving.await().exceptionOrNull()) + assertEquals(PaymentFailureReason.PAYMENT_EXPIRED, error.reason) + } + + @Test + fun `move reports a payment without an outcome in time as in flight`() = test { + whenever( + lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + ).thenReturn(Result.success("id")) + // Nothing settles it, so the virtual clock runs to the end of the wait. + assertEquals(inFlight, sut.move(quote).getOrThrow()) + assertTrue(sut.isWatchedMovePayment("hash").not(), "a move no one waits on still mutes the app's notices") + } + + @Test + fun `a move's payment stays a move after a restart`() = test { + whenever( + lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + ).thenReturn(Result.success("id")) + sut.move(quote) + + assertTrue(createSut().isMovePayment("HASH"), "a restart forgot the move's payment") + assertTrue(!createSut().isMovePayment("other")) + } + private fun nodeSend(status: PaymentStatus) = PaymentDetails( id = "id", kind = PaymentKind.Bolt11(hash = "hash", preimage = null, secret = null, description = null, bolt11 = INVOICE), diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 5f0b45f337..eaefc24e54 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -1194,6 +1194,30 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertTrue(storedProofs.isEmpty()) } + @Test + fun `a lightning proof the node failed is kept while spark reads its retry pending`() = test { + val failed = mock { + on { id } doReturn PAYMENT_HASH + on { direction } doReturn PaymentDirection.OUTBOUND + on { status } doReturn PaymentStatus.FAILED + } + whenever(lightningRepo.getPayments()).thenReturn(Result.success(listOf(failed))) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(paymentRequestRecord())) + val request = paymentRequest(MethodId.Bolt11.rawValue) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.Bolt11.rawValue, "bitkit", PaykitPaymentProofKind.Lightning).getOrThrow() + repo.associateLightningPayment(request, PAYMENT_HASH, MethodId.Bolt11.rawValue, "bitkit").getOrThrow() + // Spark reads the retry pending, then, once its success event ended the hold, only the earlier failure. + whenever(lightningRepo.sparkLightningSend(PAYMENT_HASH)).thenReturn( + SparkLightningSend.Found(SparkPaymentStatus.PENDING, null), + SparkLightningSend.Found(SparkPaymentStatus.FAILED, null), + ) + + paymentProofRepo().reconcile() + + assertEquals(PAYMENT_HASH, storedProofs.single().paymentIdentifier) + } + @Test fun `lightning proof is removed when spark failed the send`() = test { whenever(lightningRepo.getPayments()).thenReturn(Result.success(emptyList())) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index aef2f50598..3d6dc9e827 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1,5 +1,6 @@ package to.bitkit.repositories +import androidx.datastore.core.DataStore import breez_sdk_spark.AutoOptimizationEvent import breez_sdk_spark.BitcoinAddressDetails import breez_sdk_spark.Bolt11InvoiceDetails @@ -37,6 +38,7 @@ import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first @@ -49,6 +51,7 @@ import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.coroutines.yield import org.junit.Before import org.junit.Rule import org.junit.Test @@ -56,6 +59,7 @@ import org.junit.rules.TemporaryFolder import org.lightningdevkit.ldknode.Event import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argThat import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.clearInvocations @@ -100,6 +104,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant @@ -109,6 +114,9 @@ import com.synonym.bitkitcore.PaymentType as ActivityPaymentType class SparkRepoTest : BaseUnitTest() { private companion object { const val ADDRESS = "bcrt1qsavings" + + /** How many turns a Spark list read yields to a retry starting its send. */ + const val RETRY_TURNS = 100 } private val sparkService = mock() @@ -130,7 +138,10 @@ class SparkRepoTest : BaseUnitTest() { override fun now() = this@SparkRepoTest.now } - private fun createSut(cacheStore: CacheStore = this.cacheStore) = SparkRepo( + private fun createSut( + cacheStore: CacheStore = this.cacheStore, + activityRepo: ActivityRepo = this.activityRepo, + ) = SparkRepo( bgDispatcher = testDispatcher, sparkService = sparkService, activityRepo = { activityRepo }, @@ -423,6 +434,39 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any(), anyOrNull()) } + @Test + fun `an unsynced spark refuses a pre-restore invoice the operators show failed`() = test { + assertUnsyncedRestoredSend(operatorStatus = PaymentStatus.FAILED, isSent = false) + } + + @Test + fun `an unsynced spark sends a pre-restore invoice the operators show no send of`() = test { + assertUnsyncedRestoredSend(operatorStatus = null, isSent = true) + } + + private suspend fun TestScope.assertUnsyncedRestoredSend(operatorStatus: PaymentStatus?, isSent: Boolean) { + val restored = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds, sparkRestoredAt = now.epochSeconds) + val store = CacheStore(InMemoryDataStore(restored), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL).copy(lastSyncedAt = null)) + val prepared = prepared(feeSats = 0uL, createdAt = (now.epochSeconds - 600).toULong(), expirySecs = 3_600uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) + sendStatus = { operatorStatus } + val sut = createSut(store) + sut.start(0).getOrThrow() + + val result = sut.payInvoice("lnbc1280n1send", 128uL) + + if (isSent) { + assertTrue(result.isSuccess) + verify(sparkService).send(any(), anyOrNull()) + } else { + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any(), anyOrNull()) + } + } + @Test fun `a synced spark refuses a pre-restore invoice its list lacks while operators can't be asked`() = test { val restoredAt = now.epochSeconds - 60 @@ -2321,17 +2365,56 @@ class SparkRepoTest : BaseUnitTest() { fun `instant claims early at once when the offer is within the ceiling`() = test { listDeposit() whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn(ClaimDepositOutcome.Submitted) + whenever { sparkService.claimDeposit("txid", 0u, 500uL) }.thenReturn(ClaimDepositOutcome.Submitted) whenever { sparkService.listPayments() }.thenReturn(emptyList(), listOf(depositPayment())) val sut = createSut() sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) advanceUntilIdle() - verify(sparkService).claimDeposit("txid", 0u, 300uL) + verify(sparkService).claimDeposit("txid", 0u, 500uL) assertEquals(SparkDepositClaim.Claimed, sut.depositClaims.value["txid"]) } + @Test + fun `instant stops quoting once spark waits for the early claim, and clears its cap at the normal speed`() = test { + listDeposit() + // Spark keeps the ceiling as the cap, so it claims a later offer within it by itself. + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) + whenever { sparkService.claimDeposit("txid", 0u, 500uL) } + .thenReturn(ClaimDepositOutcome.Deferred(ClaimDeferredReason.NoEarlyClaimAvailable)) + val sut = createSut() + + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + verify(sparkService, times(1)).fetchClaimQuote("txid", 0u) + verify(sparkService, times(1)).claimDeposit(any(), any(), any()) + verify(sparkService).claimDeposit("txid", 0u, 500uL) + assertEquals(SparkDepositClaim.Unavailable, sut.depositClaims.value["txid"]) + // Shown at the normal speed, so Spark no longer claims it early within the ceiling. + verify(sparkService).releaseDepositClaimFee("txid", 0u) + } + + @Test + fun `instant shows adding once spark claims a deposit it waited on`() = test { + val deposit = DepositInfo("txid", 0u, 50_000uL, false, null, null, null, null, null, null) + // Listed until Spark claims it early by itself, a few polls after it waited. + whenever { sparkService.listUnclaimedDeposits() } + .thenReturn(listOf(deposit), listOf(deposit), listOf(deposit), emptyList()) + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) + whenever { sparkService.claimDeposit("txid", 0u, 500uL) } + .thenReturn(ClaimDepositOutcome.Deferred(ClaimDeferredReason.NoEarlyClaimAvailable)) + val sut = createSut() + + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + verify(sparkService, times(1)).claimDeposit("txid", 0u, 500uL) + assertEquals(SparkDepositClaim.Adding, sut.depositClaims.value["txid"]) + verify(sparkService, never()).releaseDepositClaimFee(any(), any()) + } + @Test fun `instant asks the user when the early fee is over the ceiling`() = test { listDeposit() @@ -2366,9 +2449,9 @@ class SparkRepoTest : BaseUnitTest() { fun `instant shows the new price when the claim comes back repriced`() = test { listDeposit() whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + whenever { sparkService.claimDeposit("txid", 0u, 500uL) }.thenReturn( ClaimDepositOutcome.Deferred( - ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 450uL, maxFeeSats = 300uL) + ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 600uL, maxFeeSats = 500uL) ) ) val sut = createSut() @@ -2377,16 +2460,16 @@ class SparkRepoTest : BaseUnitTest() { advanceUntilIdle() val claim = assertIs(sut.depositClaims.value["txid"]) - assertEquals(450uL, claim.offer.earlyFeeSats) + assertEquals(600uL, claim.offer.earlyFeeSats) } @Test fun `wait after a claim time reprice clears the early claim cap`() = test { listDeposit() whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + whenever { sparkService.claimDeposit("txid", 0u, 500uL) }.thenReturn( ClaimDepositOutcome.Deferred( - ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 450uL, maxFeeSats = 300uL) + ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 600uL, maxFeeSats = 500uL) ) ) val sut = createSut() @@ -2404,9 +2487,9 @@ class SparkRepoTest : BaseUnitTest() { fun `wait clears the early claim cap again when another claim held the deposit`() = test { listDeposit() whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + whenever { sparkService.claimDeposit("txid", 0u, 500uL) }.thenReturn( ClaimDepositOutcome.Deferred( - ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 450uL, maxFeeSats = 300uL) + ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 600uL, maxFeeSats = 500uL) ) ) // The first call meets Spark's own sync claiming the deposit, which leaves the cap in place. @@ -2466,7 +2549,7 @@ class SparkRepoTest : BaseUnitTest() { fun `instant is unavailable when the provider declines the early claim`() = test { listDeposit() whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + whenever { sparkService.claimDeposit("txid", 0u, 500uL) }.thenReturn( ClaimDepositOutcome.Deferred(ClaimDeferredReason.ProviderDeclined("no")) ) val sut = createSut() @@ -2564,6 +2647,99 @@ class SparkRepoTest : BaseUnitTest() { assertEquals("hash", assertIs(events.single()).paymentHash) } + @Test + fun `a restore made before spark connects connects it and fails when spark rejects its exit data`() = test { + var isConnected = false + whenever(sparkService.isConnected).thenAnswer { isConnected } + whenever { sparkService.connect(any(), any()) }.thenAnswer { + isConnected = true + true + } + whenever { sparkService.importExitState(any()) }.thenAnswer { throw SdkException.InvalidInput("bad") } + val sut = createSut() + + val result = sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) + + assertIs(result.exceptionOrNull()) + verify(sparkService, times(1)).importExitState("s") + assertTrue(File(Env.sparkExitRestorePath(0)).exists()) + } + + @Test + fun `a restore made before spark connects connects it and imports its exit data`() = test { + var isConnected = false + whenever(sparkService.isConnected).thenAnswer { isConnected } + whenever { sparkService.connect(any(), any()) }.thenAnswer { + isConnected = true + true + } + whenever { sparkService.importExitState(any()) }.thenReturn(ImportUnilateralExitStateResponse(2u, 0u, 0u, 0u)) + val sut = createSut() + + val result = sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) + + assertTrue(result.isSuccess) + verify(sparkService, times(1)).importExitState("s") + assertFalse(File(Env.sparkExitRestorePath(0)).exists()) + } + + @Test + fun `a restore spark can't connect for keeps its exit data staged for spark's start`() = test { + whenever { sparkService.connect(any(), any()) }.thenAnswer { throw SdkException.Generic("offline") } + val sut = createSut() + + val result = sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) + + assertTrue(result.isSuccess) + verify(sparkService).connect(0, false) + verify(sparkService, never()).importExitState(any()) + assertTrue(File(Env.sparkExitRestorePath(0)).exists()) + } + + @Test + fun `a restore staged while spark's start imports older data keeps and imports its own`() = test { + File(Env.sparkExitRestorePath(0)).apply { parentFile?.mkdirs() }.writeText("old") + val importing = CompletableDeferred() + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.importExitState(any()) }.doSuspendableAnswer { + if (it.getArgument(0) == "old") importing.await() + ImportUnilateralExitStateResponse(1u, 0u, 0u, 0u) + } + val sut = createSut() + val start = async { sut.start(0) } + runCurrent() + val restore = async { + sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "new"), 0) + } + runCurrent() + + importing.complete(Unit) + + assertTrue(restore.await().isSuccess) + start.await().getOrThrow() + verify(sparkService).importExitState("new") + } + + @Test + fun `a restore that connects spark handles its events before the wallet starts`() = test { + var isConnected = false + whenever(sparkService.isConnected).thenAnswer { isConnected } + whenever { sparkService.connect(any(), any()) }.thenAnswer { + isConnected = true + true + } + whenever { sparkService.importExitState(any()) }.thenReturn(ImportUnilateralExitStateResponse(2u, 0u, 0u, 0u)) + val sut = createSut() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0).getOrThrow() + + sparkEvents.emit(SdkEvent.PaymentSucceeded(sentPayment(fees = 0))) + advanceUntilIdle() + + assertEquals("hash", assertIs(events.single()).paymentHash) + } + @Test fun `a restore whose exit data spark rejects fails and keeps it staged`() = test { whenever(sparkService.isConnected).thenReturn(true) @@ -2576,6 +2752,43 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(File(Env.sparkExitRestorePath(0)).exists()) } + @Test + fun `staged exit data spark rejects as invalid reads as rejected and stays until discarded`() = test { + whenever { sparkService.importExitState(any()) }.thenAnswer { throw SdkException.InvalidInput("bad") } + val sut = createSut() + sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) + whenever(sparkService.isConnected).thenReturn(true) + + assertEquals(StagedExitImport.Rejected("s", "regtest"), sut.importStagedExitState()) + sut.discardStagedExitState("other") + assertTrue(File(Env.sparkExitRestorePath(0)).exists()) + sut.discardStagedExitState("s") + assertFalse(File(Env.sparkExitRestorePath(0)).exists()) + } + + @Test + fun `dropping rejected staged exit data asks for the stored backup to be merged again`() = test { + val sut = createSut() + sut.mergeRemoteExitBackup(null).getOrThrow() + assertTrue(sut.hasMergedRemoteExitState) + + sut.discardStagedExitState("s") + + assertFalse(sut.hasMergedRemoteExitState) + } + + @Test + fun `staged exit data spark fails to import for another reason stays pending`() = test { + whenever { sparkService.importExitState(any()) }.thenAnswer { throw SdkException.Generic("offline") } + val sut = createSut() + sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) + + assertEquals(StagedExitImport.Pending, sut.importStagedExitState()) + whenever(sparkService.isConnected).thenReturn(true) + assertEquals(StagedExitImport.Pending, sut.importStagedExitState()) + assertTrue(File(Env.sparkExitRestorePath(0)).exists()) + } + @Test fun `a failed withdrawal keeps the balance shown while spark reads zero`() = test { whenever(sparkService.isConnected).thenReturn(true) @@ -3563,120 +3776,920 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `an uncertain spark retry stays held after a restart while spark lists only its older failure`() = test { - assertUncertainRetryHeldAfterRestart(syncError = null) - } + fun `a failure spark reports during a send call is no settled send event`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + // An earlier attempt the pre-send list left out fails while the retry's send call runs. + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + listed = listOf(failed) + awaitCancellation() + } + val sut = createSut() + sut.start(0).getOrThrow() + runCurrent() + backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + advanceUntilIdle() - @Test - fun `an uncertain spark retry stays held after a restart whose first sync fails`() = test { - assertUncertainRetryHeldAfterRestart(syncError = SyncError.Network("operators unreachable")) + assertNull(sut.settledSendEvent("hash"), "a failure seen during the call settled the send") } - private suspend fun TestScope.assertUncertainRetryHeldAfterRestart(syncError: SyncError?) { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + @Test + fun `a failure listed while a spark send is in doubt is no settled send event`() = test { whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } - // An earlier attempt of the invoice failed, and the retry's outcome is unknown when the app stops. - whenever { sparkService.listPayments() } - .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) - ) - val before = createSut(store) - before.start(0).getOrThrow() - assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) - runCurrent() - - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncError = syncError, lastSyncedAt = now.epochSeconds.toULong() + 1uL) - ) - val after = createSut(store) - after.start(0).getOrThrow() + val sut = createSut() + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + // An earlier attempt on the invoice, or the doubtful send itself, shows as failed. + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) - assertTrue("hash" in store.data.first().sparkSendHashes, "A restart released a retry Spark may resume") - assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) - assertEquals(EarlierSend.Pending("hash"), after.earlierLightningSend("lnbc1", "hash")) + assertNull(sut.settledSendEvent("hash"), "a send in doubt settled as failed") } @Test - fun `a spark retry cut off by process death stays held after a restart while spark lists only its older failure`() = - test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = unexpiredPrepared() - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - // The process dies inside Spark's send call, so the call never returns. - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } - whenever { sparkService.listPayments() } - .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) - val before = createSut(store) - before.start(0).getOrThrow() - backgroundScope.launch { before.payInvoice("lnbc1", 100uL) } - runCurrent() + fun `an earlier attempt's late failure event leaves a spark send in doubt pending`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + clearInvocations(activityRepo) - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) - ) - val after = createSut(store) - after.start(0).getOrThrow() + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(earlier)) + sparkEvents.emit(SdkEvent.PaymentFailed(earlier)) + advanceUntilIdle() - assertEquals( - EarlierSend.Pending("hash"), - after.earlierLightningSend("lnbc1", "hash"), - "A restart released a retry Spark may resume to the node", - ) - assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) - } + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + verify(sparkService, times(1)).send(any(), anyOrNull()) + assertTrue(events.none { it is Event.PaymentFailed }, "a send Spark may still finish was reported failed") + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + } @Test - fun `a cancelled spark retry stays held while spark lists only its older failure`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + fun `an earlier attempt's late failure event leaves a retry spark took pending`() = test { + whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) val prepared = unexpiredPrepared() - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } - whenever { sparkService.listPayments() } - .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) - val sut = createSut(store) + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING, timestamp = 5uL) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(retry) + val sut = createSut() sut.start(0).getOrThrow() - val sending = launch { sut.payInvoice("lnbc1", 100uL) } - runCurrent() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + clearInvocations(activityRepo) - sending.cancel() - runCurrent() + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(retry, earlier)) + sparkEvents.emit(SdkEvent.PaymentFailed(earlier)) + advanceUntilIdle() - assertEquals( - EarlierSend.Pending("hash"), - sut.earlierLightningSend("lnbc1", "hash"), - "A cancelled send released a retry Spark may resume to the node", + assertTrue(events.none { it is Event.PaymentFailed }, "an earlier attempt's failure failed the retry") + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } ) - assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) } @Test - fun `an uncertain spark retry past an older failure reads as pending to paykit and quickpay`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - store.addSparkSendHash("hash", expiresAt = now.epochSeconds + 3_600) - store.addSparkUncertainSend("hash", now.epochSeconds) + fun `a retry spark took stays held while spark lists only an earlier attempt's failure`() = test { + whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) - whenever { sparkService.listPayments() } - .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) - val sut = createSut(store) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING, timestamp = 5uL) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(taken) + val sut = createSut() sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() - assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) - assertEquals( - PaymentStatus.PENDING, - sut.lightningSendStatuses()?.get("hash"), - "QuickPay reads an uncertain retry as failed", - ) - assertTrue( - "hash" in sut.attemptedLightningPaymentHashes().orEmpty(), - "Paykit reads an uncertain retry as never attempted", - ) - } + // Spark's list doesn't show the send it took yet, only the invoice's earlier failed attempt. + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(earlier)) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + verify(sparkService, times(1)).send(any(), anyOrNull()) + } + + @Test + fun `a spark retry whose success ends its hold while spark's list is read stays pending`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING, timestamp = 5uL) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(taken) + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(earlier)) + val sut = createSut() + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + + // The retry's success event ends its hold while the list is read, and the list lists only the earlier failure. + stubListEndingHoldWithSuccess(taken.copy(status = PaymentStatus.COMPLETED), earlier) + + val send = sut.lightningSend("hash") + + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), send, "a paid retry read as failed") + } + + @Test + fun `a spark retry whose success ends its hold while spark's list is read settles no send screen`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING, timestamp = 5uL) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(taken) + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(earlier)) + val sut = createSut() + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + assertNull(sut.settledSendEvent("hash")) + + // The retry's success event ends its hold while the list is read, and the list lists only the earlier failure. + stubListEndingHoldWithSuccess(taken.copy(status = PaymentStatus.COMPLETED), earlier) + + assertNull(sut.settledSendEvent("hash"), "a paid retry settled the send screen as failed") + } + + @Test + fun `a spark send whose caller was cancelled inside the send call ends at its invoice's expiry`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { awaitCancellation() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + val send = launch { sut.payInvoice("lnbc1", 100uL) } + runCurrent() + send.cancel() + advanceUntilIdle() + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + + // Spark never lists the send, and syncs after its invoice expired. + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertFalse("hash" in store.data.first().sparkUncertainSends, "a cancelled send stayed held past expiry") + assertNull(sut.earlierLightningSend("lnbc1", "hash")) + } + + @Test + fun `an older failure event leaves the row of a later failed attempt`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val later = sentPayment(fees = 0).copy(id = "later", status = PaymentStatus.FAILED, timestamp = 20uL) + val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(later, older)) + val sut = createSut() + sut.start(0).getOrThrow() + advanceUntilIdle() + clearInvocations(activityRepo) + + sparkEvents.emit(SdkEvent.PaymentFailed(older)) + advanceUntilIdle() + + verify(activityRepo, never()).upsertActivity(argThat { this is Activity.Lightning && v1.fee == 7uL }) + } + + @Test + fun `a spark send refused for its balance stays in flight until its hold is cleared`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.InsufficientFunds(null) } + val backing = InMemoryDataStore(AppCacheData()) + lateinit var sut: SparkRepo + val inFlightAtClear = mutableListOf() + // A sync's sweep skips a send in flight, so the saved hold must be cleared before the send leaves it. + val store = CacheStore( + object : DataStore { + override val data = backing.data + + override suspend fun updateData(transform: suspend (t: AppCacheData) -> AppCacheData): AppCacheData { + val wasHeld = "hash" in backing.data.first().sparkUncertainSends + val updated = backing.updateData(transform) + if (wasHeld && "hash" !in updated.sparkUncertainSends) { + inFlightAtClear += sut.isSendInFlight("hash") + } + return updated + } + }, + clock, + ) + sut = createSut(store) + sut.start(0).getOrThrow() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertTrue(inFlightAtClear.isNotEmpty() && inFlightAtClear.all { it }, "a sync could take back the hold") + assertFalse(sut.isSendInFlight("hash")) + assertNull(sut.earlierLightningSend("lnbc1", "hash")) + } + + @Test + fun `a sync while the poll settles a spark send in doubt reports its failure once`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val own = sentPayment(fees = 0).copy( + id = "own", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + // Spark lists the send's own failure once the send went out. + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { + listed = listOf(own) + throw SdkException.Generic("timeout") + } + val backing = InMemoryDataStore(AppCacheData()) + var isArmed = false + // Spark syncs while the poll clears the saved hold. + val store = CacheStore( + object : DataStore { + override val data = backing.data + + override suspend fun updateData(transform: suspend (t: AppCacheData) -> AppCacheData): AppCacheData { + val isClearing = "hash" in backing.data.first().sparkUncertainSends && + "hash" !in transform(backing.data.first()).sparkUncertainSends + if (isArmed && isClearing) { + isArmed = false + sparkEvents.emit(SdkEvent.Synced) + delay(1.seconds) + } + return backing.updateData(transform) + } + }, + clock, + ) + val sut = createSut(store) + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + isArmed = true + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure was reported twice") + } + + @Test + fun `a spark send's own failure the poll settled first is reported once`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val own = sentPayment(fees = 0).copy( + id = "own", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + whenever(sparkService.listPayments()).thenReturn(listOf(own)) + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + // Spark's callback for the same payment arrives after the poll settled it. + sparkEvents.emit(SdkEvent.PaymentFailed(own)) + advanceUntilIdle() + + assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure was reported twice") + } + + @Test + fun `a spark retry spark never lists reports its failure at expiry past a reported earlier failure`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(earlier)) + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sparkEvents.emit(SdkEvent.PaymentFailed(earlier)) + advanceUntilIdle() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(2, events.count { it is Event.PaymentFailed }, "the retry's failure was never reported") + } + + @Test + fun `a retry read as pending while the poll settles a send keeps its own success event`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + val own = sentPayment(fees = 0).copy( + id = "own", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + val retry = sentPayment(fees = 0).copy( + id = "retry", + status = PaymentStatus.PENDING, + timestamp = now.epochSeconds.toULong() + 1uL, + ) + // The poll reads the send's own failure, then a retry started meanwhile. + val reads = ArrayDeque(listOf(listOf(own), listOf(own))) + whenever(sparkService.listPayments()).thenAnswer { reads.removeFirstOrNull() ?: listOf(own, retry) } + advanceUntilIdle() + + val paid = retry.copy(status = PaymentStatus.COMPLETED) + whenever(sparkService.listPayments()).thenReturn(listOf(own, paid)) + sparkEvents.emit(SdkEvent.PaymentSucceeded(paid)) + advanceUntilIdle() + + assertTrue(events.any { it is Event.PaymentSuccessful }, "the retry's success was never reported") + } + + @Test + fun `a retry that enters spark's send call as the poll settles a send keeps its screen off the failure`() = test { + val events = settleWithRetryEntering(mutableListOf()) + + assertTrue(events.none { it is Event.PaymentFailed }, "the earlier send's failure reached the retry's screen") + } + + @Test + fun `a retry that enters spark's send call as the poll settles a send keeps its saved expiry`() = test { + val records = mutableListOf() + + settleWithRetryEntering(records) + + assertEquals("add", records.last(), "the poll dropped the retry's saved send: $records") + } + + @Test + fun `a retry entering spark's send call during a failure event keeps its hold and its screen`() = + test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy( + id = "failed", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + val retrySending = CompletableDeferred() + var sends = 0 + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + if (++sends == 1) failed else retrySending.await() + } + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + val records = mutableListOf() + whenever { cacheStore.addSparkSendHash(any(), anyOrNull()) }.doSuspendableAnswer { records += "add" } + whenever { cacheStore.removeSparkSendHash(any()) }.doSuspendableAnswer { records += "remove" } + whenever { cacheStore.addSparkUncertainSend(any(), any()) }.doSuspendableAnswer { records += "hold" } + whenever { cacheStore.removeSparkUncertainSend(any()) }.doSuspendableAnswer { records += "unhold" } + val sut = createSut() + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + var isArmed = true + // The retry enters Spark's send call while the failure event writes its row. + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + if (isArmed) { + isArmed = false + backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + var turns = 0 + while (!sut.isSendInFlight("hash") && turns++ < RETRY_TURNS) yield() + } + Result.success(Unit) + } + records.clear() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + advanceUntilIdle() + + assertTrue(sut.isSendInFlight("hash"), "the retry never entered Spark's send call") + assertEquals(listOf("add", "hold"), records, "the failure event dropped the retry's hold or saved send") + assertTrue(events.none { it is Event.PaymentFailed }, "the earlier failure reached the retry's screen") + } + + /** Settles a send in doubt on its own failure while a retry starts right after the poll takes the hold. */ + private suspend fun TestScope.settleWithRetryEntering(records: MutableList): List { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val retrySending = CompletableDeferred() + var sends = 0 + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + if (++sends == 1) throw SdkException.Generic("timeout") + retrySending.await() + } + whenever { cacheStore.addSparkSendHash(any(), anyOrNull()) }.doSuspendableAnswer { records += "add" } + whenever { cacheStore.removeSparkSendHash(any()) }.doSuspendableAnswer { records += "remove" } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + var isArmed = false + var isRetrying = false + whenever { cacheStore.removeSparkUncertainSend(any()) }.doSuspendableAnswer { + if (!isArmed) return@doSuspendableAnswer + isArmed = false + isRetrying = true + backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + val own = sentPayment(fees = 0).copy( + id = "own", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + // Spark lists only the earlier send's failure while the retry runs, and the poll's read after the take gives + // the retry the first chance to enter Spark's send call. + whenever { sparkService.listPayments() }.doSuspendableAnswer { + if (isRetrying) { + isRetrying = false + var turns = 0 + while (!sut.isSendInFlight("hash") && turns++ < RETRY_TURNS) yield() + } + listOf(own) + } + isArmed = true + advanceUntilIdle() + + assertTrue(sut.isSendInFlight("hash"), "the retry never entered Spark's send call") + return events + } + + @Test + fun `a spark send in doubt ends at once on its own failure`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + val startedAt = now.epochSeconds.toULong() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + // Spark dates a send's own failure at its start, by a clock that may run a few seconds behind the phone's. + val own = sentPayment(fees = 0).copy(id = "own", status = PaymentStatus.FAILED, timestamp = startedAt - 5uL) + whenever(sparkService.listPayments()).thenReturn(listOf(own)) + sparkEvents.emit(SdkEvent.PaymentFailed(own)) + advanceUntilIdle() + + assertEquals("hash", assertIs(events.single()).paymentHash) + verify(activityRepo).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + assertNull(sut.earlierLightningSend("lnbc1", "hash")) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sentPayment(fees = 0)) + sut.payInvoice("lnbc1", 100uL) + verify(sparkService, times(2)).send(any(), anyOrNull()) + } + + @Test + fun `a spark send in doubt fails its row once its invoice expires with only an earlier failure listed`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + // Spark dates the failure before the send started, so it may be an earlier attempt's. + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + advanceUntilIdle() + + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + verify(activityRepo).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + assertEquals("hash", assertIs(events.single()).paymentHash) + assertNull(sut.earlierLightningSend("lnbc1", "hash")) + } + + @Test + fun `a spark retry started within the clock margin of an earlier failure stays held while only that is listed`() = + test { + val (sut, events) = startRetryInMarginOfEarlierFailure() + + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL)) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + assertTrue(events.none { it is Event.PaymentFailed }, "An earlier attempt's failure ended the retry") + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status != PaymentState.PENDING } + ) + } + + @Test + fun `a spark retry in the clock margin of an earlier failure fails its own row in place at expiry`() = test { + val (_, events, store) = startRetryInMarginOfEarlierFailure() + val retryRow = storedSend(PaymentState.PENDING) + .copy(value = 200uL, fee = 7uL, timestamp = now.epochSeconds.toULong()) + var row = retryRow + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { + Result.success(Activity.Lightning(row)) + } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = (it.getArgument(0) as Activity.Lightning).v1 + Result.success(Unit) + } + + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals("hash", assertIs(events.single()).paymentHash) + assertEquals(retryRow.copy(status = PaymentState.FAILED), row) + + // The next start's sync lists only the earlier attempt's failure. + createSut(store).start(0).getOrThrow() + + assertEquals(retryRow.copy(status = PaymentState.FAILED), row, "A sync copied the earlier attempt's details") + } + + /** + * Attempt A fails, as Spark reports at once, and retry B starts 5 s later, within the clock margin of A's failure, + * with an unknown outcome while Spark lists only A's failure. + */ + private suspend fun TestScope.startRetryInMarginOfEarlierFailure(): Triple, CacheStore> { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val earlier = sentPayment(fees = 0).copy( + id = "earlier", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(earlier) + val sut = createSut(store) + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL).getOrThrow() + whenever { sparkService.listPayments() }.thenReturn(listOf(earlier)) + advanceUntilIdle() + + now += 5.seconds + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + clearInvocations(activityRepo) + return Triple(sut, events, store) + } + + @Test + fun `a spark send is refused before it goes out while spark can't list its payments`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sut = createSut(store) + sut.start(0).getOrThrow() + whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, never()).send(any(), anyOrNull()) + assertFalse("hash" in store.data.first().sparkUncertainSends) + assertFalse("hash" in store.data.first().sparkSendHashes) + } + + @Test + fun `a spark send held while a sync writes its list is not settled from that list`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + // The sync's list has no send of the invoice; Spark lists the send as pending once it went out. + var listed = listOf(receivedPayment()) + whenever(sparkService.listPayments()).thenAnswer { listed } + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { + listed = listed + sentPayment(fees = 0).copy(status = PaymentStatus.PENDING) + throw SdkException.Generic("timeout") + } + val sut = createSut(store) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + var isArmed = true + // The send starts while the sync writes its list, and its invoice expires before the sync settles holds. + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + if (isArmed) { + isArmed = false + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + now += 2.hours + } + Result.success(Unit) + } + + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertFalse(isArmed) + assertTrue(events.none { it is Event.PaymentFailed }, "A sync's older list failed a send Spark is paying") + } + + @Test + fun `a spark send that failed lets a retry of its invoice send again`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(failed) + val sut = createSut() + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + advanceUntilIdle() + + sut.payInvoice("lnbc1", 100uL) + + verify(sparkService, times(2)).send(any(), anyOrNull()) + } + + @Test + fun `a spark retry's success decides its activity row over an earlier attempt's failure`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val success = sentPayment(fees = 0).copy(id = "retry", timestamp = 5uL) + val earlierFailure = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever { sparkService.listPayments() }.thenReturn(listOf(success, earlierFailure)) + val sut = createSut() + + sut.start(0).getOrThrow() + + verify(activityRepo).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.SUCCEEDED } + ) + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + } + + @Test + fun `an uncertain spark retry stays held after a restart while spark lists only its older failure`() = test { + assertUncertainRetryHeldAfterRestart(syncError = null) + } + + @Test + fun `an uncertain spark retry stays held after a restart whose first sync fails`() = test { + assertUncertainRetryHeldAfterRestart(syncError = SyncError.Network("operators unreachable")) + } + + private suspend fun TestScope.assertUncertainRetryHeldAfterRestart(syncError: SyncError?) { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + // An earlier attempt of the invoice failed, and the retry's outcome is unknown when the app stops. + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val before = createSut(store) + before.start(0).getOrThrow() + assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = syncError, lastSyncedAt = now.epochSeconds.toULong() + 1uL) + ) + clearInvocations(activityRepo) + val after = createSut(store) + after.start(0).getOrThrow() + + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + assertTrue("hash" in store.data.first().sparkSendHashes, "A restart released a retry Spark may resume") + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) + assertEquals(EarlierSend.Pending("hash"), after.earlierLightningSend("lnbc1", "hash")) + } + + @Test + fun `a held spark send whose own failure a restart's sync lists frees its invoice without another read`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val before = createSut(store) + before.start(0).getOrThrow() + assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + assertTrue("hash" in store.data.first().sparkUncertainSends) + + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) + ) + // Spark lists the send's own failure to the restart's sync, and every read after it fails. + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + var isListed = true + whenever { sparkService.listPayments() }.doSuspendableAnswer { + if (isListed) listOf(failed) else throw SdkException.Generic("offline") + } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + isListed = false + Result.success(Unit) + } + val after = createSut(store) + after.start(0).getOrThrow() + + val cache = store.data.first() + assertFalse("hash" in cache.sparkUncertainSends, "A restart kept the hold of a send Spark listed as failed") + assertFalse("hash" in cache.sparkSendHashes, "A restart kept a failed send's invoice from the node") + } + + @Test + fun `a spark retry cut off by process death stays held after a restart while spark lists only its older failure`() = + test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + // The process dies inside Spark's send call, so the call never returns. + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + val before = createSut(store) + before.start(0).getOrThrow() + backgroundScope.launch { before.payInvoice("lnbc1", 100uL) } + runCurrent() + + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) + ) + val after = createSut(store) + after.start(0).getOrThrow() + + assertEquals( + EarlierSend.Pending("hash"), + after.earlierLightningSend("lnbc1", "hash"), + "A restart released a retry Spark may resume to the node", + ) + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) + } + + @Test + fun `a cancelled spark retry stays held while spark lists only its older failure`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + val sut = createSut(store) + sut.start(0).getOrThrow() + val sending = launch { sut.payInvoice("lnbc1", 100uL) } + runCurrent() + + sending.cancel() + runCurrent() + + assertEquals( + EarlierSend.Pending("hash"), + sut.earlierLightningSend("lnbc1", "hash"), + "A cancelled send released a retry Spark may resume to the node", + ) + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + } + + @Test + fun `an uncertain spark retry past an older failure reads as pending to paykit and quickpay`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + store.addSparkSendHash("hash", expiresAt = now.epochSeconds + 3_600) + store.addSparkUncertainSend("hash", now.epochSeconds) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + val sut = createSut(store) + sut.start(0).getOrThrow() + + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + assertEquals( + PaymentStatus.PENDING, + sut.lightningSendStatuses()?.get("hash"), + "QuickPay reads an uncertain retry as failed", + ) + assertTrue( + "hash" in sut.attemptedLightningPaymentHashes().orEmpty(), + "Paykit reads an uncertain retry as never attempted", + ) + } + + private fun stubListEndingHoldWithSuccess(completed: Payment, earlier: Payment) { + var isEnded = false + whenever { sparkService.listPayments() }.doSuspendableAnswer { + if (!isEnded) { + isEnded = true + sparkEvents.emit(SdkEvent.PaymentSucceeded(completed)) + delay(1.milliseconds) + } + listOf(earlier) + } + } private fun unexpiredPrepared(): PrepareSendPaymentResponse { val details = mock { @@ -3730,7 +4743,7 @@ class SparkRepoTest : BaseUnitTest() { advanceUntilIdle() // Spark resumes the send later and it fails. - val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) sparkEvents.emit(SdkEvent.PaymentFailed(failed)) advanceUntilIdle() diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index 709f0b5d51..d858b4459b 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -24,6 +24,7 @@ import org.lightningdevkit.ldknode.PeerDetails import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder @@ -61,6 +62,7 @@ import to.bitkit.services.PendingChannelMigration import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture import to.bitkit.test.idleSparkRepo +import to.bitkit.ui.settings.lightning.MoveToSparkManager import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError import to.bitkit.viewmodels.RestoreState @@ -92,6 +94,9 @@ class WalletViewModelTest : BaseUnitTest() { private val boltzService = mock() private val pubkySwapsRouteRepo = mock() private val sparkRepo = idleSparkRepo() + private val moveToSparkManager = mock { + on { hasRetainedMove } doReturn MutableStateFlow(false) + } private val lightningState = MutableStateFlow(LightningState()) private val walletState = MutableStateFlow(WalletState()) @@ -134,6 +139,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) } @@ -1247,6 +1253,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) assertEquals(RestoreState.Initial, testSut.restoreState.value) @@ -1316,6 +1323,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) testSut.start() @@ -1374,6 +1382,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) // Trigger restore to put state in non-idle @@ -1416,6 +1425,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) testSut.restoreWallet("mnemonic", null) @@ -1509,6 +1519,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) advanceUntilIdle() diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt index fc820e4d22..2b958f79a7 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt @@ -315,6 +315,33 @@ class SparkFundingViewModelTest : BaseUnitTest() { assertEquals("Changed", toasts.single().title) } + @Test + fun `swipe on a max transfer approves no higher instant claim fee than the one shown`() = test { + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), + ) + }.thenReturn(Result.success(OnchainSendOutcome.Accepted("txid", 99_700uL))) + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(sut.uiState.value.maxSats) + sut.onAmountContinue() + advanceUntilIdle() + // The network fee fell more than the claim fee rose, so more reaches spending and the swipe sends. + whenever { lightningRepo.estimateSendAllFee(any(), any(), any()) }.thenReturn(Result.success(300uL)) + whenever { sparkRepo.estimateDepositClaimFeeSats(any()) }.thenReturn(Result.success(1_400uL)) + + sut.onConfirm() + advanceUntilIdle() + + verify(sparkRepo).followDepositClaim("txid", SparkClaimSpeed.Instant, 1_350uL) + } + @Test fun `swipe refuses with real copy when savings no longer cover the transfer`() = test { val sut = createSut() diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt index 4ddc814c5a..1ede55ad0d 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt @@ -40,6 +40,7 @@ class LightningConnectionsViewModelTest : BaseUnitTest() { private val logsRepo = mock() private val activityRepo = mock() private val sparkRepo = mock() + private val hasRetainedMove = MutableStateFlow(false) private val lightningState = MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running)) private val lastKnownChannels = MutableStateFlow( @@ -76,6 +77,15 @@ class LightningConnectionsViewModelTest : BaseUnitTest() { assertEquals("channel_1", sut.uiState.value.openChannels.single().details.channelId) } + @Test + fun `a move kept for its result keeps move to spark offered once nothing is left to move`() = test { + hasRetainedMove.value = true + val sut = createViewModel() + advanceUntilIdle() + + assertTrue(sut.uiState.value.canMoveToSpark) + } + private fun createViewModel() = LightningConnectionsViewModel( context = context, bgDispatcher = testDispatcher, @@ -85,6 +95,7 @@ class LightningConnectionsViewModelTest : BaseUnitTest() { activityRepo = activityRepo, sparkRepo = sparkRepo, sparkExitRepo = mock { on { state } doReturn MutableStateFlow(SparkExitState()) }, + moveToSparkManager = mock { on { hasRetainedMove } doReturn hasRetainedMove }, healthRepo = mock { on { healthState } doReturn MutableStateFlow(AppHealthState()) }, ) } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt index fdb532eba4..cc870e26f8 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt @@ -9,6 +9,8 @@ import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.ext.createChannelDetails import to.bitkit.repositories.LightningRepo @@ -36,6 +38,7 @@ class MoveToSparkViewModelTest : BaseUnitTest() { private val secondMove = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash_2", paymentId = "id_2") private val firstSettled = CompletableDeferred>() private val secondSettled = CompletableDeferred>() + private val manager by lazy { MoveToSparkManager(testDispatcher, moveToSparkRepo, lightningRepo, walletRepo) } @Before fun setUp() { @@ -99,9 +102,66 @@ class MoveToSparkViewModelTest : BaseUnitTest() { return sut } - private fun createViewModel() = MoveToSparkViewModel( - moveToSparkRepo = moveToSparkRepo, - lightningRepo = lightningRepo, - walletRepo = walletRepo, - ) + @Test + fun `leaving the screen while a move runs keeps the move and shows it again`() = test { + val payment = CompletableDeferred>() + whenever(moveToSparkRepo.move(eq(quote))).doSuspendableAnswer { payment.await() } + createViewModel().move() + + manager.reset(screen = 1) + val reopened = createViewModel() + assertEquals(MoveToSparkUiState.Confirm(quote, isMoving = true), reopened.uiState.value) + + payment.complete(Result.success(moved)) + + assertEquals(MoveToSparkUiState.Done(moved, closeChannelId = null), reopened.uiState.value) + verify(moveToSparkRepo, times(1)).quote(anyOrNull()) + } + + @Test + fun `leaving the screen while a move is in flight keeps waiting for its outcome`() = test { + createViewModel().move() + + manager.reset(screen = 1) + val reopened = createViewModel() + firstSettled.complete(Result.success(moved)) + + assertEquals(MoveToSparkUiState.Done(moved, closeChannelId = null), reopened.uiState.value) + } + + @Test + fun `leaving the screen after a settled move quotes anew on return`() = test { + whenever(moveToSparkRepo.move(eq(quote))).thenReturn(Result.success(moved)) + createViewModel().move() + + manager.reset(screen = 1) + val reopened = createViewModel() + + assertEquals(MoveToSparkUiState.Confirm(quote), reopened.uiState.value) + verify(moveToSparkRepo, times(2)).quote(anyOrNull()) + } + + @Test + fun `a closed screen's late cleanup leaves the reopened screen's quote`() = test { + createViewModel() + val reopened = createViewModel() + + manager.reset(screen = 1) + + assertEquals(MoveToSparkUiState.Confirm(quote), reopened.uiState.value) + } + + @Test + fun `wiping the wallet drops an in-flight move and quotes anew on return`() = test { + createViewModel().move() + + manager.resetForWipe() + val reopened = createViewModel() + firstSettled.complete(Result.success(moved)) + + assertEquals(MoveToSparkUiState.Confirm(quote), reopened.uiState.value) + verify(moveToSparkRepo, times(2)).quote(anyOrNull()) + } + + private fun createViewModel() = MoveToSparkViewModel(manager) } diff --git a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt index 9f6c9c61d3..ffcaebbf5c 100644 --- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt @@ -42,6 +42,7 @@ import to.bitkit.services.MigrationService import to.bitkit.services.PaykitSdkService import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture +import to.bitkit.ui.settings.lightning.MoveToSparkManager import javax.inject.Provider import kotlin.test.assertFailsWith import kotlin.test.assertFalse @@ -74,6 +75,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { private val wakeRepo = mock() private val paykitSdkService = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() } private val privatePaykitRepoProvider = Provider { privatePaykitRepo } + private val moveToSparkManager = mock() private lateinit var sut: WipeWalletUseCase @@ -122,6 +124,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { paykitSdkService = paykitSdkService, connectionRecovery = connectionRecoveryFixture(settingsStore), wakeRepo = wakeRepo, + moveToSparkManager = Provider { moveToSparkManager }, ) } @@ -154,6 +157,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { privatePaykitAddressReservationRepo, migrationService, wakeRepo, + moveToSparkManager, ) inOrder.verify(backupRepo).setWiping(true) inOrder.verify(lightningRepo).setWiping(true) @@ -181,6 +185,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { inOrder.verify(blocktankRepo).resetState() inOrder.verify(activityRepo).resetState() inOrder.verify(hwWalletRepo).resetState() + inOrder.verify(moveToSparkManager).resetForWipe() inOrder.verify(migrationService).markMigrationChecked() assertTrue(onWipeCalled) assertTrue(onSetWalletExistsStateCalled) diff --git a/app/src/test/java/to/bitkit/viewmodels/ActivityListViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/ActivityListViewModelTest.kt index 856b72ca04..47e287a67f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/ActivityListViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/ActivityListViewModelTest.kt @@ -1,7 +1,9 @@ package to.bitkit.viewmodels import com.synonym.bitkitcore.Activity +import com.synonym.bitkitcore.LightningActivity import com.synonym.bitkitcore.OnchainActivity +import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.PaymentType import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf @@ -21,6 +23,7 @@ import to.bitkit.ext.rawId import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.ActivityState import to.bitkit.repositories.HwWalletRepo +import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.PubkyRepo import to.bitkit.test.BaseUnitTest import to.bitkit.ui.screens.wallets.activity.components.ActivityTab @@ -30,6 +33,7 @@ import kotlin.test.assertEquals class ActivityListViewModelTest : BaseUnitTest() { private val activityRepo = mock() + private val moveToSparkRepo = mock() private val hwWalletRepo = mock() private val pubkyRepo = mock() private val settingsStore = mock() @@ -47,6 +51,7 @@ class ActivityListViewModelTest : BaseUnitTest() { fun setUp() { hardwareActivities = MutableStateFlow(persistentListOf(hwActivity)) whenever(activityRepo.state).thenReturn(MutableStateFlow(ActivityState())) + whenever(moveToSparkRepo.moveHashes).thenReturn(MutableStateFlow(setOf("move"))) whenever(activityRepo.activitiesChanged).thenReturn(MutableStateFlow(0L)) whenever { activityRepo.syncActivities() }.thenReturn(Result.success(Unit)) whenever { activityRepo.getTxIdsInBoostTxIds(any()) }.thenReturn(emptySet()) @@ -71,6 +76,7 @@ class ActivityListViewModelTest : BaseUnitTest() { private fun createViewModel() = ActivityListViewModel( bgDispatcher = testDispatcher, activityRepo = activityRepo, + moveToSparkRepo = moveToSparkRepo, hwWalletRepo = hwWalletRepo, pubkyRepo = pubkyRepo, settingsStore = settingsStore, @@ -93,6 +99,33 @@ class ActivityListViewModelTest : BaseUnitTest() { assertEquals(listOf("db1"), sut.filteredActivities.value?.map { it.rawId() }) } + @Test + fun `a move to spark lists under other, failed too, and not under sent`() = test { + val move = lightningSend(id = "MOVE", status = PaymentState.FAILED) + whenever { + activityRepo.getActivities( + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + ) + }.thenReturn(Result.success(listOf(dbActivity, move))) + val sut = createViewModel() + + sut.setTab(ActivityTab.SENT) + advanceUntilIdle() + assertEquals(listOf("db1"), sut.filteredActivities.value?.map { it.rawId() }) + + sut.setTab(ActivityTab.OTHER) + advanceUntilIdle() + assertEquals(listOf("MOVE"), sut.filteredActivities.value?.map { it.rawId() }) + } + @Test fun `filtered activities exclude hardware activities when a tag filter is active`() = test { val sut = createViewModel() @@ -132,6 +165,18 @@ class ActivityListViewModelTest : BaseUnitTest() { job.cancel() } + private fun lightningSend(id: String, status: PaymentState) = Activity.Lightning( + LightningActivity.create( + walletId = "wallet0", + id = id, + txType = PaymentType.SENT, + status = status, + value = 1_000uL, + invoice = "lnbc", + timestamp = 150uL, + ) + ) + private fun onchainActivity( id: String, txType: PaymentType, diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 5b156caf60..6f313e3d07 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -1049,7 +1049,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { on { type } doReturn TimedSheetType.MOVE_TO_SPARK onBlocking { shouldShow() } doReturn false }, - moveToSparkRepo = mock { on { canMove } doReturn emptyFlow() }, + moveToSparkRepo = mock { + on { canMove } doReturn emptyFlow() + onBlocking { isMovePayment(any()) } doReturn false + }, formatMoneyValue = formatMoneyValue, widgetsRepo = widgetsRepo, wakeRepo = wakeRepo, @@ -18208,6 +18211,80 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(pendingPaymentRepo, never()).track(paymentHash) } + @Test + fun `pending spark send whose success was handled before it was tracked resolves as sent`() = test { + val bolt11 = "lnbcrt1sparkpending" + val paymentHash = "spark_hash" + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + // Spark's success was handled after the send returned pending, before the send screen tracked it. + whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + Event.PaymentSuccessful( + paymentId = paymentHash, + paymentHash = paymentHash, + paymentPreimage = "preimage", + feePaidMsat = 0uL, + ), + ) + whenever(pendingPaymentRepo.isPending(paymentHash)).thenReturn(true) + setSendState( + SendUiState( + address = bolt11, + amount = 1000u, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, amountSats = 1000u), + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + verify(pendingPaymentRepo).track(paymentHash) + verify(pendingPaymentRepo).resolve(PendingPaymentResolution.Success(paymentHash)) + } + + @Test + fun `pending spark send resolved as sent leaves the next send's contact alone`() = test { + val bolt11 = "lnbcrt1sparkpending" + val paymentHash = "spark_hash" + val nextContactKey = "pubkynext" + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + // The send screen moved on to a payment to a contact before the pending send's success was read. + whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenAnswer { + setActiveContactPaymentContext(nextContactKey) + Event.PaymentSuccessful( + paymentId = paymentHash, + paymentHash = paymentHash, + paymentPreimage = "preimage", + feePaidMsat = 0uL, + ) + } + whenever(pendingPaymentRepo.isPending(paymentHash)).thenReturn(true) + setSendState( + SendUiState( + address = bolt11, + amount = 1000u, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, amountSats = 1000u), + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + verify(pendingPaymentRepo).resolve(PendingPaymentResolution.Success(paymentHash)) + assertEquals(nextContactKey, activeContactPaymentContext()?.publicKey) + verify(activityRepo, never()).setContact( + contactPublicKey = eq(nextContactKey), + forPaymentId = eq(paymentHash), + syncLdkPayments = any(), + walletId = any(), + ) + } + @Test fun `private lightning pending payment consumes private list`() = test { val bolt11 = "lnbcrt1pending" diff --git a/changelog.d/next/1819.added.md b/changelog.d/next/1819.added.md new file mode 100644 index 0000000000..b71c93c681 --- /dev/null +++ b/changelog.d/next/1819.added.md @@ -0,0 +1 @@ +Moving funds to Spark now shows as a Move to Spark entry in Activity and keeps going after you leave its screen. diff --git a/changelog.d/next/1976.fixed.md b/changelog.d/next/1976.fixed.md new file mode 100644 index 0000000000..9b2b2547e8 --- /dev/null +++ b/changelog.d/next/1976.fixed.md @@ -0,0 +1 @@ +Fixed wallet restores reporting Spark exit data as restored when Spark rejects it. diff --git a/journeys/transfer/move-to-spark.xml b/journeys/transfer/move-to-spark.xml index f4e630a466..6c70503dce 100644 --- a/journeys/transfer/move-to-spark.xml +++ b/journeys/transfer/move-to-spark.xml @@ -24,6 +24,7 @@ Tap "Move To Spark" and verify the screen shows an amount (testTag "MoveToSparkAmount") and a routing fee (testTag "MoveToSparkFee") Swipe to move (testTag "MoveToSparkSwipe") and verify "Moved to Spark" shows the moved amount (testTag "MoveToSparkMoved") and "Close" (testTag "MoveToSparkClose") Tap "Close" (testTag "MoveToSparkClose"), then "Close" on the close confirmation, and verify Lightning Connections shows no channel under OPEN CONNECTIONS, only Spark via Breez, whose balance grew by the moved amount - Go back to Home, open Spending and verify the "Move To Spark" button is gone + Go back to Home and verify Activity lists a "Move to Spark" transfer row with the moved amount plus the routing fee, and that its detail screen is titled "Move to Spark" + Open Spending and verify the "Move To Spark" button is gone