Skip to content

Feature/ext the Result.of method #241

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,7 @@ inline fun <T> Result<T>.onFinished(action: () -> Unit): Result<T> {
action.invoke()
return this
}

inline fun <R> Result.Companion.of(block: () -> R): Result<R> {
return runCatching(block)
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
package com.dimension.maskbook.common.util

import com.dimension.maskbook.common.exception.NullTransactionReceiptException
import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.common.model.EthResponse
import com.dimension.maskbook.common.model.EthTransactionReceiptResponse
import com.dimension.maskbook.wallet.export.model.ChainType
Expand Down Expand Up @@ -57,7 +58,7 @@ object EthUtils {
value,
data,
)
val response = kotlin.runCatching {
val response = Result.of {
web3j.ethEstimateGas(transaction).sendAsync().get()
}.getOrElse {
return Result.failure(it)
Expand Down Expand Up @@ -95,7 +96,7 @@ object EthUtils {
val transaction = Transaction.createEthCallTransaction(
fromAddress, contractAddress, encodedFunction
)
val response: EthCall = kotlin.runCatching {
val response: EthCall = Result.of {
web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).sendAsync().get()
}.getOrElse {
return Result.failure(it)
Expand Down Expand Up @@ -155,7 +156,7 @@ object EthUtils {
): Result<EthResponse> {
val credentials = Credentials.create(privateKey)
val transaction = RawTransactionManager(web3j, credentials, chainType.chainId)
val response: EthSendTransaction = kotlin.runCatching {
val response: EthSendTransaction = Result.of {
if (chainType.supportEip25519) {
transaction.sendEIP1559Transaction(
chainType.chainId,
Expand Down Expand Up @@ -193,7 +194,7 @@ object EthUtils {
web3j: Web3j,
transactionHash: String,
): Result<EthTransactionReceiptResponse> {
val response = kotlin.runCatching {
val response = Result.of {
web3j.ethGetTransactionReceipt(transactionHash).sendAsync().get()
}.getOrElse {
return Result.failure(it)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
*/
package com.dimension.maskbook.extension.utils

import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.common.gecko.WebContentController
import com.dimension.maskbook.extension.export.model.ExtensionId
import com.dimension.maskbook.extension.export.model.ExtensionMessage
Expand Down Expand Up @@ -91,26 +92,26 @@ internal abstract class MessageChannel(
}

private fun onMessage(jsonObject: JSONObject) {
val messageId = runCatching {
val messageId = Result.of {
jsonObject.get("id")
}.getOrNull()
val result = runCatching {
val result = Result.of {
jsonObject.get("result")
}.getOrNull()?.toString()?.takeIf {
it != "null"
}
if (messageId != null && queue.containsKey(messageId)) {
queue.remove(messageId)?.trySend(result)
} else {
val method = runCatching {
val method = Result.of {
jsonObject.getString("method")
}.getOrNull()
val params = runCatching {
val params = Result.of {
jsonObject.get("params")
}.getOrNull()?.toString()?.takeIf {
it != "null"
}
val jsonrpc = kotlin.runCatching {
val jsonrpc = Result.of {
jsonObject.getString("jsonrpc")
}.getOrDefault("2.0")
if (method != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import androidx.lifecycle.viewModelScope
import com.dimension.maskbook.common.ext.asStateIn
import com.dimension.maskbook.common.ext.decodeBase64
import com.dimension.maskbook.common.ext.encodeBase64
import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.common.ui.barcode.barcodeBitmap
import com.dimension.maskbook.persona.R
import com.dimension.maskbook.persona.datasource.DbPersonaDataSource
Expand Down Expand Up @@ -79,7 +80,7 @@ class DownloadQrCodeViewModel(
context: Context,
uri: Uri,
) = withContext(Dispatchers.IO) {
runCatching {
Result.of {
personaQrCode.value?.let {
val pdfDocument = PdfDocument()
// A4 paper size is 792*1123
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ package com.dimension.maskbook.persona.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dimension.maskbook.common.ext.asStateIn
import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.common.ext.onFinished
import com.dimension.maskbook.persona.repository.IPersonaRepository
import com.dimension.maskbook.setting.export.SettingServices
Expand Down Expand Up @@ -57,7 +58,7 @@ class PersonaLogoutViewModel(

fun logout() = viewModelScope.launch {
_loadingState.value = true
runCatching {
Result.of {
repository.logout()
}.onFailure {
it.printStackTrace()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dimension.maskbook.common.ext.Validator
import com.dimension.maskbook.common.ext.asStateIn
import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.persona.export.PersonaServices
import com.dimension.maskbook.wallet.export.WalletServices
import kotlinx.coroutines.flow.MutableStateFlow
Expand All @@ -47,7 +48,7 @@ class IdentityViewModel(
}

suspend fun confirm(): Result<Unit> {
return runCatching {
return Result.of {
personaServices.createPersonaFromMnemonic(_identity.value.trim().split(" "), name)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ package com.dimension.maskbook.persona.viewmodel.recovery
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dimension.maskbook.common.ext.asStateIn
import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.persona.export.PersonaServices
import com.dimension.maskbook.wallet.export.WalletServices
import kotlinx.coroutines.flow.MutableStateFlow
Expand All @@ -45,7 +46,7 @@ class PrivateKeyViewModel(
}

suspend fun confirm(nickname: String = "persona1"): Result<Unit> {
return runCatching {
return Result.of {
personaServices.createPersonaFromPrivateKey(_privateKey.value.trim(), name = nickname)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ package com.dimension.maskbook.persona.viewmodel.register

import androidx.lifecycle.viewModelScope
import com.dimension.maskbook.common.ext.asStateIn
import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.common.viewmodel.BaseMnemonicPhraseViewModel
import com.dimension.maskbook.persona.repository.IPersonaRepository
import com.dimension.maskbook.wallet.export.WalletServices
Expand All @@ -47,7 +48,7 @@ class CreateIdentityViewModel(

override fun confirm() {
viewModelScope.launch {
runCatching {
Result.of {
personaRepository.createPersonaFromMnemonic(
_words.value.map { it.word },
personaName
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
package com.dimension.maskbook.setting.util

import com.dimension.maskbook.common.ext.msgPack
import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.setting.export.model.BackupMetaFile
import com.dimension.maskbook.setting.export.model.BackupWrongPasswordException
import com.dimension.maskbook.setting.model.RemoteBackupData
Expand Down Expand Up @@ -65,7 +66,7 @@ object EncryptUtils {
val key = SecretKeySpec(derivedKey.key, "AES")
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(remoteBackupData.paramIV))
kotlin.runCatching {
Result.of {
cipher.doFinal(remoteBackupData.encrypted)
}.onSuccess {
return msgPack.decodeFromByteArray(BackupMetaFile.serializer(), it)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import androidx.paging.PagingState
import androidx.room.withTransaction
import com.dimension.maskbook.common.bigDecimal.BigDecimal
import com.dimension.maskbook.common.ext.httpService
import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.common.ext.use
import com.dimension.maskbook.common.ext.useSuspend
import com.dimension.maskbook.common.util.EthUtils
Expand Down Expand Up @@ -195,7 +196,7 @@ internal class WalletRepository(
val balance =
services.debankServices.totalBalance(currentWallet.address).let { balance ->
balance.chainList?.map { chain ->
chain.id?.let { it1 -> runCatching { ChainID.valueOf(it1) }.getOrNull() }
chain.id?.let { it1 -> Result.of { ChainID.valueOf(it1) }.getOrNull() }
?.let {
when (it) {
ChainID.eth -> DbWalletBalanceType.eth
Expand Down Expand Up @@ -228,7 +229,7 @@ internal class WalletRepository(

val tokens = token.map {
val chainId =
kotlin.runCatching { it.chain?.let { it1 -> ChainID.valueOf(it1) } }.getOrNull()
Result.of { it.chain?.let { it1 -> ChainID.valueOf(it1) } }.getOrNull()
it.toDbToken(chainId)
}
val walletTokens = token.map {
Expand Down Expand Up @@ -859,7 +860,7 @@ internal class WalletRepository(
private suspend fun refreshPendingTransaction() {
val items = pendingTransaction.firstOrNull() ?: return
items.forEach {
runCatching {
Result.of {
Web3j.build(it.chainId.httpService).useSuspend { web3j ->
val result = web3j.ethGetTransactionReceipt(it.transactionHash).send()
if (result.transactionReceipt.orElse(null) != null) {
Expand All @@ -879,7 +880,7 @@ internal class WalletRepository(
override suspend fun createWalletBackup(): List<BackupWalletData> {
return database.walletDao().getAll().map {
val privateKey = WalletKey.load(it.storedKey.data).firstOrNull()
val mnemonic = kotlin.runCatching {
val mnemonic = Result.of {
privateKey?.exportMnemonic("")
}.getOrNull()
// TODO: support other coin types
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
*/
package com.dimension.maskbook.wallet.usecase

import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.wallet.export.model.ChainType
import com.dimension.maskbook.wallet.repository.ISendHistoryRepository
import com.dimension.maskbook.wallet.repository.IWalletContactRepository
Expand All @@ -30,14 +31,14 @@ class AddContactUseCase(
private val repository: IWalletContactRepository
) {
suspend operator fun invoke(address: String, name: String) =
runCatching { repository.addOrUpdate(address = address, name = name) }
Result.of { repository.addOrUpdate(address = address, name = name) }
}

class AddRecentAddressUseCase(
private val repository: ISendHistoryRepository
) {
suspend operator fun invoke(address: String, name: String) =
runCatching { repository.addOrUpdate(address = address, name = name) }
Result.of { repository.addOrUpdate(address = address, name = name) }
}

class GetAddressUseCase(
Expand Down Expand Up @@ -84,7 +85,7 @@ class GetRecentAddressUseCase(
class GetEnsAddressUseCase(
private val repository: IWalletRepository
) {
suspend operator fun invoke(chainType: ChainType, ensName: String) = runCatching {
suspend operator fun invoke(chainType: ChainType, ensName: String) = Result.of {
repository.getEnsAddress(
chainType = chainType,
name = ensName
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
*/
package com.dimension.maskbook.wallet.usecase

import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.wallet.export.model.WalletCollectibleData
import com.dimension.maskbook.wallet.repository.ICollectibleRepository
import com.dimension.maskbook.wallet.repository.IWalletRepository
Expand Down Expand Up @@ -56,7 +57,7 @@ class SendWalletCollectibleUseCase(
gasLimit: Double,
maxFee: Double,
maxPriorityFee: Double
) = runCatching {
) = Result.of {
suspendCoroutine<String> { continuation ->
repository.sendCollectibleWithCurrentWallet(
address = address,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
*/
package com.dimension.maskbook.wallet.usecase

import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.wallet.export.model.ChainType
import com.dimension.maskbook.wallet.services.WalletServices
import com.dimension.maskbook.wallet.services.model.EthGasFee
Expand Down Expand Up @@ -105,7 +106,7 @@ class GasFeeModel {
class GetSuggestGasFeeUseCase(
private val services: WalletServices,
) {
suspend operator fun invoke(chainType: ChainType?) = runCatching {
suspend operator fun invoke(chainType: ChainType?) = Result.of {
when (chainType) {
ChainType.eth -> GasFeeModel(
services.gasServices.ethGasFee()
Expand All @@ -127,7 +128,7 @@ class GetArrivesWithGasFeeUseCase(
private val services: WalletServices,
) {
private val unKnow = -1.0
suspend operator fun invoke(gasFee: GasFeeData, suggestGasFee: GasFeeModel) = runCatching {
suspend operator fun invoke(gasFee: GasFeeData, suggestGasFee: GasFeeModel) = Result.of {
with(services.gasServices.ethGas()) {
if (safeLowWait != null && fastestWait != null && fastWait != null && avgWait != null) {
when {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@
*/
package com.dimension.maskbook.wallet.usecase

import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.wallet.repository.IWalletRepository

class RefreshWalletUseCase(
private val repository: IWalletRepository
) {
suspend operator fun invoke() = runCatching { repository.refreshWallet() }
suspend operator fun invoke() = Result.of { repository.refreshWallet() }
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@
*/
package com.dimension.maskbook.wallet.usecase

import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.wallet.export.model.ChainType
import com.dimension.maskbook.wallet.repository.IWalletRepository

class SetCurrentChainUseCase(
private val repository: IWalletRepository
) {
operator fun invoke(chainType: ChainType) = runCatching { repository.setChainType(networkType = chainType) }
operator fun invoke(chainType: ChainType) = Result.of { repository.setChainType(networkType = chainType) }
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
package com.dimension.maskbook.wallet.usecase

import com.dimension.maskbook.common.bigDecimal.BigDecimal
import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.wallet.export.model.ChainType
import com.dimension.maskbook.wallet.export.model.TokenData
import com.dimension.maskbook.wallet.export.model.WalletTokenData
Expand All @@ -45,7 +46,7 @@ class SendTokenUseCase(
gasLimit: Double,
maxFee: Double,
maxPriorityFee: Double
) = runCatching {
) = Result.of {
suspendCoroutine<String> { continuation ->
repository.sendTokenWithCurrentWallet(
amount = amount,
Expand Down Expand Up @@ -76,7 +77,7 @@ class SendTransactionUseCase(
maxPriorityFee: Double,
data: String,
chainType: ChainType?,
) = runCatching {
) = Result.of {
val chain = chainType ?: repository.currentChain.first()?.chainType
suspendCoroutine<String> { continuation ->
repository.sendTransactionWithCurrentWallet(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@
*/
package com.dimension.maskbook.wallet.usecase

import com.dimension.maskbook.common.ext.of
import com.dimension.maskbook.setting.export.SettingServices
import kotlinx.coroutines.flow.firstOrNull

class VerifyPaymentPasswordUseCase(
private val service: SettingServices
) {
suspend operator fun invoke(pwd: String) = runCatching {
suspend operator fun invoke(pwd: String) = Result.of {
service.paymentPassword.firstOrNull()?.let {
if (it.isNotEmpty() && it == pwd) Unit else throw Error()
} ?: throw Error()
Expand Down