From 904d124e3c8b8bb6fa7708224eaefc9df4c9ad0f Mon Sep 17 00:00:00 2001 From: kubel Date: Tue, 2 Jul 2024 10:17:59 +0200 Subject: [PATCH 01/14] Remove fail-over logic --- .../internal/common/di/CoreNetworkModule.kt | 46 ++----------------- .../walletconnect/sample/common/Constants.kt | 2 +- 2 files changed, 4 insertions(+), 44 deletions(-) diff --git a/core/android/src/main/kotlin/com/walletconnect/android/internal/common/di/CoreNetworkModule.kt b/core/android/src/main/kotlin/com/walletconnect/android/internal/common/di/CoreNetworkModule.kt index 780813993c..62d48749e7 100644 --- a/core/android/src/main/kotlin/com/walletconnect/android/internal/common/di/CoreNetworkModule.kt +++ b/core/android/src/main/kotlin/com/walletconnect/android/internal/common/di/CoreNetworkModule.kt @@ -22,28 +22,21 @@ import com.walletconnect.foundation.network.data.service.RelayService import okhttp3.Authenticator import okhttp3.Interceptor import okhttp3.OkHttpClient -import okhttp3.Response import okhttp3.logging.HttpLoggingInterceptor import org.koin.android.ext.koin.androidApplication import org.koin.core.qualifier.named import org.koin.dsl.module -import java.io.IOException -import java.net.SocketTimeoutException import java.util.concurrent.TimeUnit -private var SERVER_URL: String = "" -private const val DEFAULT_RELAY_URL = "relay.walletconnect.com" private const val DEFAULT_BACKOFF_SECONDS = 5L @Suppress("LocalVariableName") @JvmSynthetic fun coreAndroidNetworkModule(serverUrl: String, connectionType: ConnectionType, sdkVersion: String, timeout: NetworkClientTimeout? = null, bundleId: String) = module { val networkClientTimeout = timeout ?: NetworkClientTimeout.getDefaultTimeout() - SERVER_URL = serverUrl - factory(named(AndroidCommonDITags.RELAY_URL)) { - val jwt = get().invoke(SERVER_URL) - Uri.parse(SERVER_URL) + val jwt = get().invoke(serverUrl) + Uri.parse(serverUrl) .buildUpon() .appendQueryParameter("auth", jwt) .appendQueryParameter("ua", get(named(AndroidCommonDITags.USER_AGENT))) @@ -74,42 +67,10 @@ fun coreAndroidNetworkModule(serverUrl: String, connectionType: ConnectionType, HttpLoggingInterceptor().apply { setLevel(HttpLoggingInterceptor.Level.BODY) } } - single(named(AndroidCommonDITags.FAIL_OVER_INTERCEPTOR)) { - Interceptor { chain -> - var request = chain.request() - var response: Response? = null - - if (request.url.host.contains(DEFAULT_RELAY_URL)) { - try { - response = chain.proceed(request) - - return@Interceptor response - } catch (e: Exception) { - when (e) { - is SocketTimeoutException, is IOException -> { - val failoverUrl = request.url.host.replace(".com", ".org") - val newHttpUrl = request.url.newBuilder().host(failoverUrl).build() - - request = request.newBuilder().url(newHttpUrl).build() - return@Interceptor chain.proceed(request) - } - else -> { - throw e - } - } - } finally { - response?.close() - } - } else { - return@Interceptor chain.proceed(request) - } - } - } - single(named(AndroidCommonDITags.AUTHENTICATOR)) { Authenticator { _, response -> response.request.run { - if (Uri.parse(SERVER_URL).host == this.url.host) { + if (Uri.parse(serverUrl).host == this.url.host) { this.newBuilder().url(get(named(AndroidCommonDITags.RELAY_URL))).build() } else { null @@ -121,7 +82,6 @@ fun coreAndroidNetworkModule(serverUrl: String, connectionType: ConnectionType, single(named(AndroidCommonDITags.OK_HTTP)) { OkHttpClient.Builder() .addInterceptor(get(named(AndroidCommonDITags.SHARED_INTERCEPTOR))) - .addInterceptor(get(named(AndroidCommonDITags.FAIL_OVER_INTERCEPTOR))) .authenticator((get(named(AndroidCommonDITags.AUTHENTICATOR)))) .writeTimeout(networkClientTimeout.timeout, networkClientTimeout.timeUnit) .readTimeout(networkClientTimeout.timeout, networkClientTimeout.timeUnit) diff --git a/sample/common/src/main/kotlin/com/walletconnect/sample/common/Constants.kt b/sample/common/src/main/kotlin/com/walletconnect/sample/common/Constants.kt index 5a00d2490c..d4097db0aa 100644 --- a/sample/common/src/main/kotlin/com/walletconnect/sample/common/Constants.kt +++ b/sample/common/src/main/kotlin/com/walletconnect/sample/common/Constants.kt @@ -1,3 +1,3 @@ package com.walletconnect.sample.common -const val RELAY_URL = "relay.walletconnect.com" \ No newline at end of file +const val RELAY_URL = "relay.walletconnect.org" \ No newline at end of file From 2b7038287c603f0c487f2f33e47669a7a6ccbc3c Mon Sep 17 00:00:00 2001 From: kubel Date: Mon, 8 Jul 2024 10:14:55 +0200 Subject: [PATCH 02/14] Update Bouncy Castle --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 2470d9859b..786c6d34cc 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -22,7 +22,7 @@ scarlet = "1.0.1" koin = "3.5.6" retrofit = "2.11.0" okhttp = "4.12.0" -bouncyCastle = "1.77" +bouncyCastle = "1.78.1" sqlCipher = "4.5.4" multibase = "1.1.1" json = "20220924" From 864b8930f2c661a73f0a2311e21a8b70f61ff78d Mon Sep 17 00:00:00 2001 From: kubel Date: Mon, 8 Jul 2024 10:21:13 +0200 Subject: [PATCH 03/14] Change topic sent on approve session error --- .../sign/engine/use_case/calls/ApproveSessionUseCase.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/protocol/sign/src/main/kotlin/com/walletconnect/sign/engine/use_case/calls/ApproveSessionUseCase.kt b/protocol/sign/src/main/kotlin/com/walletconnect/sign/engine/use_case/calls/ApproveSessionUseCase.kt index 30bf4eb6a5..ae474d2be4 100644 --- a/protocol/sign/src/main/kotlin/com/walletconnect/sign/engine/use_case/calls/ApproveSessionUseCase.kt +++ b/protocol/sign/src/main/kotlin/com/walletconnect/sign/engine/use_case/calls/ApproveSessionUseCase.kt @@ -94,7 +94,7 @@ internal class ApproveSessionUseCase( onFailure = { error -> scope.launch { supervisorScope { - insertEventUseCase(Props(type = EventType.Error.SESSION_SETTLE_PUBLISH_FAILURE, properties = Properties(trace = trace, topic = sessionTopic.value))) + insertEventUseCase(Props(type = EventType.Error.SESSION_SETTLE_PUBLISH_FAILURE, properties = Properties(trace = trace, topic = pairingTopic.value))) } }.also { logger.error("Session settle failure on topic: $sessionTopic, error: $error") } onFailure(error) @@ -133,7 +133,7 @@ internal class ApproveSessionUseCase( } trace.add(Trace.Session.PROPOSAL_NOT_EXPIRED) SignValidator.validateSessionNamespace(sessionNamespaces.toMapOfNamespacesVOSession(), proposal.requiredNamespaces) { error -> - insertEventUseCase(Props(type = EventType.Error.SESSION_APPROVE_NAMESPACE_VALIDATION_FAILURE, properties = Properties(trace = trace, topic = proposal.pairingTopic.value))) + insertEventUseCase(Props(type = EventType.Error.SESSION_APPROVE_NAMESPACE_VALIDATION_FAILURE, properties = Properties(trace = trace, topic = pairingTopic))) .also { logger.log("Session approve failure - invalid namespaces, error: $error") } throw InvalidNamespaceException(error.message) } @@ -151,7 +151,7 @@ internal class ApproveSessionUseCase( onFailure = { error -> scope.launch { supervisorScope { - insertEventUseCase(Props(type = EventType.Error.SESSION_SUBSCRIPTION_FAILURE, properties = Properties(trace = trace, topic = sessionTopic.value))) + insertEventUseCase(Props(type = EventType.Error.SESSION_SUBSCRIPTION_FAILURE, properties = Properties(trace = trace, topic = pairingTopic))) } }.also { logger.error("Subscribe to session topic failure: $error") } onFailure(error) @@ -164,7 +164,7 @@ internal class ApproveSessionUseCase( onFailure = { error -> scope.launch { supervisorScope { - insertEventUseCase(Props(type = EventType.Error.SESSION_APPROVE_PUBLISH_FAILURE, properties = Properties(trace = trace, topic = sessionTopic.value))) + insertEventUseCase(Props(type = EventType.Error.SESSION_APPROVE_PUBLISH_FAILURE, properties = Properties(trace = trace, topic = pairingTopic))) } }.also { logger.error("Session approve failure, topic: $sessionTopic: $error") } onFailure(error) From 58eb509fd093ca292886a2c14dee1a3ecb6d15a3 Mon Sep 17 00:00:00 2001 From: kubel Date: Mon, 8 Jul 2024 10:59:57 +0200 Subject: [PATCH 04/14] Add new Core init method with projectId instead of Relay url --- .github/workflows/ci_relay.yml | 2 +- .github/workflows/ci_scheduled.yml | 2 +- .../android/test/utils/TestClient.kt | 8 +- .../walletconnect/android/CoreInterface.kt | 14 +- .../com/walletconnect/android/CoreProtocol.kt | 125 +++++++++++++----- .../ClientIdJwtRepositoryAndroidTest.kt | 2 +- .../repository/ClientIdJwtRepositoryTest.kt | 2 +- .../notify/test/utils/TestClient.kt | 17 ++- .../sign/test/utils/TestClient.kt | 31 ++++- .../sample/dapp/DappSampleApp.kt | 6 +- .../sample/modal/ModalSampleApp.kt | 4 +- .../sample/wallet/Web3WalletApplication.kt | 6 +- 12 files changed, 152 insertions(+), 67 deletions(-) diff --git a/.github/workflows/ci_relay.yml b/.github/workflows/ci_relay.yml index 576063f118..d0e3c2df9f 100644 --- a/.github/workflows/ci_relay.yml +++ b/.github/workflows/ci_relay.yml @@ -24,7 +24,7 @@ jobs: - name: Run Relay CI env: - TEST_RELAY_URL: wss://relay.walletconnect.com + TEST_RELAY_URL: wss://relay.walletconnect.org TEST_PROJECT_ID: ${{ secrets.WC_CLOUD_PROJECT_ID }} NOTIFY_INTEGRATION_TESTS_PROJECT_ID: ${{ secrets.NOTIFY_INTEGRATION_TESTS_PROJECT_ID }} NOTIFY_INTEGRATION_TESTS_SECRET: ${{ secrets.NOTIFY_INTEGRATION_TESTS_SECRET }} diff --git a/.github/workflows/ci_scheduled.yml b/.github/workflows/ci_scheduled.yml index dadbf5833f..e46908687c 100644 --- a/.github/workflows/ci_scheduled.yml +++ b/.github/workflows/ci_scheduled.yml @@ -27,7 +27,7 @@ jobs: - name: Run Relay CI env: - TEST_RELAY_URL: wss://relay.walletconnect.com + TEST_RELAY_URL: wss://relay.walletconnect.org TEST_PROJECT_ID: ${{ secrets.WC_CLOUD_PROJECT_ID }} with: SECRETS_PROPERTIES: ${{ secrets.SECRETS_PROPERTIES }} diff --git a/core/android/src/androidTest/kotlin/com/walletconnect/android/test/utils/TestClient.kt b/core/android/src/androidTest/kotlin/com/walletconnect/android/test/utils/TestClient.kt index 86865d856e..60ccf78263 100644 --- a/core/android/src/androidTest/kotlin/com/walletconnect/android/test/utils/TestClient.kt +++ b/core/android/src/androidTest/kotlin/com/walletconnect/android/test/utils/TestClient.kt @@ -21,7 +21,6 @@ import org.koin.core.qualifier.named import timber.log.Timber internal object TestClient { - const val RELAY_URL = "wss://relay.walletconnect.com?projectId=${BuildConfig.PROJECT_ID}" private val app = ApplicationProvider.getApplicationContext() fun KoinApplication.Companion.createNewWCKoinApp(): KoinApplication = KoinApplication.init().apply { createEagerInstances() } @@ -40,7 +39,7 @@ internal object TestClient { private val coreProtocol = CoreClient.apply { Timber.d("Primary CP start: ") - initialize(metadata, RELAY_URL, ConnectionType.MANUAL, app, onError = ::globalOnError) + initialize(app, BuildConfig.PROJECT_ID, metadata, ConnectionType.MANUAL, onError = ::globalOnError) Relay.connect(::globalOnError) _isInitialized.tryEmit(true) Timber.d("Primary CP finish: ") @@ -72,7 +71,7 @@ internal object TestClient { private val coreProtocol = CoreProtocol(secondaryKoinApp).apply { Timber.d("Secondary CP start: ") - initialize(metadata, RELAY_URL, ConnectionType.MANUAL, app) { Timber.e(it.throwable) } + initialize(app, BuildConfig.PROJECT_ID, metadata, ConnectionType.MANUAL) { Timber.e(it.throwable) } // Override of previous Relay necessary for reinitialization of `eventsFlow` Relay = RelayClient(secondaryKoinApp) @@ -91,8 +90,5 @@ internal object TestClient { } internal val Relay get() = coreProtocol.Relay - internal val jsonRpcInteractor: JsonRpcInteractorInterface by lazy { secondaryKoinApp.koin.get() } - internal val keyManagementRepository: KeyManagementRepository by lazy { secondaryKoinApp.koin.get() } - } } diff --git a/core/android/src/main/kotlin/com/walletconnect/android/CoreInterface.kt b/core/android/src/main/kotlin/com/walletconnect/android/CoreInterface.kt index 76c531fbee..f80658faec 100644 --- a/core/android/src/main/kotlin/com/walletconnect/android/CoreInterface.kt +++ b/core/android/src/main/kotlin/com/walletconnect/android/CoreInterface.kt @@ -27,7 +27,7 @@ interface CoreInterface { fun initialize( metaData: Core.Model.AppMetaData, relayServerUrl: String, - connectionType: ConnectionType, + connectionType: ConnectionType = ConnectionType.AUTOMATIC, application: Application, relay: RelayConnectionInterface? = null, keyServerUrl: String? = null, @@ -35,4 +35,16 @@ interface CoreInterface { telemetryEnabled: Boolean = true, onError: (Core.Model.Error) -> Unit, ) + + fun initialize( + application: Application, + projectId: String, + metaData: Core.Model.AppMetaData, + connectionType: ConnectionType = ConnectionType.AUTOMATIC, + relay: RelayConnectionInterface? = null, + keyServerUrl: String? = null, + networkClientTimeout: NetworkClientTimeout? = null, + telemetryEnabled: Boolean = true, + onError: (Core.Model.Error) -> Unit, + ) } \ No newline at end of file diff --git a/core/android/src/main/kotlin/com/walletconnect/android/CoreProtocol.kt b/core/android/src/main/kotlin/com/walletconnect/android/CoreProtocol.kt index 2b507ffe1e..577bbe69af 100644 --- a/core/android/src/main/kotlin/com/walletconnect/android/CoreProtocol.kt +++ b/core/android/src/main/kotlin/com/walletconnect/android/CoreProtocol.kt @@ -76,44 +76,103 @@ class CoreProtocol(private val koinApp: KoinApplication = wcKoinApp) : CoreInter onError: (Core.Model.Error) -> Unit ) { try { - val bundleId: String = application.packageName - with(koinApp) { - androidContext(application) - require(relayServerUrl.isValidRelayServerUrl()) { "Check the schema and projectId parameter of the Server Url" } - modules( - module { single { ProjectId(relayServerUrl.projectId()) } }, - module { single(named(AndroidCommonDITags.TELEMETRY_ENABLED)) { TelemetryEnabled(telemetryEnabled) } }, - coreAndroidNetworkModule(relayServerUrl, connectionType.toCommonConnectionType(), BuildConfig.SDK_VERSION, networkClientTimeout, bundleId), - coreCommonModule(), - coreCryptoModule(), - ) + require(relayServerUrl.isValidRelayServerUrl()) { "Check the schema and projectId parameter of the Server Url" } - if (relay == null) { - Relay.initialize { error -> onError(Core.Model.Error(error)) } - } + setup( + application = application, + serverUrl = relayServerUrl, + projectId = relayServerUrl.projectId(), + telemetryEnabled = telemetryEnabled, + connectionType = connectionType, + networkClientTimeout = networkClientTimeout, + relay = relay, + onError = onError, + metaData = metaData, + keyServerUrl = keyServerUrl + ) + } catch (e: Exception) { + onError(Core.Model.Error(e)) + } + } - modules( - coreStorageModule(bundleId = bundleId), - pushModule(), - module { single { relay ?: Relay } }, - module { single { with(metaData) { AppMetaData(name = name, description = description, url = url, icons = icons, redirect = Redirect(redirect)) } } }, - module { single { Echo } }, - module { single { Push } }, - module { single { Verify } }, - coreJsonRpcModule(), - corePairingModule(Pairing, PairingController), - keyServerModule(keyServerUrl), - explorerModule(), - web3ModalModule(), - pulseModule(bundleId) - ) - } + override fun initialize( + application: Application, + projectId: String, + metaData: Core.Model.AppMetaData, + connectionType: ConnectionType, + relay: RelayConnectionInterface?, + keyServerUrl: String?, + networkClientTimeout: NetworkClientTimeout?, + telemetryEnabled: Boolean, + onError: (Core.Model.Error) -> Unit + ) { + try { + require(projectId.isEmpty()) { "Project Id cannot be empty" } - Verify.initialize() - Pairing.initialize() - PairingController.initialize() + setup( + application = application, + projectId = projectId, + telemetryEnabled = telemetryEnabled, + connectionType = connectionType, + networkClientTimeout = networkClientTimeout, + relay = relay, + onError = onError, + metaData = metaData, + keyServerUrl = keyServerUrl + ) } catch (e: Exception) { onError(Core.Model.Error(e)) } } + + private fun CoreProtocol.setup( + application: Application, + serverUrl: String? = null, + projectId: String, + telemetryEnabled: Boolean, + connectionType: ConnectionType, + networkClientTimeout: NetworkClientTimeout?, + relay: RelayConnectionInterface?, + onError: (Core.Model.Error) -> Unit, + metaData: Core.Model.AppMetaData, + keyServerUrl: String? + ) { + val bundleId: String = application.packageName + val relayServerUrl = if (serverUrl.isNullOrEmpty()) "wss://relay.walletconnect.org?projectId=$projectId" else serverUrl + + with(koinApp) { + androidContext(application) + modules( + module { single { ProjectId(projectId) } }, + module { single(named(AndroidCommonDITags.TELEMETRY_ENABLED)) { TelemetryEnabled(telemetryEnabled) } }, + coreAndroidNetworkModule(relayServerUrl, connectionType.toCommonConnectionType(), BuildConfig.SDK_VERSION, networkClientTimeout, bundleId), + coreCommonModule(), + coreCryptoModule(), + ) + + if (relay == null) { + Relay.initialize { error -> onError(Core.Model.Error(error)) } + } + + modules( + coreStorageModule(bundleId = bundleId), + pushModule(), + module { single { relay ?: Relay } }, + module { single { with(metaData) { AppMetaData(name = name, description = description, url = url, icons = icons, redirect = Redirect(redirect)) } } }, + module { single { Echo } }, + module { single { Push } }, + module { single { Verify } }, + coreJsonRpcModule(), + corePairingModule(Pairing, PairingController), + keyServerModule(keyServerUrl), + explorerModule(), + web3ModalModule(), + pulseModule(bundleId) + ) + } + + Verify.initialize() + Pairing.initialize() + PairingController.initialize() + } } \ No newline at end of file diff --git a/core/android/src/test/kotlin/com/walletconnect/android/internal/common/ClientIdJwtRepositoryAndroidTest.kt b/core/android/src/test/kotlin/com/walletconnect/android/internal/common/ClientIdJwtRepositoryAndroidTest.kt index e0f8f31ac4..0aa35f8b76 100644 --- a/core/android/src/test/kotlin/com/walletconnect/android/internal/common/ClientIdJwtRepositoryAndroidTest.kt +++ b/core/android/src/test/kotlin/com/walletconnect/android/internal/common/ClientIdJwtRepositoryAndroidTest.kt @@ -18,7 +18,7 @@ internal class ClientIdJwtRepositoryAndroidTest { private val keyChain = KeyChainMock() private val sut = spyk(ClientIdJwtRepositoryAndroid(keyChain)) private val tag = "key_did_keypair" - private val serverUrl = "wss://relay.walletconnect.com" + private val serverUrl = "wss://relay.walletconnect.org" // Expected JWT for given nonce private val expectedJWT = diff --git a/foundation/src/test/kotlin/com/walletconnect/foundation/crypto/data/repository/ClientIdJwtRepositoryTest.kt b/foundation/src/test/kotlin/com/walletconnect/foundation/crypto/data/repository/ClientIdJwtRepositoryTest.kt index 5d07ee1cbd..97913cf34a 100644 --- a/foundation/src/test/kotlin/com/walletconnect/foundation/crypto/data/repository/ClientIdJwtRepositoryTest.kt +++ b/foundation/src/test/kotlin/com/walletconnect/foundation/crypto/data/repository/ClientIdJwtRepositoryTest.kt @@ -19,7 +19,7 @@ internal class ClientIdJwtRepositoryTest { return "884ab67f787b69e534bfdba8d5beb4e719700e90ac06317ed177d49e5a33be5a" to "58e0254c211b858ef7896b00e3f36beeb13d568d47c6031c4218b87718061295" } }) - private val serverUrl = "wss://relay.walletconnect.com" + private val serverUrl = "wss://relay.walletconnect.org" // Expected JWT for given nonce private val expectedJWT = diff --git a/protocol/notify/src/androidTest/kotlin/com/walletconnect/notify/test/utils/TestClient.kt b/protocol/notify/src/androidTest/kotlin/com/walletconnect/notify/test/utils/TestClient.kt index 1ad9992735..5b88734d80 100644 --- a/protocol/notify/src/androidTest/kotlin/com/walletconnect/notify/test/utils/TestClient.kt +++ b/protocol/notify/src/androidTest/kotlin/com/walletconnect/notify/test/utils/TestClient.kt @@ -22,7 +22,6 @@ import org.koin.core.KoinApplication import timber.log.Timber internal object TestClient { - const val RELAY_URL = "wss://relay.walletconnect.com?projectId=${BuildConfig.PROJECT_ID}" private val app = ApplicationProvider.getApplicationContext() fun KoinApplication.Companion.createNewWCKoinApp(): KoinApplication = init().apply { createEagerInstances() } @@ -43,7 +42,7 @@ internal object TestClient { private val coreProtocol = CoreClient.apply { Timber.d("Primary CP start: ") - initialize(metadata, RELAY_URL, ConnectionType.MANUAL, app, onError = ::globalOnError) + initialize(app, BuildConfig.PROJECT_ID, metadata, ConnectionType.MANUAL, onError = ::globalOnError) Relay.connect(::globalOnError) } @@ -99,13 +98,23 @@ internal object TestClient { private val coreProtocol = CoreProtocol(secondaryKoinApp).apply { Timber.d("Secondary CP start: ") - initialize(metadata, RELAY_URL, ConnectionType.MANUAL, app) { Timber.e(it.throwable) } + initialize(app, BuildConfig.PROJECT_ID, metadata, ConnectionType.MANUAL) { Timber.e(it.throwable) } // Override of previous Relay necessary for reinitialization of `eventsFlow` Relay = RelayClient(secondaryKoinApp) // Override of storage instances and depending objects - secondaryKoinApp.modules(overrideModule(Relay, Pairing, PairingController, "test_secondary", RELAY_URL, ConnectionType.MANUAL, app.packageName)) + secondaryKoinApp.modules( + overrideModule( + Relay, + Pairing, + PairingController, + "test_secondary", + "wss://relay.walletconnect.org?projectId=${BuildConfig.PROJECT_ID}", + ConnectionType.MANUAL, + app.packageName + ) + ) // Necessary reinit of Relay, Pairing and PairingController Relay.initialize { Timber.e(it) } diff --git a/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/TestClient.kt b/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/TestClient.kt index 860d19f146..d37ba91d64 100644 --- a/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/TestClient.kt +++ b/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/TestClient.kt @@ -18,7 +18,6 @@ import org.koin.core.KoinApplication import timber.log.Timber internal object TestClient { - const val RELAY_URL = "wss://relay.walletconnect.com?projectId=${BuildConfig.PROJECT_ID}" private val app = ApplicationProvider.getApplicationContext() fun KoinApplication.Companion.createNewWCKoinApp(): KoinApplication = init().apply { createEagerInstances() } @@ -34,7 +33,7 @@ internal object TestClient { private val coreProtocol = CoreClient.apply { Timber.d("Wallet CP start: ") - initialize(metadata, RELAY_URL, ConnectionType.MANUAL, app, onError = ::globalOnError) + initialize(app, BuildConfig.PROJECT_ID, metadata, ConnectionType.MANUAL, onError = ::globalOnError) Relay.connect(::globalOnError) } @@ -64,13 +63,23 @@ internal object TestClient { private val coreProtocol = CoreProtocol(dappKoinApp).apply { Timber.d("Dapp CP start: ") - initialize(metadata, RELAY_URL, ConnectionType.MANUAL, app) { Timber.e(it.throwable) } + initialize(app, BuildConfig.PROJECT_ID, metadata, ConnectionType.MANUAL) { Timber.e(it.throwable) } // Override of previous Relay necessary for reinitialization of `eventsFlow` Relay = RelayClient(dappKoinApp) // Override of storage instances and depending objects - dappKoinApp.modules(overrideModule(Relay, Pairing, PairingController, "test_dapp", RELAY_URL, ConnectionType.MANUAL, app.packageName)) + dappKoinApp.modules( + overrideModule( + Relay, + Pairing, + PairingController, + "test_dapp", + "wss://relay.walletconnect.org?projectId=${BuildConfig.PROJECT_ID}", + ConnectionType.MANUAL, + app.packageName + ) + ) // Necessary reinit of Relay, Pairing and PairingController Relay.initialize { Timber.e(it) } @@ -105,13 +114,23 @@ internal object TestClient { private val coreProtocol = CoreProtocol(hybridKoinApp).apply { Timber.d("Hybrid CP start: ") - initialize(metadata, RELAY_URL, ConnectionType.MANUAL, app) { Timber.e(it.throwable) } + initialize(app, BuildConfig.PROJECT_ID, metadata, ConnectionType.MANUAL) { Timber.e(it.throwable) } // Override of previous Relay necessary for reinitialization of `eventsFlow` Relay = RelayClient(hybridKoinApp) // Override of storage instances and depending objects - hybridKoinApp.modules(overrideModule(Relay, Pairing, PairingController, "test_hybrid", RELAY_URL, ConnectionType.MANUAL, app.packageName)) + hybridKoinApp.modules( + overrideModule( + Relay, + Pairing, + PairingController, + "test_hybrid", + "wss://relay.walletconnect.org?projectId=${BuildConfig.PROJECT_ID}", + ConnectionType.MANUAL, + app.packageName + ) + ) // Necessary reinit of Relay, Pairing and PairingController Relay.initialize { Timber.e(it) } diff --git a/sample/dapp/src/main/kotlin/com/walletconnect/sample/dapp/DappSampleApp.kt b/sample/dapp/src/main/kotlin/com/walletconnect/sample/dapp/DappSampleApp.kt index cfcb6b960c..23ad54e0d6 100644 --- a/sample/dapp/src/main/kotlin/com/walletconnect/sample/dapp/DappSampleApp.kt +++ b/sample/dapp/src/main/kotlin/com/walletconnect/sample/dapp/DappSampleApp.kt @@ -6,9 +6,7 @@ import com.google.firebase.crashlytics.ktx.crashlytics import com.google.firebase.ktx.Firebase import com.walletconnect.android.Core import com.walletconnect.android.CoreClient -import com.walletconnect.android.relay.ConnectionType import com.walletconnect.sample.common.BuildConfig -import com.walletconnect.sample.common.RELAY_URL import com.walletconnect.sample.common.tag import com.walletconnect.wcmodal.client.Modal import com.walletconnect.wcmodal.client.WalletConnectModal @@ -19,7 +17,6 @@ class DappSampleApp : Application() { override fun onCreate() { super.onCreate() - val serverUri = "wss://$RELAY_URL?projectId=${BuildConfig.PROJECT_ID}" val appMetaData = Core.Model.AppMetaData( name = "Kotlin Dapp", description = "Kotlin Dapp Implementation", @@ -29,9 +26,8 @@ class DappSampleApp : Application() { ) CoreClient.initialize( - relayServerUrl = serverUri, - connectionType = ConnectionType.AUTOMATIC, application = this, + projectId = BuildConfig.PROJECT_ID, metaData = appMetaData, ) { Firebase.crashlytics.recordException(it.throwable) diff --git a/sample/modal/src/main/kotlin/com/walletconnect/sample/modal/ModalSampleApp.kt b/sample/modal/src/main/kotlin/com/walletconnect/sample/modal/ModalSampleApp.kt index 56560a9860..56288a6f30 100644 --- a/sample/modal/src/main/kotlin/com/walletconnect/sample/modal/ModalSampleApp.kt +++ b/sample/modal/src/main/kotlin/com/walletconnect/sample/modal/ModalSampleApp.kt @@ -8,7 +8,6 @@ import com.walletconnect.android.Core import com.walletconnect.android.CoreClient import com.walletconnect.android.relay.ConnectionType import com.walletconnect.sample.common.BuildConfig -import com.walletconnect.sample.common.RELAY_URL import com.walletconnect.sample.common.tag import com.walletconnect.web3.modal.client.Modal import com.walletconnect.web3.modal.client.Web3Modal @@ -19,7 +18,6 @@ class ModalSampleApp : Application() { override fun onCreate() { super.onCreate() - val serverUri = "wss://$RELAY_URL?projectId=${BuildConfig.PROJECT_ID}" val appMetaData = Core.Model.AppMetaData( name = "Kotlin Modals", description = "Kotlin Modals Lab Sample", @@ -29,7 +27,7 @@ class ModalSampleApp : Application() { ) CoreClient.initialize( - relayServerUrl = serverUri, + projectId = BuildConfig.PROJECT_ID, connectionType = ConnectionType.AUTOMATIC, application = this, metaData = appMetaData, diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/Web3WalletApplication.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/Web3WalletApplication.kt index 21f438e966..5c14ad244d 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/Web3WalletApplication.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/Web3WalletApplication.kt @@ -20,13 +20,11 @@ import com.walletconnect.android.CoreClient import com.walletconnect.android.cacao.signature.SignatureType import com.walletconnect.android.internal.common.di.AndroidCommonDITags import com.walletconnect.android.internal.common.wcKoinApp -import com.walletconnect.android.relay.ConnectionType import com.walletconnect.android.utils.cacao.sign import com.walletconnect.foundation.util.Logger import com.walletconnect.notify.client.Notify import com.walletconnect.notify.client.NotifyClient import com.walletconnect.notify.client.cacao.CacaoSigner -import com.walletconnect.sample.common.RELAY_URL import com.walletconnect.sample.common.initBeagle import com.walletconnect.sample.common.tag import com.walletconnect.sample.wallet.domain.EthAccountDelegate @@ -60,7 +58,6 @@ class Web3WalletApplication : Application() { EthAccountDelegate.application = this val projectId = BuildConfig.PROJECT_ID - val serverUrl = "wss://$RELAY_URL?projectId=$projectId" val appMetaData = Core.Model.AppMetaData( name = "Kotlin Wallet", description = "Kotlin Wallet Implementation", @@ -70,9 +67,8 @@ class Web3WalletApplication : Application() { ) CoreClient.initialize( - relayServerUrl = serverUrl, - connectionType = ConnectionType.AUTOMATIC, application = this, + projectId = projectId, metaData = appMetaData, onError = { error -> Firebase.crashlytics.recordException(error.throwable) From 403e8bd9e3b903deb41fa954a96a739409abaec6 Mon Sep 17 00:00:00 2001 From: kubel Date: Mon, 8 Jul 2024 11:14:08 +0200 Subject: [PATCH 05/14] Fix require condition --- .../src/main/kotlin/com/walletconnect/android/CoreProtocol.kt | 2 +- .../com/walletconnect/sample/wallet/Web3WalletApplication.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/android/src/main/kotlin/com/walletconnect/android/CoreProtocol.kt b/core/android/src/main/kotlin/com/walletconnect/android/CoreProtocol.kt index 577bbe69af..38ef934d36 100644 --- a/core/android/src/main/kotlin/com/walletconnect/android/CoreProtocol.kt +++ b/core/android/src/main/kotlin/com/walletconnect/android/CoreProtocol.kt @@ -107,7 +107,7 @@ class CoreProtocol(private val koinApp: KoinApplication = wcKoinApp) : CoreInter onError: (Core.Model.Error) -> Unit ) { try { - require(projectId.isEmpty()) { "Project Id cannot be empty" } + require(projectId.isNotEmpty()) { "Project Id cannot be empty" } setup( application = application, diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/Web3WalletApplication.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/Web3WalletApplication.kt index 5c14ad244d..7782187ae3 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/Web3WalletApplication.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/Web3WalletApplication.kt @@ -72,7 +72,7 @@ class Web3WalletApplication : Application() { metaData = appMetaData, onError = { error -> Firebase.crashlytics.recordException(error.throwable) - logger.error(error.throwable.stackTraceToString()) + println(error.throwable.stackTraceToString()) scope.launch { connectionStateFlow.emit(ConnectionState.Error(error.throwable.message ?: "")) } From f162df46a6c97bb3c72630a632d08e85a2e68860 Mon Sep 17 00:00:00 2001 From: kubel Date: Mon, 8 Jul 2024 12:56:08 +0200 Subject: [PATCH 06/14] Fix testing --- .../android/test/activity/WCInstrumentedActivityScenario.kt | 2 +- .../com/walletconnect/android/relay/NetworkClientTimeout.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/android/src/androidTest/kotlin/com/walletconnect/android/test/activity/WCInstrumentedActivityScenario.kt b/core/android/src/androidTest/kotlin/com/walletconnect/android/test/activity/WCInstrumentedActivityScenario.kt index e111c58c11..72fea4d224 100644 --- a/core/android/src/androidTest/kotlin/com/walletconnect/android/test/activity/WCInstrumentedActivityScenario.kt +++ b/core/android/src/androidTest/kotlin/com/walletconnect/android/test/activity/WCInstrumentedActivityScenario.kt @@ -82,7 +82,7 @@ class WCInstrumentedActivityScenario : TestRule { } } }.fold( - onSuccess = { Timber.d("Connection established with: ${TestClient.RELAY_URL}") }, + onSuccess = { Timber.d("Connection established with successfully") }, onFailure = { fail("Unable to establish connection within $timeoutDuration") } ) diff --git a/core/android/src/main/kotlin/com/walletconnect/android/relay/NetworkClientTimeout.kt b/core/android/src/main/kotlin/com/walletconnect/android/relay/NetworkClientTimeout.kt index c9046e36dc..229f8eba15 100644 --- a/core/android/src/main/kotlin/com/walletconnect/android/relay/NetworkClientTimeout.kt +++ b/core/android/src/main/kotlin/com/walletconnect/android/relay/NetworkClientTimeout.kt @@ -24,7 +24,7 @@ data class NetworkClientTimeout( private const val MAX_TIMEOUT_LIMIT_AS_MILLIS = 60_000L fun getDefaultTimeout() = NetworkClientTimeout( - timeout = MAX_TIMEOUT_LIMIT_AS_MILLIS, + timeout = MIN_TIMEOUT_LIMIT_AS_MILLIS, timeUnit = TimeUnit.MILLISECONDS ) } From 2defa2be1fbb08414a8350d715e5c587d0cb9f3d Mon Sep 17 00:00:00 2001 From: kubel Date: Mon, 8 Jul 2024 14:35:26 +0200 Subject: [PATCH 07/14] Fix Sign testing --- .../sign/test/scenario/HybridAppInstrumentedActivityScenario.kt | 2 +- .../test/scenario/SignClientInstrumentedActivityScenario.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/scenario/HybridAppInstrumentedActivityScenario.kt b/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/scenario/HybridAppInstrumentedActivityScenario.kt index 6a0b4d3206..6e2fc192ef 100644 --- a/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/scenario/HybridAppInstrumentedActivityScenario.kt +++ b/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/scenario/HybridAppInstrumentedActivityScenario.kt @@ -69,7 +69,7 @@ class HybridAppInstrumentedActivityScenario : TestRule, SignActivityScenario() { } } }.fold( - onSuccess = { Timber.d("Connection established and peers initialized with: ${TestClient.RELAY_URL}") }, + onSuccess = { Timber.d("Connection established and peers initialized successfully") }, onFailure = { TestCase.fail("Unable to establish connection OR initialize peers within $timeoutDuration") } ) diff --git a/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/scenario/SignClientInstrumentedActivityScenario.kt b/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/scenario/SignClientInstrumentedActivityScenario.kt index b5322c0f30..8f902ea4c4 100644 --- a/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/scenario/SignClientInstrumentedActivityScenario.kt +++ b/protocol/sign/src/androidTest/kotlin/com/walletconnect/sign/test/scenario/SignClientInstrumentedActivityScenario.kt @@ -63,7 +63,7 @@ class SignClientInstrumentedActivityScenario : TestRule, SignActivityScenario() } } }.fold( - onSuccess = { Timber.d("Connection established and peers initialized with: ${TestClient.RELAY_URL}") }, + onSuccess = { Timber.d("Connection established and peers initialized successfully") }, onFailure = { fail("Unable to establish connection OR initialize peers within $timeoutDuration") } ) From 2cb0308cb52e0e83b23a11903cef8d336a5fe726 Mon Sep 17 00:00:00 2001 From: kubel Date: Mon, 8 Jul 2024 14:50:13 +0200 Subject: [PATCH 08/14] Increase timeout to 10s --- .../com/walletconnect/android/relay/NetworkClientTimeout.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/android/src/main/kotlin/com/walletconnect/android/relay/NetworkClientTimeout.kt b/core/android/src/main/kotlin/com/walletconnect/android/relay/NetworkClientTimeout.kt index 229f8eba15..a500ff3552 100644 --- a/core/android/src/main/kotlin/com/walletconnect/android/relay/NetworkClientTimeout.kt +++ b/core/android/src/main/kotlin/com/walletconnect/android/relay/NetworkClientTimeout.kt @@ -20,7 +20,7 @@ data class NetworkClientTimeout( companion object { - private const val MIN_TIMEOUT_LIMIT_AS_MILLIS = 5_000L + private const val MIN_TIMEOUT_LIMIT_AS_MILLIS = 10_000L private const val MAX_TIMEOUT_LIMIT_AS_MILLIS = 60_000L fun getDefaultTimeout() = NetworkClientTimeout( From 51ce73d4acf30e1921af013c16f3911e88d09213 Mon Sep 17 00:00:00 2001 From: kubel Date: Wed, 10 Jul 2024 08:19:57 +0200 Subject: [PATCH 09/14] Allow users to connect, sign when error happens by not closing a dialog --- .../SessionAuthenticateRoute.kt | 13 ++++++------- .../session_proposal/SessionProposalRoute.kt | 13 ++++++------- .../session_request/SessionRequestRoute.kt | 11 +++++------ 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateRoute.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateRoute.kt index c77479f2c7..1cad6a1c77 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateRoute.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateRoute.kt @@ -156,10 +156,10 @@ private fun SessionAuthenticateDialog( }, onError = { error -> isCancelLoading = false - closeAndShowError(navController, error, composableScope, context) + showError(error, composableScope, context) }) } catch (e: Throwable) { - closeAndShowError(navController, e.message, composableScope, context) + showError(e.message, composableScope, context) } }, onConfirm = { isConfirmLoading = true @@ -183,10 +183,10 @@ private fun SessionAuthenticateDialog( }, onError = { error -> isConfirmLoading = false - closeAndShowError(navController, error, composableScope, context) + showError(error, composableScope, context) }) } catch (e: Exception) { - closeAndShowError(navController, e.message, composableScope, context) + showError(e.message, composableScope, context) } }, isLoadingConfirm = isConfirmLoading, @@ -196,10 +196,9 @@ private fun SessionAuthenticateDialog( } } -private fun closeAndShowError(navController: NavHostController, mesage: String?, coroutineScope: CoroutineScope, context: Context) { +private fun showError(message: String?, coroutineScope: CoroutineScope, context: Context) { coroutineScope.launch(Dispatchers.Main) { - navController.popBackStack(route = Route.Connections.path, inclusive = false) - Toast.makeText(context, mesage ?: "Session authenticate error, please check your Internet connection", Toast.LENGTH_SHORT).show() + Toast.makeText(context, message ?: "Session authenticate error, please check your Internet connection", Toast.LENGTH_SHORT).show() } } diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalRoute.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalRoute.kt index 6678484721..ff2447cf2c 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalRoute.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalRoute.kt @@ -179,10 +179,10 @@ private fun SessionProposalDialog( }, onError = { error -> isCancelLoading = false - closeAndShowError(navController, error, coroutineScope, context) + showError(error, coroutineScope, context) }) } catch (e: Throwable) { - closeAndShowError(navController, e.message, coroutineScope, context) + showError(e.message, coroutineScope, context) } }, onConfirm = { @@ -206,10 +206,10 @@ private fun SessionProposalDialog( }, onError = { error -> isConfirmLoading = false - closeAndShowError(navController, error, coroutineScope, context) + showError(error, coroutineScope, context) }) } catch (e: Throwable) { - closeAndShowError(navController, e.message, coroutineScope, context) + showError(e.message, coroutineScope, context) } }, isLoadingConfirm = isConfirmLoading, @@ -219,10 +219,9 @@ private fun SessionProposalDialog( } } -private fun closeAndShowError(navController: NavHostController, mesage: String?, coroutineScope: CoroutineScope, context: Context) { +private fun showError(message: String?, coroutineScope: CoroutineScope, context: Context) { coroutineScope.launch(Dispatchers.Main) { - navController.popBackStack(route = Route.Connections.path, inclusive = false) - Toast.makeText(context, mesage ?: "Session proposal error, please check your Internet connection", Toast.LENGTH_SHORT).show() + Toast.makeText(context, message ?: "Session proposal error, please check your Internet connection", Toast.LENGTH_SHORT).show() } } diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt index 334b751039..323623c1e1 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt @@ -100,11 +100,11 @@ fun SessionRequestRoute(navController: NavHostController, sessionRequestViewMode }, onError = { error -> isConfirmLoading = false - closeAndShowError(navController, error, composableScope, context) + showError(error, composableScope, context) }) } catch (e: Throwable) { - closeAndShowError(navController, e.message, composableScope, context) + showError(e.message, composableScope, context) } }, onCancel = { @@ -126,10 +126,10 @@ fun SessionRequestRoute(navController: NavHostController, sessionRequestViewMode }, onError = { error -> isCancelLoading = false - closeAndShowError(navController, error, composableScope, context) + showError(error, composableScope, context) }) } catch (e: Throwable) { - closeAndShowError(navController, e.message, composableScope, context) + showError(e.message, composableScope, context) } }, isLoadingConfirm = isConfirmLoading, @@ -163,9 +163,8 @@ fun SessionRequestRoute(navController: NavHostController, sessionRequestViewMode } } -private fun closeAndShowError(navController: NavHostController, message: String?, coroutineScope: CoroutineScope, context: Context) { +private fun showError(message: String?, coroutineScope: CoroutineScope, context: Context) { coroutineScope.launch(Dispatchers.Main) { - navController.popBackStack() Toast.makeText(context, message ?: "Session request error, please check your Internet connection", Toast.LENGTH_SHORT).show() } } From b58f7bce70e5389fef02c6bf279d74098cb1f5e6 Mon Sep 17 00:00:00 2001 From: kubel Date: Wed, 10 Jul 2024 09:09:55 +0200 Subject: [PATCH 10/14] Clear states --- .../SessionAuthenticateViewModel.kt | 4 +--- .../session_request/SessionRequestRoute.kt | 2 +- .../session_request/SessionRequestViewModel.kt | 11 +++++++---- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateViewModel.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateViewModel.kt index 6d790de331..bdcfe5925e 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateViewModel.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateViewModel.kt @@ -44,7 +44,6 @@ class SessionAuthenticateViewModel : ViewModel() { Web3Wallet.approveSessionAuthenticate(approveProposal, onError = { error -> Firebase.crashlytics.recordException(error.throwable) - WCDelegate.sessionAuthenticateEvent = null onError(error.throwable.message ?: "Undefined error, please check your Internet connection") }, onSuccess = { @@ -53,7 +52,7 @@ class SessionAuthenticateViewModel : ViewModel() { }) } catch (e: Exception) { Firebase.crashlytics.recordException(e) - WCDelegate.sessionProposalEvent = null + WCDelegate.sessionAuthenticateEvent = null onError(e.message ?: "Undefined error, please check your Internet connection") } } else { @@ -78,7 +77,6 @@ class SessionAuthenticateViewModel : ViewModel() { }, onError = { error -> Firebase.crashlytics.recordException(error.throwable) - WCDelegate.sessionAuthenticateEvent = null onError(error.throwable.message ?: "Undefined error, please check your Internet connection") }) } catch (e: Exception) { diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt index 323623c1e1..1189321eb9 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt @@ -64,7 +64,7 @@ fun SessionRequestRoutePreview() { @SuppressLint("RestrictedApi") @Composable fun SessionRequestRoute(navController: NavHostController, sessionRequestViewModel: SessionRequestViewModel = viewModel()) { - val sessionRequestUI = sessionRequestViewModel.sessionRequest + val sessionRequestUI = sessionRequestViewModel.sessionRequestUI val composableScope = rememberCoroutineScope() val context = LocalContext.current var isConfirmLoading by remember { mutableStateOf(false) } diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestViewModel.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestViewModel.kt index ac2b3f31e2..f7c9fa4199 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestViewModel.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestViewModel.kt @@ -20,17 +20,16 @@ import org.json.JSONArray import org.web3j.utils.Numeric.hexStringToByteArray class SessionRequestViewModel : ViewModel() { - var sessionRequest: SessionRequestUI = generateSessionRequestUI() + var sessionRequestUI: SessionRequestUI = generateSessionRequestUI() private fun clearSessionRequest() { WCDelegate.sessionRequestEvent = null WCDelegate.currentId = null - sessionRequest = SessionRequestUI.Initial } fun reject(onSuccess: (Uri?) -> Unit = {}, onError: (String) -> Unit = {}) { try { - val sessionRequest = sessionRequest as? SessionRequestUI.Content + val sessionRequest = sessionRequestUI as? SessionRequestUI.Content if (sessionRequest != null) { val result = Wallet.Params.SessionRequestResponse( sessionTopic = sessionRequest.topic, @@ -44,6 +43,7 @@ class SessionRequestViewModel : ViewModel() { Web3Wallet.respondSessionRequest(result, onSuccess = { clearSessionRequest() + sessionRequestUI = SessionRequestUI.Initial onSuccess(redirect) }, onError = { error -> @@ -57,6 +57,7 @@ class SessionRequestViewModel : ViewModel() { } catch (e: Exception) { Firebase.crashlytics.recordException(e) clearSessionRequest() + sessionRequestUI = SessionRequestUI.Initial onError(e.message ?: "Undefined error, please check your Internet connection") } } @@ -76,7 +77,7 @@ class SessionRequestViewModel : ViewModel() { fun approve(onSuccess: (Uri?) -> Unit = {}, onError: (String) -> Unit = {}) { try { - val sessionRequest = sessionRequest as? SessionRequestUI.Content + val sessionRequest = sessionRequestUI as? SessionRequestUI.Content if (sessionRequest != null) { val result: String = when { sessionRequest.method == PERSONAL_SIGN_METHOD -> CacaoSigner.sign( @@ -107,6 +108,7 @@ class SessionRequestViewModel : ViewModel() { Web3Wallet.respondSessionRequest(response, onSuccess = { clearSessionRequest() + sessionRequestUI = SessionRequestUI.Initial onSuccess(redirect) }, onError = { error -> @@ -120,6 +122,7 @@ class SessionRequestViewModel : ViewModel() { } catch (e: Exception) { Firebase.crashlytics.recordException(e) clearSessionRequest() + sessionRequestUI = SessionRequestUI.Initial onError(e.message ?: "Undefined error, please check your Internet connection") } } From 2672129dd9f682e43aac2478bb71eaaf20706c9b Mon Sep 17 00:00:00 2001 From: kubel Date: Thu, 11 Jul 2024 10:13:20 +0200 Subject: [PATCH 11/14] Do close dialog on connectivity exception --- .../sample/wallet/ui/Web3WalletNavGraph.kt | 9 ++++++ .../SessionAuthenticateRoute.kt | 17 ++++++---- .../SessionAuthenticateViewModel.kt | 32 ++++++++++++------- .../session_proposal/SessionProposalRoute.kt | 17 ++++++---- .../SessionProposalViewModel.kt | 16 +++++----- .../session_request/SessionRequestRoute.kt | 17 ++++++---- .../SessionRequestViewModel.kt | 31 ++++++++++-------- 7 files changed, 87 insertions(+), 52 deletions(-) diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/Web3WalletNavGraph.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/Web3WalletNavGraph.kt index 7b6979594f..60a0158f05 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/Web3WalletNavGraph.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/Web3WalletNavGraph.kt @@ -28,6 +28,7 @@ import com.google.accompanist.navigation.material.BottomSheetNavigator import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi import com.google.accompanist.navigation.material.ModalBottomSheetLayout import com.google.accompanist.navigation.material.bottomSheet +import com.walletconnect.sample.wallet.domain.WCDelegate import com.walletconnect.sample.wallet.ui.routes.Route import com.walletconnect.sample.wallet.ui.routes.bottomsheet_routes.scan_uri.ScanUriRoute import com.walletconnect.sample.wallet.ui.routes.bottomsheet_routes.update_subscription.UpdateSubscriptionRoute @@ -60,6 +61,14 @@ fun Web3WalletNavGraph( var scrimColor by remember { mutableStateOf(Color.Unspecified) } val inboxViewModel: InboxViewModel = viewModel() + navController.addOnDestinationChangedListener( + listener = { _, destination, _ -> + if (destination.route == Route.Connections.path) { + WCDelegate.sessionRequestEvent = null + WCDelegate.currentId = null + } + }) + ModalBottomSheetLayout( modifier = modifier, bottomSheetNavigator = bottomSheetNavigator, diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateRoute.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateRoute.kt index 1cad6a1c77..8c83454d6e 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateRoute.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateRoute.kt @@ -36,6 +36,7 @@ import androidx.compose.ui.unit.sp import androidx.core.net.toUri import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController +import com.walletconnect.android.internal.common.exception.NoConnectivityException import com.walletconnect.sample.common.sendResponseDeepLink import com.walletconnect.sample.common.ui.theme.mismatch_color import com.walletconnect.sample.common.ui.themedColor @@ -156,10 +157,10 @@ private fun SessionAuthenticateDialog( }, onError = { error -> isCancelLoading = false - showError(error, composableScope, context) + showError(navController, error, composableScope, context) }) } catch (e: Throwable) { - showError(e.message, composableScope, context) + showError(navController, e, composableScope, context) } }, onConfirm = { isConfirmLoading = true @@ -183,10 +184,10 @@ private fun SessionAuthenticateDialog( }, onError = { error -> isConfirmLoading = false - showError(error, composableScope, context) + showError(navController, error, composableScope, context) }) } catch (e: Exception) { - showError(e.message, composableScope, context) + showError(navController, e, composableScope, context) } }, isLoadingConfirm = isConfirmLoading, @@ -196,9 +197,13 @@ private fun SessionAuthenticateDialog( } } -private fun showError(message: String?, coroutineScope: CoroutineScope, context: Context) { +private fun showError(navController: NavHostController, throwable: Throwable?, coroutineScope: CoroutineScope, context: Context) { coroutineScope.launch(Dispatchers.Main) { - Toast.makeText(context, message ?: "Session authenticate error, please check your Internet connection", Toast.LENGTH_SHORT).show() + if (throwable !is NoConnectivityException) { + navController.popBackStack() + } + + Toast.makeText(context, throwable?.message ?: "Session authenticate error, please check your Internet connection", Toast.LENGTH_SHORT).show() } } diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateViewModel.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateViewModel.kt index bdcfe5925e..80de73426f 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateViewModel.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_authenticate/SessionAuthenticateViewModel.kt @@ -4,6 +4,7 @@ import androidx.lifecycle.ViewModel import com.google.firebase.crashlytics.ktx.crashlytics import com.google.firebase.ktx.Firebase import com.walletconnect.android.cacao.signature.SignatureType +import com.walletconnect.android.internal.common.exception.NoConnectivityException import com.walletconnect.android.utils.cacao.sign import com.walletconnect.sample.wallet.domain.ACCOUNTS_1_EIP155_ADDRESS import com.walletconnect.sample.wallet.domain.EthAccountDelegate @@ -18,7 +19,7 @@ import com.walletconnect.web3.wallet.utils.CacaoSigner class SessionAuthenticateViewModel : ViewModel() { val sessionAuthenticateUI: SessionAuthenticateUI? get() = generateAuthRequestUI() - fun approve(onSuccess: (String) -> Unit = {}, onError: (String) -> Unit = {}) { + fun approve(onSuccess: (String) -> Unit = {}, onError: (Throwable) -> Unit = {}) { if (WCDelegate.sessionAuthenticateEvent != null) { try { val sessionAuthenticate = WCDelegate.sessionAuthenticateEvent!!.first @@ -42,25 +43,29 @@ class SessionAuthenticateViewModel : ViewModel() { val approveProposal = Wallet.Params.ApproveSessionAuthenticate(id = sessionAuthenticate.id, auths = auths) Web3Wallet.approveSessionAuthenticate(approveProposal, - onError = { error -> - Firebase.crashlytics.recordException(error.throwable) - onError(error.throwable.message ?: "Undefined error, please check your Internet connection") - }, onSuccess = { WCDelegate.sessionAuthenticateEvent = null onSuccess(sessionAuthenticate.participant.metadata?.redirect ?: "") - }) + }, + onError = { error -> + if (error.throwable !is NoConnectivityException) { + WCDelegate.sessionAuthenticateEvent = null + } + Firebase.crashlytics.recordException(error.throwable) + onError(error.throwable) + } + ) } catch (e: Exception) { Firebase.crashlytics.recordException(e) WCDelegate.sessionAuthenticateEvent = null - onError(e.message ?: "Undefined error, please check your Internet connection") + onError(e) } } else { - onError("Authenticate request expired") + onError(Throwable("Authenticate request expired")) } } - fun reject(onSuccess: (String) -> Unit = {}, onError: (String) -> Unit = {}) { + fun reject(onSuccess: (String) -> Unit = {}, onError: (Throwable) -> Unit = {}) { if (WCDelegate.sessionAuthenticateEvent != null) { try { val sessionAuthenticate = WCDelegate.sessionAuthenticateEvent!!.first @@ -76,16 +81,19 @@ class SessionAuthenticateViewModel : ViewModel() { onSuccess(sessionAuthenticate.participant.metadata?.redirect ?: "") }, onError = { error -> + if (error.throwable !is NoConnectivityException) { + WCDelegate.sessionAuthenticateEvent = null + } Firebase.crashlytics.recordException(error.throwable) - onError(error.throwable.message ?: "Undefined error, please check your Internet connection") + onError(error.throwable) }) } catch (e: Exception) { Firebase.crashlytics.recordException(e) WCDelegate.sessionAuthenticateEvent = null - onError(e.message ?: "Undefined error, please check your Internet connection") + onError(e) } } else { - onError("Authenticate request expired") + onError(Throwable("Authenticate request expired")) } } diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalRoute.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalRoute.kt index ff2447cf2c..2b55eb980b 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalRoute.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalRoute.kt @@ -41,6 +41,7 @@ import androidx.core.net.toUri import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController +import com.walletconnect.android.internal.common.exception.NoConnectivityException import com.walletconnect.sample.common.Chains import com.walletconnect.sample.common.CompletePreviews import com.walletconnect.sample.common.sendResponseDeepLink @@ -179,10 +180,10 @@ private fun SessionProposalDialog( }, onError = { error -> isCancelLoading = false - showError(error, coroutineScope, context) + showError(navController, error, coroutineScope, context) }) } catch (e: Throwable) { - showError(e.message, coroutineScope, context) + showError(navController, e, coroutineScope, context) } }, onConfirm = { @@ -206,10 +207,10 @@ private fun SessionProposalDialog( }, onError = { error -> isConfirmLoading = false - showError(error, coroutineScope, context) + showError(navController, error, coroutineScope, context) }) } catch (e: Throwable) { - showError(e.message, coroutineScope, context) + showError(navController, e, coroutineScope, context) } }, isLoadingConfirm = isConfirmLoading, @@ -219,9 +220,13 @@ private fun SessionProposalDialog( } } -private fun showError(message: String?, coroutineScope: CoroutineScope, context: Context) { +private fun showError(navController: NavHostController, throwable: Throwable?, coroutineScope: CoroutineScope, context: Context) { coroutineScope.launch(Dispatchers.Main) { - Toast.makeText(context, message ?: "Session proposal error, please check your Internet connection", Toast.LENGTH_SHORT).show() + if (throwable !is NoConnectivityException) { + navController.popBackStack() + } + + Toast.makeText(context, throwable?.message ?: "Session proposal error, please check your Internet connection", Toast.LENGTH_SHORT).show() } } diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalViewModel.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalViewModel.kt index ee8c1971a2..63c3388df2 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalViewModel.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_proposal/SessionProposalViewModel.kt @@ -12,7 +12,7 @@ import timber.log.Timber class SessionProposalViewModel : ViewModel() { val sessionProposal: SessionProposalUI? = generateSessionProposalUI() - fun approve(proposalPublicKey: String, onSuccess: (String) -> Unit = {}, onError: (String) -> Unit = {}) { + fun approve(proposalPublicKey: String, onSuccess: (String) -> Unit = {}, onError: (Throwable) -> Unit = {}) { val proposal = Web3Wallet.getSessionProposals().find { it.proposerPublicKey == proposalPublicKey } if (proposal != null) { try { @@ -24,7 +24,7 @@ class SessionProposalViewModel : ViewModel() { onError = { error -> Firebase.crashlytics.recordException(error.throwable) WCDelegate.sessionProposalEvent = null - onError(error.throwable.message ?: "Undefined error, please check your Internet connection") + onError(error.throwable) }, onSuccess = { WCDelegate.sessionProposalEvent = null @@ -33,14 +33,14 @@ class SessionProposalViewModel : ViewModel() { } catch (e: Exception) { Firebase.crashlytics.recordException(e) WCDelegate.sessionProposalEvent = null - onError(e.message ?: "Undefined error, please check your Internet connection") + onError(e) } } else { - onError("Cannot approve session proposal, it has expired. Please try again.") + onError(Throwable("Cannot approve session proposal, it has expired. Please try again.")) } } - fun reject(proposalPublicKey: String, onSuccess: (String) -> Unit = {}, onError: (String) -> Unit = {}) { + fun reject(proposalPublicKey: String, onSuccess: (String) -> Unit = {}, onError: (Throwable) -> Unit = {}) { val proposal = Web3Wallet.getSessionProposals().find { it.proposerPublicKey == proposalPublicKey } if (proposal != null) { try { @@ -58,15 +58,15 @@ class SessionProposalViewModel : ViewModel() { onError = { error -> Firebase.crashlytics.recordException(error.throwable) WCDelegate.sessionProposalEvent = null - onError(error.throwable.message ?: "Undefined error, please check your Internet connection") + onError(error.throwable) }) } catch (e: Exception) { Firebase.crashlytics.recordException(e) WCDelegate.sessionProposalEvent = null - onError(e.message ?: "Undefined error, please check your Internet connection") + onError(e) } } else { - onError("Cannot reject session proposal, it has expired. Please try again.") + onError(Throwable("Cannot reject session proposal, it has expired. Please try again.")) } } diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt index 1189321eb9..5a2f55be9b 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestRoute.kt @@ -32,6 +32,7 @@ import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController +import com.walletconnect.android.internal.common.exception.NoConnectivityException import com.walletconnect.sample.common.CompletePreviews import com.walletconnect.sample.common.sendResponseDeepLink import com.walletconnect.sample.common.ui.theme.PreviewTheme @@ -73,6 +74,7 @@ fun SessionRequestRoute(navController: NavHostController, sessionRequestViewMode is SessionRequestUI.Content -> { val allowButtonColor = getColor(sessionRequestUI.peerContextUI) currentId = sessionRequestUI.requestId + SemiTransparentDialog { Spacer(modifier = Modifier.height(24.dp)) Peer(peerUI = sessionRequestUI.peerUI, "sends a request", sessionRequestUI.peerContextUI) @@ -100,11 +102,11 @@ fun SessionRequestRoute(navController: NavHostController, sessionRequestViewMode }, onError = { error -> isConfirmLoading = false - showError(error, composableScope, context) + showError(navController, error, composableScope, context) }) } catch (e: Throwable) { - showError(e.message, composableScope, context) + showError(navController, e, composableScope, context) } }, onCancel = { @@ -126,10 +128,10 @@ fun SessionRequestRoute(navController: NavHostController, sessionRequestViewMode }, onError = { error -> isCancelLoading = false - showError(error, composableScope, context) + showError(navController, error, composableScope, context) }) } catch (e: Throwable) { - showError(e.message, composableScope, context) + showError(navController, e, composableScope, context) } }, isLoadingConfirm = isConfirmLoading, @@ -163,9 +165,12 @@ fun SessionRequestRoute(navController: NavHostController, sessionRequestViewMode } } -private fun showError(message: String?, coroutineScope: CoroutineScope, context: Context) { +private fun showError(navController: NavHostController, throwable: Throwable?, coroutineScope: CoroutineScope, context: Context) { coroutineScope.launch(Dispatchers.Main) { - Toast.makeText(context, message ?: "Session request error, please check your Internet connection", Toast.LENGTH_SHORT).show() + if (throwable !is NoConnectivityException) { + navController.popBackStack() + } + Toast.makeText(context, throwable?.message ?: "Session request error, please check your Internet connection", Toast.LENGTH_SHORT).show() } } diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestViewModel.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestViewModel.kt index f7c9fa4199..2c2b31027c 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestViewModel.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/dialog_routes/session_request/SessionRequestViewModel.kt @@ -6,6 +6,7 @@ import androidx.lifecycle.ViewModel import com.google.firebase.crashlytics.ktx.crashlytics import com.google.firebase.ktx.Firebase import com.walletconnect.android.cacao.signature.SignatureType +import com.walletconnect.android.internal.common.exception.NoConnectivityException import com.walletconnect.android.utils.cacao.sign import com.walletconnect.sample.common.Chains import com.walletconnect.sample.wallet.domain.EthAccountDelegate @@ -25,9 +26,10 @@ class SessionRequestViewModel : ViewModel() { private fun clearSessionRequest() { WCDelegate.sessionRequestEvent = null WCDelegate.currentId = null + sessionRequestUI = SessionRequestUI.Initial } - fun reject(onSuccess: (Uri?) -> Unit = {}, onError: (String) -> Unit = {}) { + fun reject(onSuccess: (Uri?) -> Unit = {}, onError: (Throwable) -> Unit = {}) { try { val sessionRequest = sessionRequestUI as? SessionRequestUI.Content if (sessionRequest != null) { @@ -43,22 +45,22 @@ class SessionRequestViewModel : ViewModel() { Web3Wallet.respondSessionRequest(result, onSuccess = { clearSessionRequest() - sessionRequestUI = SessionRequestUI.Initial onSuccess(redirect) }, onError = { error -> Firebase.crashlytics.recordException(error.throwable) - clearSessionRequest() - onError(error.throwable.message ?: "Undefined error, please check your Internet connection") + if (error.throwable !is NoConnectivityException) { + clearSessionRequest() + } + onError(error.throwable) }) } else { - onError("Reject - Cannot find session request") + onError(Throwable("Reject - Cannot find session request")) } } catch (e: Exception) { Firebase.crashlytics.recordException(e) clearSessionRequest() - sessionRequestUI = SessionRequestUI.Initial - onError(e.message ?: "Undefined error, please check your Internet connection") + onError(e.cause ?: Throwable("Undefined error, please check your Internet connection")) } } @@ -75,7 +77,7 @@ class SessionRequestViewModel : ViewModel() { } } - fun approve(onSuccess: (Uri?) -> Unit = {}, onError: (String) -> Unit = {}) { + fun approve(onSuccess: (Uri?) -> Unit = {}, onError: (Throwable) -> Unit = {}) { try { val sessionRequest = sessionRequestUI as? SessionRequestUI.Content if (sessionRequest != null) { @@ -94,6 +96,7 @@ class SessionRequestViewModel : ViewModel() { //Note: Only for testing purposes - it will always fail on Dapp side sessionRequest.chain?.contains(Chains.Info.Solana.chain, true) == true -> """{"signature":"pBvp1bMiX6GiWmfYmkFmfcZdekJc19GbZQanqaGa\/kLPWjoYjaJWYttvm17WoDMyn4oROas4JLu5oKQVRIj911==","pub_key":{"value":"psclI0DNfWq6cOlGrKD9wNXPxbUsng6Fei77XjwdkPSt","type":"tendermint\/PubKeySecp256k1"}}""" + else -> throw Exception("Unsupported Chain") } val response = Wallet.Params.SessionRequestResponse( @@ -108,22 +111,22 @@ class SessionRequestViewModel : ViewModel() { Web3Wallet.respondSessionRequest(response, onSuccess = { clearSessionRequest() - sessionRequestUI = SessionRequestUI.Initial onSuccess(redirect) }, onError = { error -> Firebase.crashlytics.recordException(error.throwable) - clearSessionRequest() - onError(error.throwable.message ?: "Undefined error, please check your Internet connection") + if (error.throwable !is NoConnectivityException) { + clearSessionRequest() + } + onError(error.throwable) }) } else { - onError("Approve - Cannot find session request") + onError(Throwable("Approve - Cannot find session request")) } } catch (e: Exception) { Firebase.crashlytics.recordException(e) clearSessionRequest() - sessionRequestUI = SessionRequestUI.Initial - onError(e.message ?: "Undefined error, please check your Internet connection") + onError(e.cause ?: Throwable("Undefined error, please check your Internet connection")) } } From 50b6120cdd61a738dd6ea2861e75a681420e7f57 Mon Sep 17 00:00:00 2001 From: kubel Date: Thu, 11 Jul 2024 10:50:23 +0200 Subject: [PATCH 12/14] Navigate to connections screen only if current destination is not connection screen --- .../sample/wallet/ui/Web3WalletActivity.kt | 51 ++++++++++--------- .../wallet/ui/routes/host/WalletSampleHost.kt | 4 +- 2 files changed, 31 insertions(+), 24 deletions(-) diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/Web3WalletActivity.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/Web3WalletActivity.kt index fa37c4a60f..c4b6442292 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/Web3WalletActivity.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/Web3WalletActivity.kt @@ -43,7 +43,7 @@ class Web3WalletActivity : AppCompatActivity() { private val connectionsViewModel = ConnectionsViewModel() private val requestPermissionLauncher = registerForActivityResult( - ActivityResultContracts.RequestPermission() + ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { // FCM SDK (and your app) can post notifications. @@ -93,7 +93,10 @@ class Web3WalletActivity : AppCompatActivity() { when (event) { is CoreEvent.Disconnect -> { connectionsViewModel.refreshConnections() - navController.navigate(Route.Connections.path) + + if (navController.currentDestination?.route != Route.Connections.path) { + navController.navigate(Route.Connections.path) + } } else -> Unit @@ -115,13 +118,13 @@ class Web3WalletActivity : AppCompatActivity() { connectionsViewModel: ConnectionsViewModel, ) { web3walletViewModel.sessionRequestStateFlow - .onEach { - if (it.arrayOfArgs.isNotEmpty()) { - web3walletViewModel.showRequestLoader(false) - navController.navigate(Route.SessionRequest.path) - } + .onEach { + if (it.arrayOfArgs.isNotEmpty()) { + web3walletViewModel.showRequestLoader(false) + navController.navigate(Route.SessionRequest.path) } - .launchIn(lifecycleScope) + } + .launchIn(lifecycleScope) web3walletViewModel.walletEvents .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED) @@ -129,25 +132,27 @@ class Web3WalletActivity : AppCompatActivity() { when (event) { is SignEvent.SessionProposal -> navController.navigate(Route.SessionProposal.path) is SignEvent.ExpiredRequest -> { - navController.popBackStack( - route = Route.Connections.path, - inclusive = false - ) + if (navController.currentDestination?.route != Route.Connections.path) { + navController.popBackStack(route = Route.Connections.path, inclusive = false) + } Toast.makeText(baseContext, "Request expired", Toast.LENGTH_SHORT).show() } - is SignEvent.Disconnect -> { - connectionsViewModel.refreshConnections() + is SignEvent.Disconnect -> { + connectionsViewModel.refreshConnections() + + if (navController.currentDestination?.route != Route.Connections.path) { navController.navigate(Route.Connections.path) } + } - is AuthEvent.OnRequest -> navController.navigate(Route.AuthRequest.path) - is SignEvent.SessionAuthenticate -> navController.navigate(Route.SessionAuthenticate.path) + is AuthEvent.OnRequest -> navController.navigate(Route.AuthRequest.path) + is SignEvent.SessionAuthenticate -> navController.navigate(Route.SessionAuthenticate.path) - else -> Unit - } + else -> Unit } - .launchIn(lifecycleScope) + } + .launchIn(lifecycleScope) } override fun onNewIntent(intent: Intent?) { @@ -170,7 +175,7 @@ class Web3WalletActivity : AppCompatActivity() { } if (intent?.dataString?.startsWith("kotlin-web3wallet://request") == false - && intent.dataString?.contains("requestId") == false + && intent.dataString?.contains("requestId") == false ) { navController.handleDeepLink(intent) } @@ -180,9 +185,9 @@ class Web3WalletActivity : AppCompatActivity() { // This is only necessary for API level >= 33 (TIRAMISU) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission( - this, - android.Manifest.permission.POST_NOTIFICATIONS - ) == PackageManager.PERMISSION_GRANTED + this, + android.Manifest.permission.POST_NOTIFICATIONS + ) == PackageManager.PERMISSION_GRANTED ) { // FCM SDK (and your app) can post notifications. } else { diff --git a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/host/WalletSampleHost.kt b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/host/WalletSampleHost.kt index ec1f0691ec..dae42b2149 100644 --- a/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/host/WalletSampleHost.kt +++ b/sample/wallet/src/main/kotlin/com/walletconnect/sample/wallet/ui/routes/host/WalletSampleHost.kt @@ -79,7 +79,9 @@ fun WalletSampleHost( web3walletViewModel.eventsSharedFlow.collect { when (it) { is PairingEvent.Error -> { - navController.popBackStack(route = Route.Connections.path, inclusive = false) + if (navController.currentDestination?.route != Route.Connections.path) { + navController.popBackStack(route = Route.Connections.path, inclusive = false) + } Toast.makeText(navController.context, it.message, Toast.LENGTH_SHORT).show() } From af70dee3af86188798f598545c908564a90f6e28 Mon Sep 17 00:00:00 2001 From: kubel Date: Thu, 11 Jul 2024 11:34:13 +0200 Subject: [PATCH 13/14] Test fixing --- .../android/internal/SendEventUseCaseTest.kt | 31 ++++++++++++++----- .../ClientIdJwtRepositoryAndroidTest.kt | 2 +- .../foundation/di/FoundationNetworkModule.kt | 2 +- .../com/walletconnect/foundation/RelayTest.kt | 2 +- .../repository/ClientIdJwtRepositoryTest.kt | 2 +- 5 files changed, 28 insertions(+), 11 deletions(-) diff --git a/core/android/src/test/kotlin/com/walletconnect/android/internal/SendEventUseCaseTest.kt b/core/android/src/test/kotlin/com/walletconnect/android/internal/SendEventUseCaseTest.kt index 81406a1071..c664bd174b 100644 --- a/core/android/src/test/kotlin/com/walletconnect/android/internal/SendEventUseCaseTest.kt +++ b/core/android/src/test/kotlin/com/walletconnect/android/internal/SendEventUseCaseTest.kt @@ -41,17 +41,10 @@ class SendEventUseCaseTest : KoinTest { private lateinit var useCase: SendEventUseCase private val testDispatcher = StandardTestDispatcher() - private val testModule: Module = module { - single(named(AndroidCommonDITags.ENABLE_WEB_3_MODAL_ANALYTICS)) { true } - } - @OptIn(ExperimentalCoroutinesApi::class) @Before fun setUp() { Dispatchers.setMain(testDispatcher) - val app = startKoin { modules(testModule) } - useCase = SendEventUseCase(pulseService, logger, bundleId) - wcKoinApp = app } @OptIn(ExperimentalCoroutinesApi::class) @@ -64,6 +57,14 @@ class SendEventUseCaseTest : KoinTest { @OptIn(ExperimentalCoroutinesApi::class) @Test fun `send should log and send event when analytics is enabled and response is successful`() = runTest(testDispatcher) { + stopKoin() + val module: Module = module { + single(named(AndroidCommonDITags.ENABLE_WEB_3_MODAL_ANALYTICS)) { true } + } + val app = startKoin { modules(module) } + useCase = SendEventUseCase(pulseService, logger, bundleId) + wcKoinApp = app + val props = Props(type = "testEvent") val sdkType = SDKType.WEB3MODAL val event = Event(props = props, bundleId = bundleId) @@ -82,6 +83,14 @@ class SendEventUseCaseTest : KoinTest { @OptIn(ExperimentalCoroutinesApi::class) @Test fun `send should log error when analytics is enabled and response is unsuccessful`() = runTest(testDispatcher) { + stopKoin() + val module: Module = module { + single(named(AndroidCommonDITags.ENABLE_WEB_3_MODAL_ANALYTICS)) { true } + } + val app = startKoin { modules(module) } + useCase = SendEventUseCase(pulseService, logger, bundleId) + wcKoinApp = app + val props = Props(type = "testEvent") val sdkType = SDKType.WEB3MODAL val event = Event(props = props, bundleId = bundleId) @@ -100,6 +109,14 @@ class SendEventUseCaseTest : KoinTest { @OptIn(ExperimentalCoroutinesApi::class) @Test fun `send should log exception when analytics is enabled and an exception occurs`() = runTest(testDispatcher) { + stopKoin() + val module: Module = module { + single(named(AndroidCommonDITags.ENABLE_WEB_3_MODAL_ANALYTICS)) { true } + } + val app = startKoin { modules(module) } + useCase = SendEventUseCase(pulseService, logger, bundleId) + wcKoinApp = app + val props = Props(type = "testEvent") val sdkType = SDKType.WEB3MODAL val event = Event(props = props, bundleId = bundleId) diff --git a/core/android/src/test/kotlin/com/walletconnect/android/internal/common/ClientIdJwtRepositoryAndroidTest.kt b/core/android/src/test/kotlin/com/walletconnect/android/internal/common/ClientIdJwtRepositoryAndroidTest.kt index 0aa35f8b76..892772dfaf 100644 --- a/core/android/src/test/kotlin/com/walletconnect/android/internal/common/ClientIdJwtRepositoryAndroidTest.kt +++ b/core/android/src/test/kotlin/com/walletconnect/android/internal/common/ClientIdJwtRepositoryAndroidTest.kt @@ -22,7 +22,7 @@ internal class ClientIdJwtRepositoryAndroidTest { // Expected JWT for given nonce private val expectedJWT = - "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkaWQ6a2V5Ono2TWtvZEhad25lVlJTaHRhTGY4SktZa3hwREdwMXZHWm5wR21kQnBYOE0yZXh4SCIsInN1YiI6ImM0NzlmZTVkYzQ2NGU3NzFlNzhiMTkzZDIzOWE2NWI1OGQyNzhjYWQxYzM0YmZiMGI1NzE2ZTViYjUxNDkyOGUiLCJhdWQiOiJ3c3M6Ly9yZWxheS53YWxsZXRjb25uZWN0LmNvbSIsImlhdCI6MTY1NjkxMDA5NywiZXhwIjoxNjU2OTk2NDk3fQ.bAKl1swvwqqV_FgwvD4Bx3Yp987B9gTpZctyBviA-EkAuWc8iI8SyokOjkv9GJESgid4U8Tf2foCgrQp2qrxBA" + "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkaWQ6a2V5Ono2TWtvZEhad25lVlJTaHRhTGY4SktZa3hwREdwMXZHWm5wR21kQnBYOE0yZXh4SCIsInN1YiI6ImM0NzlmZTVkYzQ2NGU3NzFlNzhiMTkzZDIzOWE2NWI1OGQyNzhjYWQxYzM0YmZiMGI1NzE2ZTViYjUxNDkyOGUiLCJhdWQiOiJ3c3M6Ly9yZWxheS53YWxsZXRjb25uZWN0Lm9yZyIsImlhdCI6MTY1NjkxMDA5NywiZXhwIjoxNjU2OTk2NDk3fQ.lV9WBz1j3uQvDlv8NFnzymGczKQMWFsSqaZdXs4cUwFepP5LVC2eYIHdGsYkiJfwJxNia3LghX20GBW09SuwBA" @Before fun setUp() { diff --git a/foundation/src/main/kotlin/com/walletconnect/foundation/di/FoundationNetworkModule.kt b/foundation/src/main/kotlin/com/walletconnect/foundation/di/FoundationNetworkModule.kt index f1e51de476..bb5e8a9556 100644 --- a/foundation/src/main/kotlin/com/walletconnect/foundation/di/FoundationNetworkModule.kt +++ b/foundation/src/main/kotlin/com/walletconnect/foundation/di/FoundationNetworkModule.kt @@ -18,7 +18,7 @@ import java.util.concurrent.TimeUnit fun networkModule(serverUrl: String, sdkVersion: String, jwt: String): Module = module { val DEFAULT_BACKOFF_SECONDS = 5L - val TIMEOUT_TIME = 5000L + val TIMEOUT_TIME = 10000L // TODO: Setup env variable for tag instead of relayTest. Use env variable here instead of hard coded version single(named(FoundationDITags.INTERCEPTOR)) { diff --git a/foundation/src/test/kotlin/com/walletconnect/foundation/RelayTest.kt b/foundation/src/test/kotlin/com/walletconnect/foundation/RelayTest.kt index 1f3e367f45..b2d74b7041 100644 --- a/foundation/src/test/kotlin/com/walletconnect/foundation/RelayTest.kt +++ b/foundation/src/test/kotlin/com/walletconnect/foundation/RelayTest.kt @@ -42,7 +42,7 @@ sealed class TestState { @ExperimentalCoroutinesApi class RelayTest { private val testProjectId: String = requireNotNull(System.getProperty("TEST_PROJECT_ID")) - private val testRelayUrl: String = requireNotNull(System.getProperty("TEST_RELAY_URL")) + private val testRelayUrl: String = "https://staging.relay.walletconnect.org" private val serverUrl = "$testRelayUrl?projectId=$testProjectId" private val sdkVersion: String = System.getProperty("SDK_VERSION") + "-relayTest" private val testJob: CompletableJob = SupervisorJob() diff --git a/foundation/src/test/kotlin/com/walletconnect/foundation/crypto/data/repository/ClientIdJwtRepositoryTest.kt b/foundation/src/test/kotlin/com/walletconnect/foundation/crypto/data/repository/ClientIdJwtRepositoryTest.kt index 97913cf34a..8db23b58f5 100644 --- a/foundation/src/test/kotlin/com/walletconnect/foundation/crypto/data/repository/ClientIdJwtRepositoryTest.kt +++ b/foundation/src/test/kotlin/com/walletconnect/foundation/crypto/data/repository/ClientIdJwtRepositoryTest.kt @@ -23,7 +23,7 @@ internal class ClientIdJwtRepositoryTest { // Expected JWT for given nonce private val expectedJWT = - "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkaWQ6a2V5Ono2TWtvZEhad25lVlJTaHRhTGY4SktZa3hwREdwMXZHWm5wR21kQnBYOE0yZXh4SCIsInN1YiI6ImM0NzlmZTVkYzQ2NGU3NzFlNzhiMTkzZDIzOWE2NWI1OGQyNzhjYWQxYzM0YmZiMGI1NzE2ZTViYjUxNDkyOGUiLCJhdWQiOiJ3c3M6Ly9yZWxheS53YWxsZXRjb25uZWN0LmNvbSIsImlhdCI6MTY1NjkxMDA5NywiZXhwIjoxNjU2OTk2NDk3fQ.bAKl1swvwqqV_FgwvD4Bx3Yp987B9gTpZctyBviA-EkAuWc8iI8SyokOjkv9GJESgid4U8Tf2foCgrQp2qrxBA" + "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkaWQ6a2V5Ono2TWtvZEhad25lVlJTaHRhTGY4SktZa3hwREdwMXZHWm5wR21kQnBYOE0yZXh4SCIsInN1YiI6ImM0NzlmZTVkYzQ2NGU3NzFlNzhiMTkzZDIzOWE2NWI1OGQyNzhjYWQxYzM0YmZiMGI1NzE2ZTViYjUxNDkyOGUiLCJhdWQiOiJ3c3M6Ly9yZWxheS53YWxsZXRjb25uZWN0Lm9yZyIsImlhdCI6MTY1NjkxMDA5NywiZXhwIjoxNjU2OTk2NDk3fQ.lV9WBz1j3uQvDlv8NFnzymGczKQMWFsSqaZdXs4cUwFepP5LVC2eYIHdGsYkiJfwJxNia3LghX20GBW09SuwBA" @Before fun setUp() { From 998a80efa5f4f5665383d651a9f7bd1d8703146f Mon Sep 17 00:00:00 2001 From: kubel Date: Thu, 11 Jul 2024 12:04:58 +0200 Subject: [PATCH 14/14] Fix notify tests --- .../notify/test/scenario/ClientInstrumentedActivityScenario.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/protocol/notify/src/androidTest/kotlin/com/walletconnect/notify/test/scenario/ClientInstrumentedActivityScenario.kt b/protocol/notify/src/androidTest/kotlin/com/walletconnect/notify/test/scenario/ClientInstrumentedActivityScenario.kt index 05fc1e354b..3faccbf637 100644 --- a/protocol/notify/src/androidTest/kotlin/com/walletconnect/notify/test/scenario/ClientInstrumentedActivityScenario.kt +++ b/protocol/notify/src/androidTest/kotlin/com/walletconnect/notify/test/scenario/ClientInstrumentedActivityScenario.kt @@ -120,7 +120,7 @@ class ClientInstrumentedActivityScenario : TestRule, ActivityScenario() { } } }.fold( - onSuccess = { Timber.d("Connection established and peers initialized with: ${TestClient.RELAY_URL}") }, + onSuccess = { Timber.d("Connection established and peers initialized successfully") }, onFailure = { fail("Unable to establish connection OR initialize peers within $timeoutDuration") } )