From e1389ab83a926c403bd36a4ae6066f370adba6cc Mon Sep 17 00:00:00 2001 From: kubel Date: Tue, 2 Aug 2022 12:00:25 +0200 Subject: [PATCH 01/21] Add redirect to app metadata --- .../dapp/DappSampleApplication.kt | 8 ++- .../com/walletconnect/sign/client/Sign.kt | 20 ++++++- .../sign/client/mapper/ClientMapper.kt | 60 ++++++++++--------- .../model/vo/clientsync/common/MetaDataVO.kt | 2 + .../model/vo/clientsync/common/RedirectVO.kt | 10 ++++ .../sign/engine/model/EngineDO.kt | 27 +++++---- .../sign/engine/model/mapper/EngineMapper.kt | 17 +++--- .../sequence/SequenceStorageRepository.kt | 6 +- .../storage/data/dao/metadata/MetaDataDao.sq | 7 ++- .../storage/data/dao/session/SessionDao.sq | 4 +- .../wallet/WalletSampleApplication.kt | 6 +- 11 files changed, 109 insertions(+), 58 deletions(-) create mode 100644 signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/model/vo/clientsync/common/RedirectVO.kt diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt index a42fafd883..33513e5d6d 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt @@ -28,15 +28,19 @@ class DappSampleApplication : Application() { // ) // Sample of how to use a URI to initialize the WalletConnect SDK + + val redirect = Sign.Model.Redirect(native = "") //todo: add deep link for Dapp + val initString = Sign.Params.Init( application = this, - relayServerUrl = "wss://$WALLET_CONNECT_PROD_RELAY_URL?projectId=${BuildConfig.PROJECT_ID}", //TODO: register at https://walletconnect.com/register to get a project ID + relayServerUrl = "wss://$WALLET_CONNECT_PROD_RELAY_URL?projectId=${BuildConfig.PROJECT_ID}", metadata = Sign.Model.AppMetaData( name = "Kotlin Dapp", description = "Dapp description", url = "example.dapp", - icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media") + icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media"), + redirect = redirect ) ) diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt index c67467cd46..5e996e8623 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt @@ -54,12 +54,22 @@ object Sign { sealed class Namespace : Model() { - data class Proposal(val chains: List, val methods: List, val events: List, val extensions: List?) : Namespace() { + data class Proposal( + val chains: List, + val methods: List, + val events: List, + val extensions: List?, + ) : Namespace() { data class Extension(val chains: List, val methods: List, val events: List) } - data class Session(val accounts: List, val methods: List, val events: List, val extensions: List?) : Namespace() { + data class Session( + val accounts: List, + val methods: List, + val events: List, + val extensions: List?, + ) : Namespace() { data class Extension(val accounts: List, val methods: List, val events: List) } @@ -142,6 +152,12 @@ object Sign { val description: String, val url: String, val icons: List, + val redirect: Redirect?, + ) : Model() + + data class Redirect( + val native: String? = null, + val universal: String? = null, ) : Model() data class PendingRequest( diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt index 9dc5499f71..c7246bca6c 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt @@ -2,14 +2,11 @@ package com.walletconnect.sign.client.mapper import android.net.Uri import android.os.Build -import android.util.Log -import com.walletconnect.sign.BuildConfig import com.walletconnect.sign.client.Sign import com.walletconnect.sign.core.model.vo.jsonRpc.JsonRpcResponseVO import com.walletconnect.sign.core.model.vo.sync.PendingRequestVO import com.walletconnect.sign.engine.model.EngineDO import com.walletconnect.sign.network.data.connection.ConnectionType -import java.net.URI //TODO: Figure out what to do with models separation @JvmSynthetic @@ -118,17 +115,20 @@ internal fun EngineDO.SessionApproved.toClientSessionApproved(): Sign.Model.Appr Sign.Model.ApprovedSession(topic, peerAppMetaData?.toClientAppMetaData(), namespaces.toMapOfClientNamespacesSession(), accounts) @JvmSynthetic -internal fun Map.toMapOfClientNamespacesSession(): Map = this.mapValues { (_, namespace) -> - Sign.Model.Namespace.Session(namespace.accounts, namespace.methods, namespace.events, namespace.extensions?.map { extension -> - Sign.Model.Namespace.Session.Extension(extension.accounts, extension.methods, extension.events) - }) -} +internal fun Map.toMapOfClientNamespacesSession(): Map = + this.mapValues { (_, namespace) -> + Sign.Model.Namespace.Session(namespace.accounts, namespace.methods, namespace.events, namespace.extensions?.map { extension -> + Sign.Model.Namespace.Session.Extension(extension.accounts, extension.methods, extension.events) + }) + } @JvmSynthetic -internal fun Sign.Model.AppMetaData.toEngineAppMetaData() = EngineDO.AppMetaData(name, description, url, icons) +internal fun Sign.Model.AppMetaData.toEngineAppMetaData() = + EngineDO.AppMetaData(name, description, url, icons, EngineDO.Redirect(redirect?.native, redirect?.universal)) @JvmSynthetic -internal fun EngineDO.AppMetaData.toClientAppMetaData() = Sign.Model.AppMetaData(name, description, url, icons) +internal fun EngineDO.AppMetaData.toClientAppMetaData() = + Sign.Model.AppMetaData(name, description, url, icons, Sign.Model.Redirect(redirect?.native, redirect?.universal)) @JvmSynthetic internal fun Sign.Params.Request.toEngineDORequest(): EngineDO.Request = @@ -166,30 +166,34 @@ internal fun EngineDO.SessionPayloadResponse.toClientSessionPayloadResponse(): S Sign.Model.SessionRequestResponse(topic, chainId, method, result.toClientJsonRpcResponse()) @JvmSynthetic -internal fun Map.toMapOfEngineNamespacesProposal(): Map = mapValues { (_, namespace) -> - EngineDO.Namespace.Proposal(namespace.chains, namespace.methods, namespace.events, namespace.extensions?.map { extension -> - EngineDO.Namespace.Proposal.Extension(extension.chains, extension.methods, extension.events) - }) -} +internal fun Map.toMapOfEngineNamespacesProposal(): Map = + mapValues { (_, namespace) -> + EngineDO.Namespace.Proposal(namespace.chains, namespace.methods, namespace.events, namespace.extensions?.map { extension -> + EngineDO.Namespace.Proposal.Extension(extension.chains, extension.methods, extension.events) + }) + } @JvmSynthetic -internal fun Map.toMapOfClientNamespacesProposal(): Map = mapValues { (_, namespace) -> - Sign.Model.Namespace.Proposal(namespace.chains, namespace.methods, namespace.events, namespace.extensions?.map { extension -> - Sign.Model.Namespace.Proposal.Extension(extension.chains, extension.methods, extension.events) - }) -} +internal fun Map.toMapOfClientNamespacesProposal(): Map = + mapValues { (_, namespace) -> + Sign.Model.Namespace.Proposal(namespace.chains, namespace.methods, namespace.events, namespace.extensions?.map { extension -> + Sign.Model.Namespace.Proposal.Extension(extension.chains, extension.methods, extension.events) + }) + } @JvmSynthetic -internal fun Map.toMapOfEngineNamespacesSession(): Map = mapValues { (_, namespace) -> - EngineDO.Namespace.Session(namespace.accounts, namespace.methods, namespace.events, namespace.extensions?.map { extension -> - EngineDO.Namespace.Session.Extension(extension.accounts, extension.methods, extension.events) - }) -} +internal fun Map.toMapOfEngineNamespacesSession(): Map = + mapValues { (_, namespace) -> + EngineDO.Namespace.Session(namespace.accounts, namespace.methods, namespace.events, namespace.extensions?.map { extension -> + EngineDO.Namespace.Session.Extension(extension.accounts, extension.methods, extension.events) + }) + } @JvmSynthetic -internal fun List.toListEngineOfRelayProtocolOptions(): List = map { relayProtocolOptions -> - EngineDO.RelayProtocolOptions(relayProtocolOptions.protocol, relayProtocolOptions.data) -} +internal fun List.toListEngineOfRelayProtocolOptions(): List = + map { relayProtocolOptions -> + EngineDO.RelayProtocolOptions(relayProtocolOptions.protocol, relayProtocolOptions.data) + } @JvmSynthetic internal fun Sign.ConnectionType.toRelayConnectionType(): ConnectionType { diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/model/vo/clientsync/common/MetaDataVO.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/model/vo/clientsync/common/MetaDataVO.kt index 4ef78bb125..c737678d44 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/model/vo/clientsync/common/MetaDataVO.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/model/vo/clientsync/common/MetaDataVO.kt @@ -13,4 +13,6 @@ internal data class MetaDataVO( val url: String, @Json(name = "icons") val icons: List, + @Json(name = "redirect") + val redirect: RedirectVO? = null, ) \ No newline at end of file diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/model/vo/clientsync/common/RedirectVO.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/model/vo/clientsync/common/RedirectVO.kt new file mode 100644 index 0000000000..cab76a5513 --- /dev/null +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/model/vo/clientsync/common/RedirectVO.kt @@ -0,0 +1,10 @@ +package com.walletconnect.sign.core.model.vo.clientsync.common + +import com.squareup.moshi.Json + +internal data class RedirectVO( + @Json(name = "native") + val native: String? = null, + @Json(name = "universal") + val universal: String? = null +) \ No newline at end of file diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/EngineDO.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/EngineDO.kt index a7b230186f..07faa3298d 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/EngineDO.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/EngineDO.kt @@ -14,7 +14,7 @@ import java.net.URI internal sealed class EngineDO { - internal class InternalError(val exception: WalletConnectException.InternalError): EngineDO(), EngineEvent + internal class InternalError(val exception: WalletConnectException.InternalError) : EngineDO(), EngineEvent internal sealed class ProposedSequence { class Pairing(val uri: String) : ProposedSequence() @@ -25,7 +25,7 @@ internal sealed class EngineDO { val topic: TopicVO, val symKey: SymmetricKey, val relay: RelayProtocolOptionsVO, - val version: String = "2" + val version: String = "2", ) : EngineDO() internal data class SessionProposal( @@ -39,14 +39,14 @@ internal sealed class EngineDO { val relayData: String?, ) : EngineDO(), EngineEvent - internal sealed class Namespace: EngineDO() { + internal sealed class Namespace : EngineDO() { data class Proposal( val chains: List, val methods: List, val events: List, - val extensions: List? - ): Namespace() { + val extensions: List?, + ) : Namespace() { data class Extension(val chains: List, val methods: List, val events: List) } @@ -55,8 +55,8 @@ internal sealed class EngineDO { val accounts: List, val methods: List, val events: List, - val extensions: List? - ): Namespace() { + val extensions: List?, + ) : Namespace() { data class Extension(val accounts: List, val methods: List, val events: List) } @@ -102,7 +102,7 @@ internal sealed class EngineDO { val chainId: String?, ) : EngineDO(), EngineEvent - internal sealed class SettledSessionResponse : EngineDO(), EngineEvent { + internal sealed class SettledSessionResponse : EngineDO(), EngineEvent { data class Result(val settledSession: Session) : SettledSessionResponse() data class Error(val errorMessage: String) : SettledSessionResponse() } @@ -132,7 +132,8 @@ internal sealed class EngineDO { internal data class PairingSettle(val topic: TopicVO, val metaData: AppMetaData?) : EngineDO(), EngineEvent internal data class SessionUpdateAccounts(val topic: TopicVO, val accounts: List) : EngineDO(), EngineEvent - internal data class SessionUpdateNamespaces(val topic: TopicVO, val namespaces: Map) : EngineDO(), EngineEvent + internal data class SessionUpdateNamespaces(val topic: TopicVO, val namespaces: Map) : EngineDO(), + EngineEvent internal data class SessionExtend( override val topic: TopicVO, @@ -159,10 +160,16 @@ internal sealed class EngineDO { val description: String, val url: String, val icons: List, + val redirect: Redirect?, + ) : EngineDO() + + internal data class Redirect( + val native: String? = null, + val universal: String? = null, ) : EngineDO() internal data class ConnectionState( - val isAvailable: Boolean + val isAvailable: Boolean, ) : EngineDO(), EngineEvent internal sealed class JsonRpcResponse : EngineDO() { diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/mapper/EngineMapper.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/mapper/EngineMapper.kt index 9b8bb63928..a3a74e7f5e 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/mapper/EngineMapper.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/mapper/EngineMapper.kt @@ -4,10 +4,7 @@ import com.walletconnect.sign.core.exceptions.peer.PeerError import com.walletconnect.sign.core.model.vo.ExpiryVO import com.walletconnect.sign.core.model.vo.PublicKey import com.walletconnect.sign.core.model.vo.TopicVO -import com.walletconnect.sign.core.model.vo.clientsync.common.MetaDataVO -import com.walletconnect.sign.core.model.vo.clientsync.common.NamespaceVO -import com.walletconnect.sign.core.model.vo.clientsync.common.RelayProtocolOptionsVO -import com.walletconnect.sign.core.model.vo.clientsync.common.SessionParticipantVO +import com.walletconnect.sign.core.model.vo.clientsync.common.* import com.walletconnect.sign.core.model.vo.clientsync.pairing.params.PairingParamsVO import com.walletconnect.sign.core.model.vo.clientsync.pairing.payload.SessionProposerVO import com.walletconnect.sign.core.model.vo.clientsync.session.params.SessionParamsVO @@ -34,11 +31,11 @@ private fun EngineDO.WalletConnectUri.getQuery(): String { @JvmSynthetic internal fun EngineDO.AppMetaData.toMetaDataVO() = - MetaDataVO(name, description, url, icons) + MetaDataVO(name, description, url, icons, RedirectVO(redirect?.native, redirect?.universal)) @JvmSynthetic internal fun MetaDataVO.toEngineDOMetaData(): EngineDO.AppMetaData = - EngineDO.AppMetaData(name, description, url, icons) + EngineDO.AppMetaData(name, description, url, icons, EngineDO.Redirect(redirect?.native, redirect?.universal)) @JvmSynthetic internal fun PairingParamsVO.SessionProposeParams.toEngineDOSessionProposal(): EngineDO.SessionProposal = @@ -65,7 +62,7 @@ internal fun SessionParamsVO.SessionRequestParams.toEngineDOSessionRequest( request = EngineDO.SessionRequest.JSONRPCRequest( id = request.id, method = this.request.method, - params = this.request.params.toString() + params = this.request.params ) ) @@ -87,7 +84,9 @@ internal fun SessionVO.toEngineDOApprovedSessionVO(): EngineDO.Session = peerMetaData?.name ?: String.Empty, peerMetaData?.description ?: String.Empty, peerMetaData?.url ?: String.Empty, - peerMetaData?.icons?.map { iconUri -> iconUri } ?: listOf()) + peerMetaData?.icons?.map { iconUri -> iconUri } ?: listOf(), + EngineDO.Redirect(peerMetaData?.redirect?.native, peerMetaData?.redirect?.universal) + ) ) @JvmSynthetic @@ -96,7 +95,7 @@ internal fun SessionVO.toEngineDOSessionExtend(expiryVO: ExpiryVO): EngineDO.Ses @JvmSynthetic private fun MetaDataVO.toEngineDOAppMetaData(): EngineDO.AppMetaData = - EngineDO.AppMetaData(name, description, url, icons) + EngineDO.AppMetaData(name, description, url, icons, EngineDO.Redirect(redirect?.native, redirect?.universal)) @JvmSynthetic internal fun PairingVO.toEngineDOSettledPairing(): EngineDO.PairingSettle = diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/storage/sequence/SequenceStorageRepository.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/storage/sequence/SequenceStorageRepository.kt index a117ae88d9..552e369e87 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/storage/sequence/SequenceStorageRepository.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/storage/sequence/SequenceStorageRepository.kt @@ -9,6 +9,7 @@ import com.walletconnect.sign.core.model.vo.PublicKey import com.walletconnect.sign.core.model.vo.TopicVO import com.walletconnect.sign.core.model.vo.clientsync.common.MetaDataVO import com.walletconnect.sign.core.model.vo.clientsync.common.NamespaceVO +import com.walletconnect.sign.core.model.vo.clientsync.common.RedirectVO import com.walletconnect.sign.core.model.vo.sequence.PairingVO import com.walletconnect.sign.core.model.vo.sequence.SessionVO import com.walletconnect.sign.storage.data.dao.metadata.MetaDataDaoQueries @@ -122,6 +123,7 @@ internal class SequenceStorageRepository( metaData.description, metaData.url, metaData.icons, + metaData.redirect?.native, MetaDataType.PEER, topic.value ) @@ -296,6 +298,7 @@ internal class SequenceStorageRepository( metaData.description, metaData.url, metaData.icons, + metaData.redirect?.native, metaDataType ) } @@ -392,6 +395,7 @@ internal class SequenceStorageRepository( peerDesc: String?, peerUrl: String?, peerIcons: List?, + peerNative: String?, is_acknowledged: Boolean, ): SessionVO { val selfMetaData = if (selfName != null && selfDesc != null && selfUrl != null && selfIcons != null) { @@ -401,7 +405,7 @@ internal class SequenceStorageRepository( } val peerMetaData = if (peerName != null && peerDesc != null && peerUrl != null && peerIcons != null) { - MetaDataVO(peerName, peerDesc, peerUrl, peerIcons) + MetaDataVO(peerName, peerDesc, peerUrl, peerIcons, RedirectVO(native = peerNative)) } else { null } diff --git a/signSDK/sign/src/main/sqldelight/com/walletconnect/sign/storage/data/dao/metadata/MetaDataDao.sq b/signSDK/sign/src/main/sqldelight/com/walletconnect/sign/storage/data/dao/metadata/MetaDataDao.sq index 939a8c517c..abb67786ce 100644 --- a/signSDK/sign/src/main/sqldelight/com/walletconnect/sign/storage/data/dao/metadata/MetaDataDao.sq +++ b/signSDK/sign/src/main/sqldelight/com/walletconnect/sign/storage/data/dao/metadata/MetaDataDao.sq @@ -8,17 +8,18 @@ CREATE TABLE MetaDataDao( description TEXT NOT NULL, url TEXT NOT NULL, icons TEXT AS List NOT NULL, + native TEXT, type TEXT AS MetaDataType NOT NULL, UNIQUE(sequence_topic, type) ); insertOrAbortMetaData: -INSERT OR ABORT INTO MetaDataDao(sequence_topic, name, description, url, icons, type) -VALUES (?, ?, ?, ?, ?, ?); +INSERT OR ABORT INTO MetaDataDao(sequence_topic, name, description, url, icons, native, type) +VALUES (?, ?, ?, ?, ?, ?,?); updateOrAbortMetaData: UPDATE MetaDataDao -SET name = ?, description = ?, url = ?, icons = ?, type = ? +SET name = ?, description = ?, url = ?, icons = ?, native = ?, type = ? WHERE sequence_topic = ?; getByTopic: diff --git a/signSDK/sign/src/main/sqldelight/com/walletconnect/sign/storage/data/dao/session/SessionDao.sq b/signSDK/sign/src/main/sqldelight/com/walletconnect/sign/storage/data/dao/session/SessionDao.sq index c5f3f68494..b2416fb19a 100644 --- a/signSDK/sign/src/main/sqldelight/com/walletconnect/sign/storage/data/dao/session/SessionDao.sq +++ b/signSDK/sign/src/main/sqldelight/com/walletconnect/sign/storage/data/dao/session/SessionDao.sq @@ -22,13 +22,13 @@ FROM SessionDao WHERE id = (SELECT MAX(id) FROM SessionDao); getListOfSessionDaos: -SELECT sd.id, sd.topic, sd.expiry, sd.relay_protocol, sd.relay_data, sd.controller_key, sd.self_participant, self_mdd.name, self_mdd.description, self_mdd.url, self_mdd.icons, sd.peer_participant, peer_mdd.name, peer_mdd.description, peer_mdd.url, peer_mdd.icons, sd.is_acknowledged +SELECT sd.id, sd.topic, sd.expiry, sd.relay_protocol, sd.relay_data, sd.controller_key, sd.self_participant, self_mdd.name, self_mdd.description, self_mdd.url, self_mdd.icons, sd.peer_participant, peer_mdd.name, peer_mdd.description, peer_mdd.url, peer_mdd.icons, peer_mdd.native, sd.is_acknowledged FROM SessionDao sd LEFT JOIN MetaDataDao self_mdd ON sd.topic = self_mdd.sequence_topic AND self_mdd.type = "SELF" LEFT JOIN MetaDataDao peer_mdd ON sd.topic = peer_mdd.sequence_topic AND peer_mdd.type = "PEER"; getSessionByTopic: -SELECT sd.id, sd.topic, sd.expiry, sd.relay_protocol, sd.relay_data, sd.controller_key, sd.self_participant, self_mdd.name, self_mdd.description, self_mdd.url, self_mdd.icons, sd.peer_participant, peer_mdd.name, peer_mdd.description, peer_mdd.url, peer_mdd.icons, sd.is_acknowledged +SELECT sd.id, sd.topic, sd.expiry, sd.relay_protocol, sd.relay_data, sd.controller_key, sd.self_participant, self_mdd.name, self_mdd.description, self_mdd.url, self_mdd.icons, sd.peer_participant, peer_mdd.name, peer_mdd.description, peer_mdd.url, peer_mdd.icons, peer_mdd.native, sd.is_acknowledged FROM SessionDao sd LEFT JOIN MetaDataDao self_mdd ON sd.topic = self_mdd.sequence_topic AND self_mdd.type = "SELF" LEFT JOIN MetaDataDao peer_mdd ON sd.topic = peer_mdd.sequence_topic AND peer_mdd.type = "PEER" diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt index 8278b407eb..fc6a5274e7 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt @@ -29,6 +29,9 @@ class WalletSampleApplication : Application() { // ) // Sample of how to use a URI to initialize the WalletConnect Sign SDK + + val redirect = Sign.Model.Redirect(native = "wc:/{topic}/request") + val initString = Sign.Params.Init( application = this, relayServerUrl = "wss://$WALLET_CONNECT_PROD_RELAY_URL?projectId=${BuildConfig.PROJECT_ID}", @@ -37,7 +40,8 @@ class WalletSampleApplication : Application() { name = "Kotlin Wallet", description = "Wallet description", url = "example.wallet", - icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media") + icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media"), + redirect = redirect ) ) From 9de15792f90301b65f5ddae945f5b4dd8e7b961b Mon Sep 17 00:00:00 2001 From: kubel Date: Thu, 4 Aug 2022 11:14:37 +0200 Subject: [PATCH 02/21] Add reject and approve session request redirection to Dapp --- signSDK/dapp/src/main/AndroidManifest.xml | 4 ++ .../dapp/DappSampleApplication.kt | 2 +- .../dapp/ui/host/DappSampleActivity.kt | 11 ++++- .../SelectedAccountFragment.kt | 3 ++ .../SelectedAccountViewModel.kt | 8 +++- .../dapp/ui/session/SessionFragment.kt | 3 +- .../src/main/res/navigation/nav_graph.xml | 5 +++ .../wallet/WalletSampleApplication.kt | 2 +- .../wallet/ui/host/WalletSampleActivity.kt | 4 ++ .../host/request/SessionRequestBottomSheet.kt | 18 ++++++++- .../host/request/SessionRequestViewModel.kt | 40 +++++++++++++------ .../src/main/res/navigation/nav_graph.xml | 3 +- 12 files changed, 83 insertions(+), 20 deletions(-) diff --git a/signSDK/dapp/src/main/AndroidManifest.xml b/signSDK/dapp/src/main/AndroidManifest.xml index 07f9d24894..8a57172936 100644 --- a/signSDK/dapp/src/main/AndroidManifest.xml +++ b/signSDK/dapp/src/main/AndroidManifest.xml @@ -14,7 +14,11 @@ + + + diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt index 33513e5d6d..095e3b0833 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt @@ -29,7 +29,7 @@ class DappSampleApplication : Application() { // Sample of how to use a URI to initialize the WalletConnect SDK - val redirect = Sign.Model.Redirect(native = "") //todo: add deep link for Dapp + val redirect = Sign.Model.Redirect(native = "kotlin-dapp-wc:/request") //todo: add deep link for Dapp val initString = Sign.Params.Init( application = this, diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/host/DappSampleActivity.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/host/DappSampleActivity.kt index e0f04b6b04..58376f87b9 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/host/DappSampleActivity.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/host/DappSampleActivity.kt @@ -1,5 +1,6 @@ package com.walletconnect.dapp.ui.host +import android.content.Intent import android.os.Bundle import android.util.Log import androidx.activity.viewModels @@ -45,9 +46,17 @@ class DappSampleActivity : AppCompatActivity(R.layout.activity_dapp) { return navHostFragment.navController.navigateUp() || super.onSupportNavigateUp() } + override fun onNewIntent(intent: Intent?) { + super.onNewIntent(intent) + + Log.e("kobe", "DeepLink intent: ${intent.toString()}") + +// navHostFragment.navController.handleDeepLink(intent) + } + override fun onDestroy() { super.onDestroy() - viewModel.disconnect() +// viewModel.disconnect() } } diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountFragment.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountFragment.kt index a73fa31beb..e63ece36ac 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountFragment.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountFragment.kt @@ -5,6 +5,7 @@ import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle +import android.util.Log import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels @@ -88,6 +89,8 @@ class SelectedAccountFragment : Fragment(R.layout.fragment_selected_account) { try { requireActivity().startActivity(Intent(Intent.ACTION_VIEW, sessionRequestDeeplinkUri)) } catch (exception: ActivityNotFoundException) { + + Log.e("kobe", "Dapp No Activity: $exception") // There is no app to handle deep link } } diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt index 8218057253..affa33c504 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt @@ -1,6 +1,7 @@ package com.walletconnect.dapp.ui.selected_account import android.net.Uri +import android.util.Log import androidx.core.net.toUri import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -75,7 +76,12 @@ class SelectedAccountViewModel : ViewModel() { } } - val sessionRequestDeepLinkUri = "wc:/${requestParams.sessionTopic})}/request".toUri() + val sessionRequestDeepLinkUri = SignClient.getListOfSettledSessions() + .find { session -> session.topic == requestParams.sessionTopic }?.metaData?.redirect?.native?.toUri() + ?: "wc:/${requestParams.sessionTopic})}/request".toUri() + + Log.e("kobe", "$sessionRequestDeepLinkUri") + sendSessionRequestDeepLink(sessionRequestDeepLinkUri) } } diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionFragment.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionFragment.kt index c06ac3dbce..76cfb08165 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionFragment.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionFragment.kt @@ -24,9 +24,10 @@ class SessionFragment : Fragment(R.layout.fragment_session) { private val binding by viewBinding(FragmentSessionBinding::bind) private val viewModel: SessionViewModel by viewModels() private val sessionAccountAdapter by lazy { - SessionAdapter() { selectedAccount -> + SessionAdapter { selectedAccount -> val selectedAccountKey = getString(R.string.selected_account) findNavController().navigate(R.id.action_fragment_session_to_fragment_selected_account, bundleOf(selectedAccountKey to selectedAccount)) +// findNavController().navigate(R.id.action_global_to_selected_account, bundleOf(selectedAccountKey to selectedAccount)) } } diff --git a/signSDK/dapp/src/main/res/navigation/nav_graph.xml b/signSDK/dapp/src/main/res/navigation/nav_graph.xml index f9c9e5b9ca..822c085cdb 100644 --- a/signSDK/dapp/src/main/res/navigation/nav_graph.xml +++ b/signSDK/dapp/src/main/res/navigation/nav_graph.xml @@ -50,6 +50,11 @@ android:id="@+id/action_global_fragment_chain_selection" app:destination="@id/fragment_chain_selection" /> + + + Unit) { (uiState.value as? SessionRequestUI.Content)?.let { sessionRequest -> val result = Sign.Params.Response( sessionTopic = sessionRequest.topic, @@ -44,15 +46,17 @@ class SessionRequestViewModel : ViewModel() { SignClient.respond(result) { error -> Log.e(tag(this), error.throwable.stackTraceToString()) } - } - viewModelScope.launch { - _event.emit(SampleWalletEvents.SessionRequestResponded) - WalletDelegate.clearCache() + viewModelScope.launch { + _event.emit(SampleWalletEvents.SessionRequestResponded) + WalletDelegate.clearCache() + } + + sendResponseDeepLink(sessionRequest, sendSessionRequestResponseDeepLink) } } - fun approve() { + fun approve(sendSessionRequestResponseDeepLink: (Uri) -> Unit) { (uiState.value as? SessionRequestUI.Content)?.let { sessionRequest -> val result = Sign.Params.Response( sessionTopic = sessionRequest.topic, @@ -65,11 +69,23 @@ class SessionRequestViewModel : ViewModel() { SignClient.respond(result) { error -> Log.e(tag(this), error.throwable.stackTraceToString()) } - } - viewModelScope.launch { - _event.emit(SampleWalletEvents.SessionRequestResponded) - WalletDelegate.clearCache() + viewModelScope.launch { + _event.emit(SampleWalletEvents.SessionRequestResponded) + WalletDelegate.clearCache() + } + + sendResponseDeepLink(sessionRequest, sendSessionRequestResponseDeepLink) } } + + private fun sendResponseDeepLink( + sessionRequest: SessionRequestUI.Content, + sendSessionRequestResponseDeepLink: (Uri) -> Unit, + ) { + val session = SignClient.getListOfSettledSessions().find { session -> session.topic == sessionRequest.topic } + val deepLinUri = session?.metaData?.redirect?.native?.toUri() ?: "wc:/${sessionRequest.topic})}/request".toUri() + + sendSessionRequestResponseDeepLink(deepLinUri) + } } \ No newline at end of file diff --git a/signSDK/wallet/src/main/res/navigation/nav_graph.xml b/signSDK/wallet/src/main/res/navigation/nav_graph.xml index 540f83fc51..752b90f3e5 100644 --- a/signSDK/wallet/src/main/res/navigation/nav_graph.xml +++ b/signSDK/wallet/src/main/res/navigation/nav_graph.xml @@ -70,6 +70,7 @@ android:name="com.walletconnect.wallet.ui.sessions.active.ActiveSessionsFragment" android:label="Sessions" tools:layout="@layout/fragment_active_sessions"> + @@ -81,7 +82,7 @@ + app:uri="kotlin-wallet-wc:/request" /> From 890a13c0e312412bb5d85420f5aeb04b836a0054 Mon Sep 17 00:00:00 2001 From: kubel Date: Thu, 4 Aug 2022 11:27:35 +0200 Subject: [PATCH 03/21] Remove onIntent --- .../dapp/ui/host/DappSampleActivity.kt | 14 ++------------ .../wallet/ui/host/WalletSampleActivity.kt | 4 ---- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/host/DappSampleActivity.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/host/DappSampleActivity.kt index 58376f87b9..08a69a98ef 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/host/DappSampleActivity.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/host/DappSampleActivity.kt @@ -1,6 +1,5 @@ package com.walletconnect.dapp.ui.host -import android.content.Intent import android.os.Bundle import android.util.Log import androidx.activity.viewModels @@ -46,17 +45,8 @@ class DappSampleActivity : AppCompatActivity(R.layout.activity_dapp) { return navHostFragment.navController.navigateUp() || super.onSupportNavigateUp() } - override fun onNewIntent(intent: Intent?) { - super.onNewIntent(intent) - - Log.e("kobe", "DeepLink intent: ${intent.toString()}") - -// navHostFragment.navController.handleDeepLink(intent) - } - override fun onDestroy() { super.onDestroy() -// viewModel.disconnect() + viewModel.disconnect() } -} - +} \ No newline at end of file diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/WalletSampleActivity.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/WalletSampleActivity.kt index 160f800b08..c6084a1283 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/WalletSampleActivity.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/WalletSampleActivity.kt @@ -2,7 +2,6 @@ package com.walletconnect.wallet.ui.host import android.content.Intent import android.os.Bundle -import android.util.Log import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf @@ -62,9 +61,6 @@ class WalletSampleActivity : AppCompatActivity() { override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) - - Log.e("kobe", "DeepLink intent: ${intent.toString()}") - navController.handleDeepLink(intent) } } \ No newline at end of file From 78abb33834f750515a33befa3d88615fa63a4525 Mon Sep 17 00:00:00 2001 From: kubel Date: Thu, 4 Aug 2022 13:56:57 +0200 Subject: [PATCH 04/21] Fix deeplink for pairing --- .../ui/selected_account/SelectedAccountFragment.kt | 3 --- .../ui/selected_account/SelectedAccountViewModel.kt | 10 ++++------ .../walletconnect/dapp/ui/session/SessionFragment.kt | 1 - .../ui/host/request/SessionRequestBottomSheet.kt | 3 --- signSDK/wallet/src/main/res/navigation/nav_graph.xml | 7 +++---- 5 files changed, 7 insertions(+), 17 deletions(-) diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountFragment.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountFragment.kt index e63ece36ac..a73fa31beb 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountFragment.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountFragment.kt @@ -5,7 +5,6 @@ import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle -import android.util.Log import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels @@ -89,8 +88,6 @@ class SelectedAccountFragment : Fragment(R.layout.fragment_selected_account) { try { requireActivity().startActivity(Intent(Intent.ACTION_VIEW, sessionRequestDeeplinkUri)) } catch (exception: ActivityNotFoundException) { - - Log.e("kobe", "Dapp No Activity: $exception") // There is no app to handle deep link } } diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt index affa33c504..ab3667896e 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt @@ -1,7 +1,6 @@ package com.walletconnect.dapp.ui.selected_account import android.net.Uri -import android.util.Log import androidx.core.net.toUri import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -76,11 +75,10 @@ class SelectedAccountViewModel : ViewModel() { } } - val sessionRequestDeepLinkUri = SignClient.getListOfSettledSessions() - .find { session -> session.topic == requestParams.sessionTopic }?.metaData?.redirect?.native?.toUri() - ?: "wc:/${requestParams.sessionTopic})}/request".toUri() - - Log.e("kobe", "$sessionRequestDeepLinkUri") + val sessionRequestDeepLinkUri = + SignClient.getListOfSettledSessions() + .find { session -> session.topic == requestParams.sessionTopic }?.metaData?.redirect?.native?.toUri() + ?: "wc:/${requestParams.sessionTopic}/request".toUri() sendSessionRequestDeepLink(sessionRequestDeepLinkUri) } diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionFragment.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionFragment.kt index 76cfb08165..f8b34d1e06 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionFragment.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionFragment.kt @@ -27,7 +27,6 @@ class SessionFragment : Fragment(R.layout.fragment_session) { SessionAdapter { selectedAccount -> val selectedAccountKey = getString(R.string.selected_account) findNavController().navigate(R.id.action_fragment_session_to_fragment_selected_account, bundleOf(selectedAccountKey to selectedAccount)) -// findNavController().navigate(R.id.action_global_to_selected_account, bundleOf(selectedAccountKey to selectedAccount)) } } diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestBottomSheet.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestBottomSheet.kt index 05a200f981..156e312c4d 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestBottomSheet.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestBottomSheet.kt @@ -4,7 +4,6 @@ import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -81,8 +80,6 @@ class SessionRequestBottomSheet : BottomSheetDialogFragment() { try { requireActivity().startActivity(Intent(Intent.ACTION_VIEW, sessionRequestDeeplinkUri)) } catch (exception: ActivityNotFoundException) { - - Log.e("kobe", "Walelt No Activity: $exception") // There is no app to handle deep link } } diff --git a/signSDK/wallet/src/main/res/navigation/nav_graph.xml b/signSDK/wallet/src/main/res/navigation/nav_graph.xml index 752b90f3e5..314060d54c 100644 --- a/signSDK/wallet/src/main/res/navigation/nav_graph.xml +++ b/signSDK/wallet/src/main/res/navigation/nav_graph.xml @@ -42,7 +42,8 @@ + app:uri="kotlin-wallet-wc:/request" /> + - @@ -82,8 +82,7 @@ - + app:uri="wc:/{topic}@2" /> Date: Thu, 4 Aug 2022 14:06:41 +0200 Subject: [PATCH 05/21] Clean up --- .../kotlin/com/walletconnect/dapp/DappSampleApplication.kt | 3 +-- .../kotlin/com/walletconnect/wallet/WalletSampleApplication.kt | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt index 095e3b0833..83aeb838c2 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt @@ -29,8 +29,7 @@ class DappSampleApplication : Application() { // Sample of how to use a URI to initialize the WalletConnect SDK - val redirect = Sign.Model.Redirect(native = "kotlin-dapp-wc:/request") //todo: add deep link for Dapp - + val redirect = Sign.Model.Redirect(native = "kotlin-dapp-wc:/request") val initString = Sign.Params.Init( application = this, //TODO: register at https://walletconnect.com/register to get a project ID diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt index 9f1f4d89b3..5bc2035e44 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt @@ -30,8 +30,7 @@ class WalletSampleApplication : Application() { // Sample of how to use a URI to initialize the WalletConnect Sign SDK - val redirect = Sign.Model.Redirect(native = "kotlin-wallet-wc:/request") //todo: create a val in build confing and add to graph - + val redirect = Sign.Model.Redirect(native = "kotlin-wallet-wc:/request") val initString = Sign.Params.Init( application = this, relayServerUrl = "wss://$WALLET_CONNECT_PROD_RELAY_URL?projectId=${BuildConfig.PROJECT_ID}", From 7a26c9d9a7398ada1ece45d12356835371f93761 Mon Sep 17 00:00:00 2001 From: kubel Date: Fri, 5 Aug 2022 08:32:16 +0200 Subject: [PATCH 06/21] Add migration file --- .../sign/src/main/sqldelight/migrations/4.sqm | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 signSDK/sign/src/main/sqldelight/migrations/4.sqm diff --git a/signSDK/sign/src/main/sqldelight/migrations/4.sqm b/signSDK/sign/src/main/sqldelight/migrations/4.sqm new file mode 100644 index 0000000000..d3873bcd13 --- /dev/null +++ b/signSDK/sign/src/main/sqldelight/migrations/4.sqm @@ -0,0 +1,18 @@ +import com.walletconnect.sign.core.model.type.enums.MetaDataType; +import java.util.List; + +ALTER TABLE MetaDataDao RENAME TO MetaDataDaoBak; + +CREATE TABLE IF NOT EXISTS MetaDataDao( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + sequence_topic TEXT NOT NULL, + name TEXT NOT NULL, + description TEXT NOT NULL, + url TEXT NOT NULL, + icons TEXT AS List NOT NULL, + native TEXT, + type TEXT AS MetaDataType NOT NULL, + UNIQUE(sequence_topic, type) +); + +DROP TABLE IF EXISTS MetaDataDaoBak; \ No newline at end of file From 1a7d7237c9054f8b091a983135d739df1a5ff4a6 Mon Sep 17 00:00:00 2001 From: kubel Date: Fri, 5 Aug 2022 08:54:54 +0200 Subject: [PATCH 07/21] Fix migration file after adding test db --- .../sign/src/debug/sqldelight/migrations/3.db | Bin 0 -> 81920 bytes .../sign/src/main/sqldelight/migrations/1.sqm | 8 +------- .../sign/src/main/sqldelight/migrations/4.sqm | 5 ++++- 3 files changed, 5 insertions(+), 8 deletions(-) create mode 100644 signSDK/sign/src/debug/sqldelight/migrations/3.db diff --git a/signSDK/sign/src/debug/sqldelight/migrations/3.db b/signSDK/sign/src/debug/sqldelight/migrations/3.db new file mode 100644 index 0000000000000000000000000000000000000000..40f67d4ee3bde2400d3aea41844891bd921aca54 GIT binary patch literal 81920 zcmeI*&2QW09S3mIvZY9g%(hD=1U-~dkR?X_LQ~?h2L_o@Sk$R??#t|``Q0p_|^HF>A#-m&;2@e``qHl-%=Nc|BzT3 z-r+w@T<$9Y2}cU-{pjUX?#dPZ>7#(?b-F@*-*W6Z;_Scr-t2O9X0I?u6V0@SDaZ}eQ#ljZFsx7v??yW$9~rq7stab0>`xs zakcv6RdH=;;r+F0?`pc^THbD_(4I{_S|__T*K-2LaOzPRF&Rt}kmkzf`x%ZMcuu`e zz1k+--B0&veZA%qFR%>DC3X-~oJ-k82eUK_wfq_}Hf`roothhT-=MuWnX$qv$=o|v zc+Rp-y5m2nvtCjo+kw+uuI($<(O`JbI+a^k;Gg(S!8@MgIzFj)lzaO5(QD85*dCo%Ja%&* zyyF}9h!q!CkJas^R4S*c{L@4{A8Uhs5G*ZyG!@Hne4yjTgMnFkqrst_{hf2k+=uF6 zjW$lJCdZ{__GXf)+{6U`RBhU?(k-{sY?io>w;;JaI)7IulDmOF3KV=`9*y+7TrKjs3z9x0JYflN^ zV2?laK%C@ffat6m(}LQ^Br|qrIGKC>b^dPCy7dva{c-KUVzNi|z{(q85FBS)j_q9@ zYF>>zc^t(bVtJOm5k{TPtKpuK_S26aVY)bDPIRJp)D?;Nm6s%~9KF{h;gEtg(|d3HR&Za-xU$ z;9BuU-7!c#I%$uE7xB$2`4fK%3&sNi5P$##AOHafKmY;|fB*y_0D;pWkYzi;3;*TV z4;~PJ00bZa0SG_<0uX=z1Rwwb2%If}6hD-sc5Q7Xy8a*Lg!ah(vsF*j1_BU(00bZa z0SG_<0uX=z1R&56XzcPCu8|#nmD^iOS1M&)mkZ^RVH8wK%Y+(A*(5qG5=kaSeVv+G zQ7dZ|Nv3+GQk0}ZsiGPcMXIQ>u2qbS?|#Pq>cOJ|@@Dfd6eir(A5Fi} zD*Ffi?$#~3`-WC2l9H?|TE!%CMbiqEb=9PLK{m@;p(K@y1+65@T7|7D8=6v33hOLU zm)7NiR+fxXhAHsEGmib>0Rad=00Izz00bZa0SG_<0uX?}=@Xb6Ze$1kx*{w5ol6QI zbHcxbkA=So&xGF#zd3zX#U4Qb0uX=z1Rwwb2tWV=5P$##zO4e6h7wbJ-we1zxnx33 z$4xLQj3ln5yJr*?h7(u$uF0{7vWdi%^h#$2cn0(Rew-}NGVRYW7>@sElm6oY0SG_< z0uX=z1Rwwb2tWV=5P-lL7QprY89unE8U!E!0SG_<0uX=z1Rwwb2tc4E5Y7L`#{Yi| z5(q#50uX=z1Rwwb2tWV=5P$##PF|pq;LmaC%da&is?>62RgIpfiwX_y)qHB3s~)j^ zVg#0Bk2lk-4LdGv+@+rH*rZ3r!YdCSaC%OzDSRphdwC?!SGA!F7e2gpP&9D@6iX_mPgIboWRZ0=xhCOeN+rf{4gIg zqL398Gp4XBHGHq`afMy0R@);B^B;}po1+V(cWDk|WCIw(WcrY@QHJ50cMm^gg&Y`w znE&YU<8fA(I@t|#f0A$C>6q2Ob+6<6V^$tZb{(I3Va?oay>1!o_Qx!bCQ+rJNk&1T z>$0Shf?<>;s_F)j6uGEM8Y$>%krs=zBxz<@){9cnR5iVznCw2uCCc`QK@pRUlMIVC zsc(3e8;-eTg)dV!{8F58U2)y<#1BZlPJ>y;wy6=Y?Y6x-%X2RXTz`6M$_w*O5Z9f2 z)XZl@`6dl#i{-W0VpHQevQMp(hhhFn_7qauWQ%t1O#U%@Ja1$2sJ~qgqV~d!n|!T% zNwYFL!r>wCUB@=5cc)92sHCD%QzA;aOcb?5RCYIMQ)a*=N@OY*Wm+j26*B-QZAOmd#CS*ELA$Jq=6<&^IdgZkH$`H97wH|gwsW6|@}!kn=x z->#QgGI_}2v^VM68*h?&@WvK3EfSqU!aa_*4ny4jS+IS&X`Tk#C#Y#@M^Y3+GKvbR zNV+L&)tRC(FU@O3qd2e4Yo$_AEvs5tE`EKD> zke1j!BLvRcgfE1De+PpDstf@LKmY;|fB*y_009U<00Iy=TLPKH2p@g@ zHFQ3aWZ#HI|Hu)||2NMG^JlBNs0{=l009U<00Izz00bZa0SG|g{qjo#-3i9O)~0SG_<0uX=z z1Rwwb2tWV=5ExjXG0Wy*Y-C@XUD>=e=nRaVd09Iz`X^|8j)_*EBTM&Otaqx_<;HC` zQ*a}DT^?)516QMGdd2?P6niI8Z13#JO`Nz=U7U~R|J&q*P2rCNA7T^$0SG_<0uX=z z1Rwwb2tWV=5P-lbJtvja Date: Fri, 5 Aug 2022 09:40:24 +0200 Subject: [PATCH 08/21] Add drop session dao --- .../sign/src/main/sqldelight/migrations/1.sqm | 2 -- .../sign/src/main/sqldelight/migrations/4.sqm | 16 ++++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/signSDK/sign/src/main/sqldelight/migrations/1.sqm b/signSDK/sign/src/main/sqldelight/migrations/1.sqm index 0a7f11794d..e56fa6155a 100644 --- a/signSDK/sign/src/main/sqldelight/migrations/1.sqm +++ b/signSDK/sign/src/main/sqldelight/migrations/1.sqm @@ -30,8 +30,6 @@ CREATE TABLE IF NOT EXISTS SessionDao( DROP TABLE IF EXISTS SessionDaoBak; -- MetaDataDao --- ALTER TABLE MetaDataDao RENAME TO MetaDataDaoBak; - CREATE TABLE IF NOT EXISTS MetaDataDao( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, sequence_topic TEXT NOT NULL, diff --git a/signSDK/sign/src/main/sqldelight/migrations/4.sqm b/signSDK/sign/src/main/sqldelight/migrations/4.sqm index 4f449ab421..b2397cb151 100644 --- a/signSDK/sign/src/main/sqldelight/migrations/4.sqm +++ b/signSDK/sign/src/main/sqldelight/migrations/4.sqm @@ -17,5 +17,21 @@ CREATE TABLE IF NOT EXISTS MetaDataDao( DROP TABLE IF EXISTS MetaDataDaoBak; +ALTER TABLE SessionDao RENAME TO SessionDaoBak; + +CREATE TABLE IF NOT EXISTS SessionDao( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + topic TEXT UNIQUE NOT NULL, + expiry INTEGER NOT NULL, + relay_protocol TEXT NOT NULL, + relay_data TEXT, + controller_key TEXT, + self_participant TEXT NOT NULL, + peer_participant TEXT, + is_acknowledged INTEGER AS Boolean NOT NULL +); + +DROP TABLE IF EXISTS SessionDaoBak; + -- android_metadata DROP TABLE IF EXISTS android_metadata; \ No newline at end of file From a5dfe44448e3f86aa784ab4e6c59e6e7f87f4d46 Mon Sep 17 00:00:00 2001 From: Derek Date: Fri, 5 Aug 2022 13:57:05 +0200 Subject: [PATCH 09/21] fix: only adds issues not PRs --- .github/workflows/intake.yml | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/.github/workflows/intake.yml b/.github/workflows/intake.yml index 4e05990cd0..5ec7570ca4 100644 --- a/.github/workflows/intake.yml +++ b/.github/workflows/intake.yml @@ -1,4 +1,4 @@ -# This workflow moves issues to the Kotlin board +# This workflow moves issues to the board # when they receive the "accepted" label # When WalletConnect Org members create issues they # are automatically "accepted". @@ -8,8 +8,6 @@ name: intake on: issues: types: [opened, labeled] - pull_request: - types: [opened, labeled] jobs: add-to-project: @@ -28,15 +26,20 @@ jobs: if: github.event.action == 'opened' runs-on: ubuntu-latest steps: - - name: Check if organization member - id: is_organization_member - if: github.event.action == 'opened' - uses: JamesSingleton/is-organization-member@1.0.0 + - name: Check Core Team membership + uses: tspascoal/get-user-teams-membership@v1 + id: is-core-team with: - organization: WalletConnect username: ${{ github.event_name != 'pull_request' && github.event.issue.user.login || github.event.sender.login }} - token: ${{ secrets.ASSIGN_TO_PROJECT_GITHUB_TOKEN }} + team: "Core Team" + GITHUB_TOKEN: ${{ secrets.ASSIGN_TO_PROJECT_GITHUB_TOKEN }} + - name: Print result + env: + CREATOR: ${{ github.event_name != 'pull_request' && github.event.issue.user.login || github.event.sender.login }} + IS_TEAM_MEMBER: ${{ steps.is-core-team.outputs.isTeamMember }} + run: echo "$CREATOR (Core Team Member $IS_TEAM_MEMBER) created this issue/PR" - name: Label issues + if: ${{ steps.is-core-team.outputs.isTeamMember == 'true' }} uses: andymckay/labeler@e6c4322d0397f3240f0e7e30a33b5c5df2d39e90 with: add-labels: "accepted" From b372b0cbdb5465b0190ec10455af31b5d2542dd3 Mon Sep 17 00:00:00 2001 From: kubel Date: Fri, 5 Aug 2022 15:48:14 +0200 Subject: [PATCH 10/21] Fix for first migration file --- .../sign/src/main/sqldelight/migrations/1.sqm | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/signSDK/sign/src/main/sqldelight/migrations/1.sqm b/signSDK/sign/src/main/sqldelight/migrations/1.sqm index e56fa6155a..8f4ce391e4 100644 --- a/signSDK/sign/src/main/sqldelight/migrations/1.sqm +++ b/signSDK/sign/src/main/sqldelight/migrations/1.sqm @@ -2,7 +2,9 @@ import com.walletconnect.sign.core.model.type.enums.MetaDataType; import kotlin.collections.List; -- PairingDao -CREATE TABLE IF NOT EXISTS PairingDao ( +DROP TABLE IF EXISTS PairingDao; + +CREATE TABLE PairingDao ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, topic TEXT UNIQUE NOT NULL, expiry INTEGER NOT NULL, @@ -12,10 +14,10 @@ CREATE TABLE IF NOT EXISTS PairingDao ( is_active INTEGER AS Boolean NOT NULL ); -DROP TABLE IF EXISTS PairingDaoBak; - -- SessionDao -CREATE TABLE IF NOT EXISTS SessionDao( +DROP TABLE IF EXISTS SessionDao; + +CREATE TABLE SessionDao( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, topic TEXT UNIQUE NOT NULL, expiry INTEGER NOT NULL, @@ -27,10 +29,10 @@ CREATE TABLE IF NOT EXISTS SessionDao( is_acknowledged INTEGER AS Boolean NOT NULL ); -DROP TABLE IF EXISTS SessionDaoBak; - -- MetaDataDao -CREATE TABLE IF NOT EXISTS MetaDataDao( +DROP TABLE IF EXISTS MetaDataDao; + +CREATE TABLE MetaDataDao( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, sequence_topic TEXT NOT NULL, name TEXT NOT NULL, @@ -41,10 +43,10 @@ CREATE TABLE IF NOT EXISTS MetaDataDao( UNIQUE(sequence_topic, type) ); -DROP TABLE IF EXISTS MetaDataDaoBak; - -- JsonRpcHistoryDao -CREATE TABLE IF NOT EXISTS JsonRpcHistoryDao( +DROP TABLE IF EXISTS JsonRpcHistoryDao; + +CREATE TABLE JsonRpcHistoryDao( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, request_id INTEGER UNIQUE NOT NULL, topic TEXT NOT NULL, @@ -53,10 +55,10 @@ CREATE TABLE IF NOT EXISTS JsonRpcHistoryDao( response TEXT AS String ); -DROP TABLE IF EXISTS JsonRpcHistoryDaoBak; - -- NamespaceDao -CREATE TABLE IF NOT EXISTS NamespaceDao( +DROP TABLE IF EXISTS NamespaceDao; + +CREATE TABLE NamespaceDao( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, session_id INTEGER NOT NULL, key TEXT NOT NULL, From 6c0603efcb5427a7ef1d7cabca733b11fdaf8f97 Mon Sep 17 00:00:00 2001 From: kubel Date: Tue, 9 Aug 2022 11:09:39 +0200 Subject: [PATCH 11/21] Remove redirect object from public app metadata --- .../com/walletconnect/dapp/DappSampleApplication.kt | 4 +--- .../dapp/ui/selected_account/SelectedAccountViewModel.kt | 2 +- .../src/main/kotlin/com/walletconnect/sign/client/Sign.kt | 7 +------ .../com/walletconnect/sign/client/mapper/ClientMapper.kt | 4 ++-- .../com/walletconnect/sign/engine/model/EngineDO.kt | 7 +------ .../sign/engine/model/mapper/EngineMapper.kt | 8 ++++---- .../com/walletconnect/wallet/WalletSampleApplication.kt | 4 +--- .../wallet/ui/host/request/SessionRequestViewModel.kt | 2 +- 8 files changed, 12 insertions(+), 26 deletions(-) diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt index 83aeb838c2..25d488fabc 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/DappSampleApplication.kt @@ -28,8 +28,6 @@ class DappSampleApplication : Application() { // ) // Sample of how to use a URI to initialize the WalletConnect SDK - - val redirect = Sign.Model.Redirect(native = "kotlin-dapp-wc:/request") val initString = Sign.Params.Init( application = this, //TODO: register at https://walletconnect.com/register to get a project ID @@ -39,7 +37,7 @@ class DappSampleApplication : Application() { description = "Dapp description", url = "example.dapp", icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media"), - redirect = redirect + redirect = "kotlin-dapp-wc:/request" ) ) diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt index ab3667896e..9780514451 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt @@ -77,7 +77,7 @@ class SelectedAccountViewModel : ViewModel() { val sessionRequestDeepLinkUri = SignClient.getListOfSettledSessions() - .find { session -> session.topic == requestParams.sessionTopic }?.metaData?.redirect?.native?.toUri() + .find { session -> session.topic == requestParams.sessionTopic }?.metaData?.redirect?.toUri() ?: "wc:/${requestParams.sessionTopic}/request".toUri() sendSessionRequestDeepLink(sessionRequestDeepLinkUri) diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt index 5e996e8623..2414b15dea 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt @@ -152,12 +152,7 @@ object Sign { val description: String, val url: String, val icons: List, - val redirect: Redirect?, - ) : Model() - - data class Redirect( - val native: String? = null, - val universal: String? = null, + val redirect: String?, ) : Model() data class PendingRequest( diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt index c7246bca6c..cef153ddab 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt @@ -124,11 +124,11 @@ internal fun Map.toMapOfClientNamespacesSess @JvmSynthetic internal fun Sign.Model.AppMetaData.toEngineAppMetaData() = - EngineDO.AppMetaData(name, description, url, icons, EngineDO.Redirect(redirect?.native, redirect?.universal)) + EngineDO.AppMetaData(name, description, url, icons, redirect) @JvmSynthetic internal fun EngineDO.AppMetaData.toClientAppMetaData() = - Sign.Model.AppMetaData(name, description, url, icons, Sign.Model.Redirect(redirect?.native, redirect?.universal)) + Sign.Model.AppMetaData(name, description, url, icons, redirect) @JvmSynthetic internal fun Sign.Params.Request.toEngineDORequest(): EngineDO.Request = diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/EngineDO.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/EngineDO.kt index 07faa3298d..5a2bb38edf 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/EngineDO.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/EngineDO.kt @@ -160,12 +160,7 @@ internal sealed class EngineDO { val description: String, val url: String, val icons: List, - val redirect: Redirect?, - ) : EngineDO() - - internal data class Redirect( - val native: String? = null, - val universal: String? = null, + val redirect: String?, ) : EngineDO() internal data class ConnectionState( diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/mapper/EngineMapper.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/mapper/EngineMapper.kt index a3a74e7f5e..a43e15aee4 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/mapper/EngineMapper.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/engine/model/mapper/EngineMapper.kt @@ -31,11 +31,11 @@ private fun EngineDO.WalletConnectUri.getQuery(): String { @JvmSynthetic internal fun EngineDO.AppMetaData.toMetaDataVO() = - MetaDataVO(name, description, url, icons, RedirectVO(redirect?.native, redirect?.universal)) + MetaDataVO(name, description, url, icons, RedirectVO(redirect)) @JvmSynthetic internal fun MetaDataVO.toEngineDOMetaData(): EngineDO.AppMetaData = - EngineDO.AppMetaData(name, description, url, icons, EngineDO.Redirect(redirect?.native, redirect?.universal)) + EngineDO.AppMetaData(name, description, url, icons, redirect?.native) @JvmSynthetic internal fun PairingParamsVO.SessionProposeParams.toEngineDOSessionProposal(): EngineDO.SessionProposal = @@ -85,7 +85,7 @@ internal fun SessionVO.toEngineDOApprovedSessionVO(): EngineDO.Session = peerMetaData?.description ?: String.Empty, peerMetaData?.url ?: String.Empty, peerMetaData?.icons?.map { iconUri -> iconUri } ?: listOf(), - EngineDO.Redirect(peerMetaData?.redirect?.native, peerMetaData?.redirect?.universal) + peerMetaData?.redirect?.native ) ) @@ -95,7 +95,7 @@ internal fun SessionVO.toEngineDOSessionExtend(expiryVO: ExpiryVO): EngineDO.Ses @JvmSynthetic private fun MetaDataVO.toEngineDOAppMetaData(): EngineDO.AppMetaData = - EngineDO.AppMetaData(name, description, url, icons, EngineDO.Redirect(redirect?.native, redirect?.universal)) + EngineDO.AppMetaData(name, description, url, icons, redirect?.native) @JvmSynthetic internal fun PairingVO.toEngineDOSettledPairing(): EngineDO.PairingSettle = diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt index 5bc2035e44..2dd769d7ce 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/WalletSampleApplication.kt @@ -29,8 +29,6 @@ class WalletSampleApplication : Application() { // ) // Sample of how to use a URI to initialize the WalletConnect Sign SDK - - val redirect = Sign.Model.Redirect(native = "kotlin-wallet-wc:/request") val initString = Sign.Params.Init( application = this, relayServerUrl = "wss://$WALLET_CONNECT_PROD_RELAY_URL?projectId=${BuildConfig.PROJECT_ID}", @@ -40,7 +38,7 @@ class WalletSampleApplication : Application() { description = "Wallet description", url = "example.wallet", icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media"), - redirect = redirect + redirect = "kotlin-wallet-wc:/request" ) ) diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt index c12fd526bc..469cffd521 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt @@ -84,7 +84,7 @@ class SessionRequestViewModel : ViewModel() { sendSessionRequestResponseDeepLink: (Uri) -> Unit, ) { val session = SignClient.getListOfSettledSessions().find { session -> session.topic == sessionRequest.topic } - val deepLinUri = session?.metaData?.redirect?.native?.toUri() ?: "wc:/${sessionRequest.topic})}/request".toUri() + val deepLinUri = session?.metaData?.redirect?.toUri() ?: "wc:/${sessionRequest.topic})}/request".toUri() sendSessionRequestResponseDeepLink(deepLinUri) } From d251957759b15da1435283630d52a976eb4c95a5 Mon Sep 17 00:00:00 2001 From: szymon Date: Thu, 4 Aug 2022 14:26:01 +0200 Subject: [PATCH 12/21] feat: Add relay integration tests --- signSDK/sign/build.gradle.kts | 12 +- .../sign/SessionRequestParserTest.kt | 55 -- .../sign/WCIntegrationActivityScenarioRule.kt | 47 -- .../dapp/DappClientAndroidIntegrationTest.kt | 52 -- .../test/relay/RelayIntegrationAndroidTest.kt | 101 ++++ .../utils/IntegrationTestActivity.kt | 2 +- .../utils/IntegrationTestApplication.kt | 2 +- .../WCIntegrationActivityScenarioRule.kt | 145 +++++ .../sign/{ => test/utils}/WCTestRunner.kt | 3 +- .../WalletClientIntegrationAndroidTest.kt | 516 ------------------ .../walletconnect/sign/di/StorageModule.kt | 118 +--- .../walletconnect/sign/client/SignProtocol.kt | 13 +- .../sign/di/SharedStorageModule.kt | 129 +++++ .../com/walletconnect/sign/di/DITags.kt | 6 + .../walletconnect/sign/di/StorageModule.kt | 34 ++ .../di/StorageModule.kt | 117 +--- 16 files changed, 443 insertions(+), 909 deletions(-) delete mode 100644 signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/SessionRequestParserTest.kt delete mode 100644 signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/WCIntegrationActivityScenarioRule.kt delete mode 100644 signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/dapp/DappClientAndroidIntegrationTest.kt create mode 100644 signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/relay/RelayIntegrationAndroidTest.kt rename signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/{ => test}/utils/IntegrationTestActivity.kt (87%) rename signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/{ => test}/utils/IntegrationTestApplication.kt (65%) create mode 100644 signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/WCIntegrationActivityScenarioRule.kt rename signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/{ => test/utils}/WCTestRunner.kt (79%) delete mode 100644 signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/wallet/WalletClientIntegrationAndroidTest.kt create mode 100644 signSDK/sign/src/main/kotlin/com/walletconnect/sign/di/SharedStorageModule.kt create mode 100644 signSDK/sign/src/qa/kotlin/com/walletconnect/sign/di/DITags.kt create mode 100644 signSDK/sign/src/qa/kotlin/com/walletconnect/sign/di/StorageModule.kt diff --git a/signSDK/sign/build.gradle.kts b/signSDK/sign/build.gradle.kts index d55d4e070b..236927ae86 100644 --- a/signSDK/sign/build.gradle.kts +++ b/signSDK/sign/build.gradle.kts @@ -23,8 +23,9 @@ android { targetSdk = 32 } - testInstrumentationRunner = "com.walletconnect.sign.WCTestRunner" + testInstrumentationRunner = "com.walletconnect.sign.test.utils.WCTestRunner" testInstrumentationRunnerArguments += mutableMapOf("runnerBuilder" to "de.mannodermaus.junit5.AndroidJUnit5Builder") + testInstrumentationRunnerArguments += mutableMapOf("clearPackageData" to "true") } buildTypes { @@ -35,8 +36,17 @@ android { "proguard-rules.pro" ) } + create("qa"){ + initWith(getByName("debug")) + signingConfig = signingConfigs.getByName("debug") + + buildConfigField("String", "PROJECT_ID", "\"${System.getenv("TEST_PROJECT_ID") ?: ""}\"") + buildConfigField("String", "WC_RELAY_URL", "\"${System.getenv("TEST_RELAY_URL") ?: ""}\"") + } } + testBuildType = "qa" + compileOptions { sourceCompatibility = jvmVersion targetCompatibility = jvmVersion diff --git a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/SessionRequestParserTest.kt b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/SessionRequestParserTest.kt deleted file mode 100644 index 6ad8dc09be..0000000000 --- a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/SessionRequestParserTest.kt +++ /dev/null @@ -1,55 +0,0 @@ -package com.walletconnect.sign - -import org.json.JSONArray -import org.json.JSONObject -import org.junit.jupiter.api.Assertions -import org.junit.jupiter.api.Test - -class SessionRequestParserTest { - - @Test - fun testJsonArrayParsing() { - val json = - "[{\"from\":\"0x022c0c42a80bd19EA4cF0F94c4F9F96645759716\",\"to\":\"0x022c0c42a80bd19EA4cF0F94c4F9F96645759716\",\"data\":\"0x\",\"nonce\":0,\"gasPrice\":27000000000,\"gasLimit\":21000,\"value\":0}]" - - val params = JSONArray(json) - val from = params.getJSONObject(0).getString("from") - val to = params.getJSONObject(0).getString("to") - val data = params.getJSONObject(0).getString("data") - val none = params.getJSONObject(0).getDouble("nonce") - val gasPrice = params.getJSONObject(0).getLong("gasPrice") - val gasLimit = params.getJSONObject(0).getLong("gasLimit") - val value = params.getJSONObject(0).getInt("value") - - Assertions.assertEquals("0x022c0c42a80bd19EA4cF0F94c4F9F96645759716", from) - Assertions.assertEquals("0x022c0c42a80bd19EA4cF0F94c4F9F96645759716", to) - Assertions.assertEquals("0x", data) - Assertions.assertEquals(0.0, none) - Assertions.assertEquals(27000000000, gasPrice) - Assertions.assertEquals(21000, gasLimit) - Assertions.assertEquals(0, value) - } - - @Test - fun testJsonObjectParsing() { - val json = - "{\"from\":\"0x022c0c42a80bd19EA4cF0F94c4F9F96645759716\",\"to\":\"0x022c0c42a80bd19EA4cF0F94c4F9F96645759716\",\"data\":\"0x\",\"nonce\":0,\"gasPrice\":27000000000,\"gasLimit\":21000,\"value\":0}" - - val params = JSONObject(json) - val from = params.getString("from") - val to = params.getString("to") - val data = params.getString("data") - val none = params.getDouble("nonce") - val gasPrice = params.getLong("gasPrice") - val gasLimit = params.getLong("gasLimit") - val value = params.getInt("value") - - Assertions.assertEquals("0x022c0c42a80bd19EA4cF0F94c4F9F96645759716", from) - Assertions.assertEquals("0x022c0c42a80bd19EA4cF0F94c4F9F96645759716", to) - Assertions.assertEquals("0x", data) - Assertions.assertEquals(0.0, none) - Assertions.assertEquals(27000000000, gasPrice) - Assertions.assertEquals(21000, gasLimit) - Assertions.assertEquals(0, value) - } -} \ No newline at end of file diff --git a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/WCIntegrationActivityScenarioRule.kt b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/WCIntegrationActivityScenarioRule.kt deleted file mode 100644 index 4674f43efd..0000000000 --- a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/WCIntegrationActivityScenarioRule.kt +++ /dev/null @@ -1,47 +0,0 @@ -package com.walletconnect.sign - -import androidx.lifecycle.Lifecycle -import androidx.test.core.app.ActivityScenario -import com.walletconnect.sign.utils.IntegrationTestActivity -import org.junit.Assert -import org.junit.rules.ExternalResource -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit - -// Source: https://gist.github.com/zawadz88/f057c70d3061454207ccd56e0add81c6#file-lazyactivityscenariorule-kt -class WCIntegrationActivityScenarioRule : ExternalResource() { - private var scenario: ActivityScenario? = null - private var scenarioLaunched: Boolean = false - private val latch = CountDownLatch(1) - - override fun before() { - } - - override fun after() { - scenario?.close() - } - - fun launch(timeoutMinutes: Long = 1, testCodeBlock: () -> Unit) { - require(!scenarioLaunched) { "Scenario has already been launched!" } - - scenario = ActivityScenario.launch(IntegrationTestActivity::class.java) - scenarioLaunched = true - - scenario?.moveToState(Lifecycle.State.RESUMED) - assert(scenario?.state?.isAtLeast(Lifecycle.State.RESUMED) == true) - - testCodeBlock() - - try { - latch.await(timeoutMinutes, TimeUnit.MINUTES) - } catch (exception: InterruptedException) { - Assert.fail(exception.stackTraceToString()) - } catch (exception: IllegalArgumentException) { - Assert.fail(exception.stackTraceToString()) - } - } - - fun close() { - latch.countDown() - } -} \ No newline at end of file diff --git a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/dapp/DappClientAndroidIntegrationTest.kt b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/dapp/DappClientAndroidIntegrationTest.kt deleted file mode 100644 index 89234962fe..0000000000 --- a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/dapp/DappClientAndroidIntegrationTest.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.walletconnect.sign.dapp - -// fixme -class DappClientAndroidIntegrationTest { -// -// @get:Rule -// val activityRule = WCIntegrationActivityScenarioRule() -// private val app = ApplicationProvider.getApplicationContext() -// -// private val metadata = WalletConnect.Model.AppMetaData( -// name = "Kotlin Wallet", -// description = "Wallet description", -// url = "example.wallet", -// icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media") -// ) -// -// @Test -// fun testDappConnectMethod() { -// val initParams = WalletConnect.Params.Init( -// application = app, -// useTls = true, -// hostName = "", -// projectId = "", -// metadata = WalletConnect.Model.AppMetaData( -// name = "Kotlin Dapp", -// description = "Dapp description", -// url = "example.dapp", -// icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media") -// ) -// ) -// AuthClient.initialize(initParams) -// -// AuthClient.connect( -// WalletConnect.Params.Connect( -// permissions = WalletConnect.Model.SessionPermissions(methods = WalletConnect.Model.JsonRpc(listOf("eth_sign"))), -// blockchain = WalletConnect.Model.Blockchain(listOf("1", "2")) -// ), -// onProposedSequence = { proposedSequence -> -// when (proposedSequence) { -// is WalletConnect.Model.ProposedSequence.Pairing -> { -// -// } -// -// is WalletConnect.Model.ProposedSequence.Session -> { -// -// } -// } -// -// } -// ) -// } -} \ No newline at end of file diff --git a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/relay/RelayIntegrationAndroidTest.kt b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/relay/RelayIntegrationAndroidTest.kt new file mode 100644 index 0000000000..39d2846c8e --- /dev/null +++ b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/relay/RelayIntegrationAndroidTest.kt @@ -0,0 +1,101 @@ +package com.walletconnect.sign.test.relay + +import com.walletconnect.sign.test.utils.WCIntegrationActivityScenarioRule +import com.walletconnect.sign.client.Sign +import com.walletconnect.sign.client.SignClient +import com.walletconnect.sign.util.Logger +import org.junit.Rule +import org.junit.Test +import org.junit.jupiter.api.fail + +class RelayIntegrationAndroidTest { + @get:Rule + val activityRule = WCIntegrationActivityScenarioRule() + + private fun globalOnError(error: Sign.Model.Error) { + fail(error.throwable) + } + + private fun setDelegates(walletDelegate: SignClient.WalletDelegate, dappDelegate: SignClient.DappDelegate) { + activityRule.walletClient.setWalletDelegate(walletDelegate) + activityRule.dappClient.setDappDelegate(dappDelegate) + } + + @Test + fun pairAndPing() { + val walletDelegate = object : SignClient.WalletDelegate { + override fun onSessionRequest(sessionRequest: Sign.Model.SessionRequest) {} + override fun onSessionDelete(deletedSession: Sign.Model.DeletedSession) {} + override fun onSessionSettleResponse(settleSessionResponse: Sign.Model.SettledSessionResponse) {} + override fun onSessionUpdateResponse(sessionUpdateResponse: Sign.Model.SessionUpdateResponse) {} + override fun onConnectionStateChange(state: Sign.Model.ConnectionState) {} + override fun onError(error: Sign.Model.Error) { + globalOnError(error) + } + + override fun onSessionProposal(sessionProposal: Sign.Model.SessionProposal) { + val namespaces: Map = mapOf( + "eip155" to Sign.Model.Namespace.Session(listOf("eip155:1:0xab16a96d359ec26a11e2c2b3d8f8b8942d5bfcdb"), + listOf("someMethod"), + listOf("someEvent"), + null) + ) + + activityRule.walletClient.approveSession(Sign.Params.Approve(sessionProposal.proposerPublicKey, namespaces), + ::globalOnError) + } + + } + + val dappDelegate = object : SignClient.DappDelegate { + override fun onSessionRejected(rejectedSession: Sign.Model.RejectedSession) {} + override fun onSessionUpdate(updatedSession: Sign.Model.UpdatedSession) {} + override fun onSessionEvent(sessionEvent: Sign.Model.SessionEvent) {} + override fun onSessionExtend(session: Sign.Model.Session) {} + override fun onSessionDelete(deletedSession: Sign.Model.DeletedSession) {} + override fun onSessionRequestResponse(response: Sign.Model.SessionRequestResponse) {} + override fun onConnectionStateChange(state: Sign.Model.ConnectionState) {} + override fun onError(error: Sign.Model.Error) { + globalOnError(error) + } + + override fun onSessionApproved(approvedSession: Sign.Model.ApprovedSession) { + activityRule.dappClient.ping(Sign.Params.Ping(approvedSession.topic), object : Sign.Listeners.SessionPing { + override fun onSuccess(pingSuccess: Sign.Model.Ping.Success) { + activityRule.close() + } + + override fun onError(pingError: Sign.Model.Ping.Error) { + fail(pingError.error) + } + }) + } + } + + setDelegates(walletDelegate, dappDelegate) + + activityRule.launch(10L) { + val namespaces: Map = mapOf( + "eip155" to Sign.Model.Namespace.Proposal(listOf("eip155:1"), listOf("someMethod"), listOf("someEvent"), null) + ) + + val connectParams = Sign.Params.Connect( + namespaces = namespaces, + pairingTopic = null + ) + + activityRule.dappClient.connect(connectParams, + onProposedSequence = { proposedSequence -> + if (proposedSequence is Sign.Model.ProposedSequence.Pairing) { + activityRule.walletClient.pair(Sign.Params.Pair(proposedSequence.uri), ::globalOnError) + } else { + Logger.error("proposedSequence !is Sign.Model.ProposedSequence.Pairing") + } + }, + onError = { + globalOnError(it) + } + ) + } + } +} \ No newline at end of file diff --git a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/utils/IntegrationTestActivity.kt b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/IntegrationTestActivity.kt similarity index 87% rename from signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/utils/IntegrationTestActivity.kt rename to signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/IntegrationTestActivity.kt index 437f16f646..96974ed54a 100644 --- a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/utils/IntegrationTestActivity.kt +++ b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/IntegrationTestActivity.kt @@ -1,4 +1,4 @@ -package com.walletconnect.sign.utils +package com.walletconnect.sign.test.utils import android.app.Activity import android.os.Bundle diff --git a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/utils/IntegrationTestApplication.kt b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/IntegrationTestApplication.kt similarity index 65% rename from signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/utils/IntegrationTestApplication.kt rename to signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/IntegrationTestApplication.kt index c931e3a8fe..c369abc301 100644 --- a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/utils/IntegrationTestApplication.kt +++ b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/IntegrationTestApplication.kt @@ -1,4 +1,4 @@ -package com.walletconnect.sign.utils +package com.walletconnect.sign.test.utils import android.app.Application diff --git a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/WCIntegrationActivityScenarioRule.kt b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/WCIntegrationActivityScenarioRule.kt new file mode 100644 index 0000000000..f5595d9142 --- /dev/null +++ b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/WCIntegrationActivityScenarioRule.kt @@ -0,0 +1,145 @@ +package com.walletconnect.sign.test.utils + +import android.net.Uri +import androidx.lifecycle.Lifecycle +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import com.walletconnect.sign.BuildConfig +import com.walletconnect.sign.client.Sign +import com.walletconnect.sign.client.SignProtocol +import com.walletconnect.sign.core.model.client.Relay +import com.walletconnect.sign.core.scope.scope +import com.walletconnect.sign.util.Logger +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.* +import org.junit.Assert +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.rules.ExternalResource +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +// Source: https://gist.github.com/zawadz88/f057c70d3061454207ccd56e0add81c6#file-lazyactivityscenariorule-kt +class WCIntegrationActivityScenarioRule : ExternalResource() { + private var scenario: ActivityScenario? = null + private var scenarioLaunched: Boolean = false + private val latch = CountDownLatch(1) + private val testScope: CoroutineScope = CoroutineScope(Dispatchers.Default) + private val app = ApplicationProvider.getApplicationContext() + + private val relayUrl = BuildConfig.WC_RELAY_URL.split(URL_DELIMETER).let { (scheme, hostName) -> + Uri.Builder() + .scheme(scheme) + .authority(hostName) + .appendQueryParameter(PROJECT_ID_KEY, BuildConfig.PROJECT_ID) + .build() + .toString() + } + + private val walletMetadata = Sign.Model.AppMetaData( + name = "Kotlin Wallet", + description = "Wallet description", + url = "example.wallet", + icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media") + ) + + private val walletParams = Sign.Params.Init( + application = app, + relayServerUrl = relayUrl, + metadata = walletMetadata, + connectionType = Sign.ConnectionType.MANUAL + ) + + + internal val walletClient = SignProtocol().apply { + initialize(walletParams) {} + blockUntilInitialized() + relay.connect { } + } + + + private val dappMetadata = Sign.Model.AppMetaData( + name = "Kotlin Dapp", + description = "Dapp description", + url = "example.dapp", + icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media") + ) + + private val dappParams = Sign.Params.Init( + application = app, + relayServerUrl = relayUrl, + metadata = dappMetadata, + connectionType = Sign.ConnectionType.MANUAL + ) + + internal val dappClient = SignProtocol().apply { + initialize(dappParams) {} + blockUntilInitialized() + relay.connect { } + } + + override fun before() { + runBlocking { + val isDappReady = MutableStateFlow(false) + val isWalletReady = MutableStateFlow(false) + val areBothReady: StateFlow = + combine(isDappReady, isWalletReady) { dapp, wallet -> dapp && wallet }.stateIn(scope, SharingStarted.Eagerly, false) + + val dappJob = dappClient.relay.eventsFlow.onEach { event -> + when (event) { + is Relay.Model.Event.OnConnectionOpened<*> -> isDappReady.compareAndSet(expect = false, update = true) + else -> {} + } + }.launchIn(scope) + + val walletJob = walletClient.relay.eventsFlow.onEach { event -> + when (event) { + is Relay.Model.Event.OnConnectionOpened<*> -> isWalletReady.compareAndSet(expect = false, update = true) + else -> {} + } + }.launchIn(scope) + + while (!areBothReady.value) { + delay(100) + } + + dappJob.cancel() + walletJob.cancel() + Logger.log("Connection established with: $relayUrl") + } + } + + override fun after() { + scenario?.close() + } + + fun launch(timeoutSeconds: Long = 1, testCodeBlock: () -> Unit) { + require(!scenarioLaunched) { "Scenario has already been launched!" } + + scenario = ActivityScenario.launch(IntegrationTestActivity::class.java) + scenarioLaunched = true + + scenario?.moveToState(Lifecycle.State.RESUMED) + assert(scenario?.state?.isAtLeast(Lifecycle.State.RESUMED) == true) + + testScope.launch { testCodeBlock() } + + try { + assertTrue(latch.await(timeoutSeconds, TimeUnit.SECONDS)) + } catch (exception: InterruptedException) { + Assert.fail(exception.stackTraceToString()) + testScope.cancel() + } catch (exception: IllegalArgumentException) { + Assert.fail(exception.stackTraceToString()) + testScope.cancel() + } + } + + fun close() { + latch.countDown() + } + + companion object { + const val URL_DELIMETER = "://" + const val PROJECT_ID_KEY = "projectId" + } +} \ No newline at end of file diff --git a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/WCTestRunner.kt b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/WCTestRunner.kt similarity index 79% rename from signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/WCTestRunner.kt rename to signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/WCTestRunner.kt index abbefc02c1..d37c765b3f 100644 --- a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/WCTestRunner.kt +++ b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/WCTestRunner.kt @@ -1,9 +1,8 @@ -package com.walletconnect.sign +package com.walletconnect.sign.test.utils import android.app.Application import android.content.Context import androidx.test.runner.AndroidJUnitRunner -import com.walletconnect.sign.utils.IntegrationTestApplication class WCTestRunner : AndroidJUnitRunner() { diff --git a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/wallet/WalletClientIntegrationAndroidTest.kt b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/wallet/WalletClientIntegrationAndroidTest.kt deleted file mode 100644 index 6ed0652db9..0000000000 --- a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/wallet/WalletClientIntegrationAndroidTest.kt +++ /dev/null @@ -1,516 +0,0 @@ -package com.walletconnect.sign.wallet - -//fixme -class AuthClientIntegrationAndroidTest { -// @get:Rule -// val activityRule = WCIntegrationActivityScenarioRule() -// private val app = ApplicationProvider.getApplicationContext() -// -// private val metadata = WalletConnect.Model.AppMetaData( -// name = "Kotlin Wallet", -// description = "Wallet description", -// url = "example.wallet", -// icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media") -// ) -// -// @Test -// fun responderApprovePairingAndGetSessionProposalTest() { -// activityRule.launch { -// val initParams = WalletConnect.Params.Init( -// application = app, -// useTls = true, -// hostName = "relay.walletconnect.org", -// projectId = "2ee94aca5d98e6c05c38bce02bee952a", -// metadata = metadata -// ) -// AuthClient.initialize(initParams) -// val uri = -// "wc:4f47abd615d5b56941989e120f108c2f338801ce16ee902237654b8c1970e8a2@2?controller=false&publicKey=2d573da1d2b8dbe3dcdb6ce7de47ce44b18fb8ec5ddc9d3f412ab4a718fff93c&relay=%7B%22protocol%22%3A%22waku%22%7D" -// val pairingParams = WalletConnect.Params.Pair(uri) -// -// val delegate = object : AuthClient.WalletDelegate { -// override fun onSessionProposal(sessionProposal: WalletConnect.Model.SessionProposal) { -// assert(true) -// activityRule.close() -// } -// -// override fun onSessionRequest(sessionRequest: WalletConnect.Model.SessionRequest) {} -// override fun onSessionDelete(deletedSession: WalletConnect.Model.DeletedSession) {} -// override fun onSessionEvent(sessionEvent: WalletConnect.Model.SessionEvent) {} -// override fun onPairingSettledResponse(response: WalletConnect.Model.SettledPairingResponse) { -// Logger.log("Pairing settle response: $response") -// } -// -// override fun onSessionSettleResponse(response: WalletConnect.Model.SettledSessionResponse) { -// Logger.log("Session settle response: $response") -// } -// -// override fun onSessionUpgradeResponse(response: WalletConnect.Model.SessionUpgradeResponse) {} -// override fun onSessionUpdateAccountsResponse(response: WalletConnect.Model.SessionUpdateAccountsResponse) {} -// } -// -// AuthClient.setWalletDelegate(delegate) -// AuthClient.pair(pairingParams) -// } -// } -// -// @Test -// fun responderSessionApproveTest() { -// activityRule.launch { -// val initParams = WalletConnect.Params.Init( -// application = app, -// useTls = true, -// hostName = "relay.walletconnect.org", -// projectId = "2ee94aca5d98e6c05c38bce02bee952a", -// metadata = metadata -// ) -// AuthClient.initialize(initParams) -// -// val uri = -// "wc:76a4fd7ab4015aa22ad77bfa0cd0bc563047fd3d92ad5285db71e80cea68f9ca@2?controller=false&publicKey=7a6875ec8512a8d77be1ddd23797a08d078627c0f85887bf0452be97b7390e34&relay=%7B%22protocol%22%3A%22waku%22%7D" -// val pairingParams = WalletConnect.Params.Pair(uri) -// val listener = object : AuthClient.WalletDelegate { -// override fun onSessionProposal(sessionProposal: WalletConnect.Model.SessionProposal) { -// assert(true) -// val accounts = sessionProposal.chains.map { chainId -> "$chainId:0x022c0c42a80bd19EA4cF0F94c4F9F96645759716" } -// val approveParams: WalletConnect.Params.Approve = WalletConnect.Params.Approve(sessionProposal, accounts) -// -// AuthClient.approveSession(approveParams) -// } -// -// override fun onSessionRequest(sessionRequest: WalletConnect.Model.SessionRequest) {} -// override fun onSessionDelete(deletedSession: WalletConnect.Model.DeletedSession) {} -// override fun onSessionEvent(sessionEvent: WalletConnect.Model.SessionEvent) {} -// override fun onPairingSettledResponse(response: WalletConnect.Model.SettledPairingResponse) { -// Logger.log("Pairing settle response: $response") -// } -// -// override fun onSessionSettleResponse(response: WalletConnect.Model.SettledSessionResponse) { -// Logger.log("Session settle response: $response") -// assert(true) -// activityRule.close() -// } -// -// override fun onSessionUpgradeResponse(response: WalletConnect.Model.SessionUpgradeResponse) {} -// override fun onSessionUpdateAccountsResponse(response: WalletConnect.Model.SessionUpdateAccountsResponse) {} -// } -// -// AuthClient.setWalletDelegate(listener) -// AuthClient.pair(pairingParams) -// } -// } -// -// @Test -// fun responderUpgradeSessionPermissionsTest() { -// activityRule.launch { -// val initParams = WalletConnect.Params.Init( -// application = app, -// useTls = true, -// hostName = "relay.walletconnect.org", -// projectId = "2ee94aca5d98e6c05c38bce02bee952a", -// metadata = metadata -// ) -// AuthClient.initialize(initParams) -// -// val uri = -// "wc:a26b323e1ad907d7c68264dbf9d5ccbd2077adae3195d23d7b052116ffcd4736@2?controller=false&publicKey=b9577a879cb2fea465ff945e409790b5996cc21dab10db48ceda23cfa3baab37&relay=%7B%22protocol%22%3A%22waku%22%7D" -// val pairingParams = WalletConnect.Params.Pair(uri) -// -// val listener = object : AuthClient.WalletDelegate { -// override fun onSessionProposal(sessionProposal: WalletConnect.Model.SessionProposal) { -// assert(true) -// -// val accounts = sessionProposal.chains.map { chainId -> "$chainId:0x022c0c42a80bd19EA4cF0F94c4F9F96645759716" } -// val approveParams: WalletConnect.Params.Approve = WalletConnect.Params.Approve(sessionProposal, accounts) -// -// AuthClient.approveSession(approveParams) -// } -// -// override fun onSessionRequest(sessionRequest: WalletConnect.Model.SessionRequest) {} -// override fun onSessionDelete(deletedSession: WalletConnect.Model.DeletedSession) {} -// override fun onSessionEvent(sessionEvent: WalletConnect.Model.SessionEvent) {} -// override fun onPairingSettledResponse(response: WalletConnect.Model.SettledPairingResponse) { -// Logger.log("Pairing settle response: $response") -// } -// -// override fun onSessionSettleResponse(response: WalletConnect.Model.SettledSessionResponse) { -// Logger.log("Session settle response: $response") -// -// if (response is WalletConnect.Model.SettledSessionResponse.Result) { -// val permissions = WalletConnect.Model.SessionPermissions( -// blockchain = WalletConnect.Model.Blockchain(chains = listOf("eip155:80001")), -// methods = WalletConnect.Model.JsonRpc(listOf("eth_sign")) -// ) -// val upgradeParams = WalletConnect.Params.Upgrade(response.session.topic, permissions) -// -// AuthClient.upgrade(upgradeParams) -// } -// } -// -// override fun onSessionUpgradeResponse(response: WalletConnect.Model.SessionUpgradeResponse) { -// Logger.log("Session upgrade response: $response") -// if (response is WalletConnect.Model.SessionUpgradeResponse.Result) { -// assert(true) -// activityRule.close() -// } -// } -// -// override fun onSessionUpdateAccountsResponse(response: WalletConnect.Model.SessionUpdateAccountsResponse) {} -// -// } -// -// AuthClient.setWalletDelegate(listener) -// AuthClient.pair(pairingParams) -// } -// } -// -// @Test -// fun responderAcceptRequestAndSendResponseTest() { -// activityRule.launch { -// val initParams = WalletConnect.Params.Init( -// application = app, -// useTls = true, -// hostName = "relay.walletconnect.org", -// projectId = "2ee94aca5d98e6c05c38bce02bee952a", -// metadata = metadata -// ) -// AuthClient.initialize(initParams) -// -// val uri = -// "wc:a436606363ab68232f14d46899397d2d765488a1d5b599922a5e11f3826b44eb@2?controller=false&publicKey=6868953b0b4fdbf203902dd2ea2c982a106c5656879b18df815343fe5e609a6d&relay=%7B%22protocol%22%3A%22waku%22%7D" -// val pairingParams = WalletConnect.Params.Pair(uri) -// -// val listener = object : AuthClient.WalletDelegate { -// -// override fun onSessionProposal(sessionProposal: WalletConnect.Model.SessionProposal) { -// assert(true) -// val accounts = sessionProposal.chains.map { chainId -> "$chainId:0xa0A6c118b1B25207A8A764E1CAe1635339bedE62" } -// val approveParams: WalletConnect.Params.Approve = WalletConnect.Params.Approve(sessionProposal, accounts) -// -// AuthClient.approveSession(approveParams) -// } -// -// override fun onSessionRequest(sessionRequest: WalletConnect.Model.SessionRequest) { -// val result = WalletConnect.Params.Response( -// sessionTopic = sessionRequest.topic, -// jsonRpcResponse = WalletConnect.Model.JsonRpcResponse.JsonRpcResult( -// sessionRequest.request.id, -// "0xa3f20717a250c2b0b729b7e5becbff67fdaef7e0699da4de7ca5895b02a170a12d887fd3b17bfdce3481f10bea41f45ba9f709d39ce8325427b57afcfc994cee1b" -// ) -// ) -// -// AuthClient.respond(result) -// -// } -// -// override fun onSessionDelete(deletedSession: WalletConnect.Model.DeletedSession) {} -// override fun onSessionEvent(sessionEvent: WalletConnect.Model.SessionEvent) {} -// override fun onPairingSettledResponse(response: WalletConnect.Model.SettledPairingResponse) { -// Logger.log("Pairing settle response: $response") -// } -// -// override fun onSessionSettleResponse(response: WalletConnect.Model.SettledSessionResponse) { -// Logger.log("Session settle response: $response") -// } -// -// override fun onSessionUpgradeResponse(response: WalletConnect.Model.SessionUpgradeResponse) {} -// override fun onSessionUpdateAccountsResponse(response: WalletConnect.Model.SessionUpdateAccountsResponse) {} -// } -// -// AuthClient.setWalletDelegate(listener) -// AuthClient.pair(pairingParams) -// } -// } -// -// @Test -// fun responderAcceptRequestAndSendErrorTest() { -// activityRule.launch { -// val initParams = WalletConnect.Params.Init( -// application = app, -// useTls = true, -// hostName = "relay.walletconnect.org", -// projectId = "2ee94aca5d98e6c05c38bce02bee952a", -// metadata = metadata -// ) -// AuthClient.initialize(initParams) -// -// val uri = -// "wc:5435739a2365dd46bbbb2543abbad1964bb702f622428f63d0d4257ddd7df7b7@2?controller=false&publicKey=76464aa17766b58a335e8ee6a96d8be7e1bbfcd81307c57e81b0b6cd54639765&relay=%7B%22protocol%22%3A%22waku%22%7D" -// val pairingParams = WalletConnect.Params.Pair(uri) -// -// -// val listener = object : AuthClient.WalletDelegate { -// override fun onSessionProposal(sessionProposal: WalletConnect.Model.SessionProposal) { -// assert(true) -// val accounts = sessionProposal.chains.map { chainId -> "$chainId:0xa0A6c118b1B25207A8A764E1CAe1635339bedE62" } -// val approveParams: WalletConnect.Params.Approve = WalletConnect.Params.Approve(sessionProposal, accounts) -// -// AuthClient.approveSession(approveParams) -// } -// -// override fun onSessionRequest(sessionRequest: WalletConnect.Model.SessionRequest) { -// val result = WalletConnect.Params.Response( -// sessionTopic = sessionRequest.topic, -// jsonRpcResponse = WalletConnect.Model.JsonRpcResponse.JsonRpcError( -// id = sessionRequest.request.id, -// code = 500, -// message = "Kotlin Wallet Error" -// ) -// ) -// -// AuthClient.respond(result) -// } -// -// override fun onSessionDelete(deletedSession: WalletConnect.Model.DeletedSession) {} -// override fun onSessionEvent(sessionEvent: WalletConnect.Model.SessionEvent) {} -// override fun onPairingSettledResponse(response: WalletConnect.Model.SettledPairingResponse) { -// Logger.log("Pairing settle response: $response") -// } -// -// override fun onSessionSettleResponse(response: WalletConnect.Model.SettledSessionResponse) { -// Logger.log("Session settle response: $response") -// } -// -// override fun onSessionUpgradeResponse(response: WalletConnect.Model.SessionUpgradeResponse) {} -// override fun onSessionUpdateAccountsResponse(response: WalletConnect.Model.SessionUpdateAccountsResponse) {} -// } -// -// AuthClient.setWalletDelegate(listener) -// AuthClient.pair(pairingParams) -// } -// } -// -// @Test -// fun responderSessionUpdateTest() { -// activityRule.launch { -// val initParams = WalletConnect.Params.Init( -// application = app, -// useTls = true, -// hostName = "relay.walletconnect.org", -// projectId = "2ee94aca5d98e6c05c38bce02bee952a", -// metadata = metadata -// ) -// AuthClient.initialize(initParams) -// -// val uri = -// "wc:7518ca65d85b3084d3b5f5fb223a7cd902c8bb5faca80fbe3e4f74f936eecd20@2?controller=false&publicKey=55fa723c020e8b3d3f7cc01c0d7f7eaf246fce2203e8f2f32580f2d947312a09&relay=%7B%22protocol%22%3A%22waku%22%7D" -// val pairingParams = WalletConnect.Params.Pair(uri) -// -// val listener = object : AuthClient.WalletDelegate { -// override fun onSessionProposal(sessionProposal: WalletConnect.Model.SessionProposal) { -// assert(true) -// val accounts = sessionProposal.chains.map { chainId -> "$chainId:0xa0A6c118b1B25207A8A764E1CAe1635339bedE62" } -// val approveParams: WalletConnect.Params.Approve = WalletConnect.Params.Approve(sessionProposal, accounts) -// -// AuthClient.approveSession(approveParams) -// } -// -// override fun onSessionRequest(sessionRequest: WalletConnect.Model.SessionRequest) {} -// override fun onSessionDelete(deletedSession: WalletConnect.Model.DeletedSession) {} -// override fun onSessionEvent(sessionEvent: WalletConnect.Model.SessionEvent) {} -// -// override fun onPairingSettledResponse(response: WalletConnect.Model.SettledPairingResponse) { -// Logger.log("Pairing settle response: $response") -// } -// -// override fun onSessionSettleResponse(response: WalletConnect.Model.SettledSessionResponse) { -// Logger.log("Session settle response: $response") -// -// if (response is WalletConnect.Model.SettledSessionResponse.Result) { -// -// val updateParams = WalletConnect.Params.UpdateAccounts( -// response.session.topic, -// WalletConnect.Model.SessionState(accounts = listOf("eip155:8001:0x022c0c42a80bd19EA4cF0F94c4F9F96645759716")) -// ) -// -//// WalletConnectClient.updateAccounts(updateParams) -// } -// } -// -// override fun onSessionUpgradeResponse(response: WalletConnect.Model.SessionUpgradeResponse) {} -// override fun onSessionUpdateAccountsResponse(response: WalletConnect.Model.SessionUpdateAccountsResponse) { -// if (response is WalletConnect.Model.SessionUpdateAccountsResponse.Result) { -// assert(true) -// activityRule.close() -// } else { -// assert(false) -// activityRule.close() -// } -// } -// } -// -// AuthClient.setWalletDelegate(listener) -// AuthClient.pair(pairingParams) -// } -// } -// -// @Test -// fun responderSendSessionPingTest() { -// activityRule.launch { -// val initParams = WalletConnect.Params.Init( -// application = app, -// useTls = true, -// hostName = "relay.walletconnect.org", -// projectId = "2ee94aca5d98e6c05c38bce02bee952a", -// metadata = metadata -// ) -// AuthClient.initialize(initParams) -// -// val uri = -// "wc:776558f58c4a41273d6a7dee4404eb58bed4b42949370e06680992f4916ca600@2?controller=false&publicKey=fe0ae6439d3b3fa8aaf6e478bd3e6d4528ec21cb595bb73f6c9c62b1e5135b23&relay=%7B%22protocol%22%3A%22waku%22%7D" -// val pairingParams = WalletConnect.Params.Pair(uri) -// -// val listener = object : AuthClient.WalletDelegate { -// override fun onSessionProposal(sessionProposal: WalletConnect.Model.SessionProposal) { -// assert(true) -// val accounts = sessionProposal.chains.map { chainId -> "$chainId:0xa0A6c118b1B25207A8A764E1CAe1635339bedE62" } -// val approveParams: WalletConnect.Params.Approve = WalletConnect.Params.Approve(sessionProposal, accounts) -// -// AuthClient.approveSession(approveParams) -// } -// -// override fun onSessionRequest(sessionRequest: WalletConnect.Model.SessionRequest) {} -// override fun onSessionDelete(deletedSession: WalletConnect.Model.DeletedSession) {} -// override fun onSessionEvent(sessionEvent: WalletConnect.Model.SessionEvent) {} -// -// override fun onPairingSettledResponse(response: WalletConnect.Model.SettledPairingResponse) { -// Logger.log("Pairing settle response: $response") -// } -// -// override fun onSessionSettleResponse(response: WalletConnect.Model.SettledSessionResponse) { -// Logger.log("Session settle response: $response") -// -// if (response is WalletConnect.Model.SettledSessionResponse.Result) { -// val pingParams = WalletConnect.Params.Ping(response.session.topic) -// -// AuthClient.ping(pingParams, object : WalletConnect.Listeners.SessionPing { -// override fun onSuccess(topic: String) { -// assert(true) -// activityRule.close() -// } -// -// override fun onError(error: Throwable) { -// assert(false) -// activityRule.close() -// } -// }) -// } -// } -// -// override fun onSessionUpgradeResponse(response: WalletConnect.Model.SessionUpgradeResponse) {} -// override fun onSessionUpdateAccountsResponse(response: WalletConnect.Model.SessionUpdateAccountsResponse) {} -// } -// -// AuthClient.setWalletDelegate(listener) -// AuthClient.pair(pairingParams) -// } -// } -// -// @Test -// fun responderSendNotificationTest() { -// activityRule.launch { -// val initParams = WalletConnect.Params.Init( -// application = app, -// useTls = true, -// hostName = "relay.walletconnect.org", -// projectId = "2ee94aca5d98e6c05c38bce02bee952a", -// metadata = metadata -// ) -// AuthClient.initialize(initParams) -// -// -// val uri = -// "wc:8d45a8b64d4b921ee8608053ebbbea7a52d8c59ded79f379a868f524c868789f@2?controller=false&publicKey=8d18b02dbbd8c29133255a847061af36a7673ebdcdbf0a05aaac3a3ef7391703&relay=%7B%22protocol%22%3A%22waku%22%7D" -// val pairingParams = WalletConnect.Params.Pair(uri) -// -// val listener = object : AuthClient.WalletDelegate { -// override fun onSessionProposal(sessionProposal: WalletConnect.Model.SessionProposal) { -// assert(true) -// val accounts = sessionProposal.chains.map { chainId -> "$chainId:0xa0A6c118b1B25207A8A764E1CAe1635339bedE62" } -// val approveParams: WalletConnect.Params.Approve = WalletConnect.Params.Approve(sessionProposal, accounts) -// -// AuthClient.approveSession(approveParams) -// } -// -// override fun onSessionRequest(sessionRequest: WalletConnect.Model.SessionRequest) {} -// override fun onSessionDelete(deletedSession: WalletConnect.Model.DeletedSession) {} -// override fun onSessionEvent(sessionEvent: WalletConnect.Model.SessionEvent) {} -// -// override fun onPairingSettledResponse(response: WalletConnect.Model.SettledPairingResponse) { -// Logger.log("Pairing settle response: $response") -// } -// -// override fun onSessionSettleResponse(response: WalletConnect.Model.SettledSessionResponse) { -// Logger.log("Session settle response: $response") -// -// if (response is WalletConnect.Model.SettledSessionResponse.Result) { -// val notificationParams = WalletConnect.Params.Emit( -// response.session.topic, -// WalletConnect.Model.SessionEvent("type", "test") -// ) -// -// AuthClient.emit(notificationParams) -// } -// } -// -// override fun onSessionUpgradeResponse(response: WalletConnect.Model.SessionUpgradeResponse) {} -// override fun onSessionUpdateAccountsResponse(response: WalletConnect.Model.SessionUpdateAccountsResponse) {} -// } -// -// AuthClient.setWalletDelegate(listener) -// AuthClient.pair(pairingParams) -// } -// } -// -// @Test -// fun responderSessionExtendTest() { -// activityRule.launch { -// val initParams = WalletConnect.Params.Init( -// application = app, -// useTls = true, -// hostName = "relay.walletconnect.org", -// projectId = "2ee94aca5d98e6c05c38bce02bee952a", -// metadata = metadata -// ) -// AuthClient.initialize(initParams) -// -// val uri = -// "wc:d948c3ca8b323d9711fd304ba285a1835d91d5c71ea70e5a894597dadf7322e4@2?controller=false&publicKey=e28a8553a79655d6a350ff2099b95913831d7ee671ef540af706d4eb9d2d6949&relay=%7B%22protocol%22%3A%22waku%22%7D" -// val pairingParams = WalletConnect.Params.Pair(uri) -// -// val listener = object : AuthClient.WalletDelegate { -// override fun onSessionProposal(sessionProposal: WalletConnect.Model.SessionProposal) { -// assert(true) -// val accounts = sessionProposal.chains.map { chainId -> "$chainId:0xa0A6c118b1B25207A8A764E1CAe1635339bedE62" } -// val approveParams: WalletConnect.Params.Approve = WalletConnect.Params.Approve(sessionProposal, accounts) -// -// AuthClient.approveSession(approveParams) -// } -// -// override fun onSessionRequest(sessionRequest: WalletConnect.Model.SessionRequest) {} -// override fun onSessionDelete(deletedSession: WalletConnect.Model.DeletedSession) {} -// override fun onSessionEvent(sessionEvent: WalletConnect.Model.SessionEvent) {} -// -// override fun onPairingSettledResponse(response: WalletConnect.Model.SettledPairingResponse) { -// Logger.log("Pairing settle response: $response") -// } -// -// override fun onSessionSettleResponse(response: WalletConnect.Model.SettledSessionResponse) { -// Logger.log("Session settle response: $response") -// -// if (response is WalletConnect.Model.SettledSessionResponse.Result) { -// -// val extend = WalletConnect.Params.Extend(response.session.topic, 1646901496) -// AuthClient.updateExpiry(extend) -// } -// } -// -// override fun onSessionUpgradeResponse(response: WalletConnect.Model.SessionUpgradeResponse) {} -// override fun onSessionUpdateAccountsResponse(response: WalletConnect.Model.SessionUpdateAccountsResponse) {} -// } -// -// AuthClient.setWalletDelegate(listener) -// AuthClient.pair(pairingParams) -// } -// } -} \ No newline at end of file diff --git a/signSDK/sign/src/debug/kotlin/com/walletconnect/sign/di/StorageModule.kt b/signSDK/sign/src/debug/kotlin/com/walletconnect/sign/di/StorageModule.kt index 557d7b4d6b..60fc16ed83 100644 --- a/signSDK/sign/src/debug/kotlin/com/walletconnect/sign/di/StorageModule.kt +++ b/signSDK/sign/src/debug/kotlin/com/walletconnect/sign/di/StorageModule.kt @@ -3,21 +3,9 @@ package com.walletconnect.sign.di import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences -import com.squareup.sqldelight.ColumnAdapter -import com.squareup.sqldelight.EnumColumnAdapter import com.squareup.sqldelight.android.AndroidSqliteDriver import com.squareup.sqldelight.db.SqlDriver import com.walletconnect.sign.Database -import com.walletconnect.sign.core.model.type.enums.MetaDataType -import com.walletconnect.sign.storage.data.dao.metadata.MetaDataDao -import com.walletconnect.sign.storage.data.dao.namespace.NamespaceDao -import com.walletconnect.sign.storage.data.dao.namespace.NamespaceExtensionsDao -import com.walletconnect.sign.storage.data.dao.proposalnamespace.ProposalNamespaceDao -import com.walletconnect.sign.storage.data.dao.proposalnamespace.ProposalNamespaceExtensionsDao -import com.walletconnect.sign.storage.data.dao.temp.TempNamespaceDao -import com.walletconnect.sign.storage.data.dao.temp.TempNamespaceExtensionsDao -import com.walletconnect.sign.storage.history.JsonRpcHistory -import com.walletconnect.sign.storage.sequence.SequenceStorageRepository import org.koin.android.ext.koin.androidContext import org.koin.core.module.Module import org.koin.core.qualifier.named @@ -33,24 +21,6 @@ internal fun storageModule(): Module = module { androidContext().getSharedPreferences(sharedPrefsFile, Context.MODE_PRIVATE) } - single, String>> { - object : ColumnAdapter, String> { - - override fun decode(databaseValue: String) = - if (databaseValue.isBlank()) { - listOf() - } else { - databaseValue.split(",") - } - - override fun encode(value: List) = value.joinToString(separator = ",") - } - } - - single>(named("MetaDataType")) { - EnumColumnAdapter() - } - single { AndroidSqliteDriver( schema = Database.Schema, @@ -59,91 +29,5 @@ internal fun storageModule(): Module = module { ) } - single { - Database( - get(), - MetaDataDaoAdapter = MetaDataDao.Adapter( - iconsAdapter = get(), - typeAdapter = get(named("MetaDataType")) - ), - NamespaceDaoAdapter = NamespaceDao.Adapter( - accountsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ), - NamespaceExtensionsDaoAdapter = NamespaceExtensionsDao.Adapter( - accountsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ), - TempNamespaceDaoAdapter = TempNamespaceDao.Adapter( - accountsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ), - TempNamespaceExtensionsDaoAdapter = TempNamespaceExtensionsDao.Adapter( - accountsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ), - ProposalNamespaceDaoAdapter = ProposalNamespaceDao.Adapter( - chainsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ), - ProposalNamespaceExtensionsDaoAdapter = ProposalNamespaceExtensionsDao.Adapter( - chainsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ) - ) - } - - single { - get().pairingDaoQueries - } - - single { - get().sessionDaoQueries - } - - single { - get().metaDataDaoQueries - } - - single { - get().jsonRpcHistoryQueries - } - - single { - get().namespaceDaoQueries - } - - single { - get().namespaceExtensionDaoQueries - } - - single { - get().tempNamespaceDaoQueries - } - - single { - get().tempNamespaceExtensionDaoQueries - } - - single { - get().proposalNamespaceDaoQueries - } - - single { - get().proposalNamespaceExtensionDaoQueries - } - - single { - SequenceStorageRepository(get(), get(), get(), get(), get(), get(), get(), get(), get()) - } - - single { - JsonRpcHistory(get(named(DITags.RPC_STORE)), get()) - } + includes(sharedStorageModule()) } \ No newline at end of file diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt index 5e3a16322b..d2cb84b016 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt @@ -53,7 +53,10 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { val jwtRepository = wcKoinApp.koin.get() val jwt = jwtRepository.generateJWT(initial.relayServerUrl.strippedUrl()) - wcKoinApp.modules(scarletModule(initial.relayServerUrl.addUserAgent(), jwt, initial.connectionType.toRelayConnectionType(), initial.relay)) + wcKoinApp.modules(scarletModule(initial.relayServerUrl.addUserAgent(), + jwt, + initial.connectionType.toRelayConnectionType(), + initial.relay)) signEngine = wcKoinApp.koin.get() signEngine.handleInitializationErrors { error -> onError(Sign.Model.Error(error)) } } @@ -279,6 +282,14 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { } } + fun blockUntilInitialized() { + runBlocking(signProtocolScope.coroutineContext) { + mutex.withLock { + checkEngineInitialization() + } + } + } + @Throws(IllegalStateException::class) private fun checkEngineInitialization() { check(::signEngine.isInitialized) { diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/di/SharedStorageModule.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/di/SharedStorageModule.kt new file mode 100644 index 0000000000..59f93bb676 --- /dev/null +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/di/SharedStorageModule.kt @@ -0,0 +1,129 @@ +package com.walletconnect.sign.di + +import com.squareup.sqldelight.ColumnAdapter +import com.squareup.sqldelight.EnumColumnAdapter +import com.walletconnect.sign.Database +import com.walletconnect.sign.core.model.type.enums.MetaDataType +import com.walletconnect.sign.storage.data.dao.metadata.MetaDataDao +import com.walletconnect.sign.storage.data.dao.namespace.NamespaceDao +import com.walletconnect.sign.storage.data.dao.namespace.NamespaceExtensionsDao +import com.walletconnect.sign.storage.data.dao.proposalnamespace.ProposalNamespaceDao +import com.walletconnect.sign.storage.data.dao.proposalnamespace.ProposalNamespaceExtensionsDao +import com.walletconnect.sign.storage.data.dao.temp.TempNamespaceDao +import com.walletconnect.sign.storage.data.dao.temp.TempNamespaceExtensionsDao +import com.walletconnect.sign.storage.history.JsonRpcHistory +import com.walletconnect.sign.storage.sequence.SequenceStorageRepository +import org.koin.core.module.Module +import org.koin.core.qualifier.named +import org.koin.dsl.module + + +@JvmSynthetic +internal fun sharedStorageModule(): Module = module { + + single, String>> { + object : ColumnAdapter, String> { + + override fun decode(databaseValue: String) = + if (databaseValue.isBlank()) { + listOf() + } else { + databaseValue.split(",") + } + + override fun encode(value: List) = value.joinToString(separator = ",") + } + } + + single>(named("MetaDataType")) { + EnumColumnAdapter() + } + + single { + Database( + get(), + MetaDataDaoAdapter = MetaDataDao.Adapter( + iconsAdapter = get(), + typeAdapter = get(named("MetaDataType")) + ), + NamespaceDaoAdapter = NamespaceDao.Adapter( + accountsAdapter = get(), + methodsAdapter = get(), + eventsAdapter = get() + ), + NamespaceExtensionsDaoAdapter = NamespaceExtensionsDao.Adapter( + accountsAdapter = get(), + methodsAdapter = get(), + eventsAdapter = get() + ), + TempNamespaceDaoAdapter = TempNamespaceDao.Adapter( + accountsAdapter = get(), + methodsAdapter = get(), + eventsAdapter = get() + ), + TempNamespaceExtensionsDaoAdapter = TempNamespaceExtensionsDao.Adapter( + accountsAdapter = get(), + methodsAdapter = get(), + eventsAdapter = get() + ), + ProposalNamespaceDaoAdapter = ProposalNamespaceDao.Adapter( + chainsAdapter = get(), + methodsAdapter = get(), + eventsAdapter = get() + ), + ProposalNamespaceExtensionsDaoAdapter = ProposalNamespaceExtensionsDao.Adapter( + chainsAdapter = get(), + methodsAdapter = get(), + eventsAdapter = get() + ) + ) + } + + single { + get().pairingDaoQueries + } + + single { + get().sessionDaoQueries + } + + single { + get().metaDataDaoQueries + } + + single { + get().jsonRpcHistoryQueries + } + + single { + get().namespaceDaoQueries + } + + single { + get().namespaceExtensionDaoQueries + } + + single { + get().tempNamespaceDaoQueries + } + + single { + get().tempNamespaceExtensionDaoQueries + } + + single { + get().proposalNamespaceDaoQueries + } + + single { + get().proposalNamespaceExtensionDaoQueries + } + + single { + SequenceStorageRepository(get(), get(), get(), get(), get(), get(), get(), get(), get()) + } + + single { + JsonRpcHistory(get(named(DITags.RPC_STORE)), get()) + } +} diff --git a/signSDK/sign/src/qa/kotlin/com/walletconnect/sign/di/DITags.kt b/signSDK/sign/src/qa/kotlin/com/walletconnect/sign/di/DITags.kt new file mode 100644 index 0000000000..ad919b7e4e --- /dev/null +++ b/signSDK/sign/src/qa/kotlin/com/walletconnect/sign/di/DITags.kt @@ -0,0 +1,6 @@ +package com.walletconnect.sign.di + +internal enum class DITags { + @JvmSynthetic KEY_STORE, + @JvmSynthetic RPC_STORE +} \ No newline at end of file diff --git a/signSDK/sign/src/qa/kotlin/com/walletconnect/sign/di/StorageModule.kt b/signSDK/sign/src/qa/kotlin/com/walletconnect/sign/di/StorageModule.kt new file mode 100644 index 0000000000..c885779bdd --- /dev/null +++ b/signSDK/sign/src/qa/kotlin/com/walletconnect/sign/di/StorageModule.kt @@ -0,0 +1,34 @@ +package com.walletconnect.sign.di + +import android.annotation.SuppressLint +import android.content.Context +import android.content.SharedPreferences +import com.squareup.sqldelight.android.AndroidSqliteDriver +import com.squareup.sqldelight.db.SqlDriver +import com.walletconnect.sign.Database +import org.koin.android.ext.koin.androidContext +import org.koin.core.module.Module +import org.koin.core.qualifier.named +import org.koin.dsl.module +import kotlin.random.Random + +@SuppressLint("HardwareIds") +@JvmSynthetic +internal fun storageModule(): Module = module { + + single(named(DITags.RPC_STORE)) { + val sharedPrefsFile = "wc_rpc_store" + + androidContext().getSharedPreferences(sharedPrefsFile, Context.MODE_PRIVATE) + } + + single { + AndroidSqliteDriver( + schema = Database.Schema, + context = androidContext(), + name = "WalletConnectV2${Random.nextInt()}.db" + ) + } + + includes(sharedStorageModule()) +} \ No newline at end of file diff --git a/signSDK/sign/src/release/kotlin/com.walletconnect.sign/di/StorageModule.kt b/signSDK/sign/src/release/kotlin/com.walletconnect.sign/di/StorageModule.kt index a08f8ff90e..21ec15b11c 100644 --- a/signSDK/sign/src/release/kotlin/com.walletconnect.sign/di/StorageModule.kt +++ b/signSDK/sign/src/release/kotlin/com.walletconnect.sign/di/StorageModule.kt @@ -7,21 +7,9 @@ import android.security.keystore.KeyProperties import android.util.Base64 import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKeys -import com.squareup.sqldelight.ColumnAdapter -import com.squareup.sqldelight.EnumColumnAdapter import com.squareup.sqldelight.android.AndroidSqliteDriver import com.squareup.sqldelight.db.SqlDriver import com.walletconnect.sign.Database -import com.walletconnect.sign.core.model.type.enums.MetaDataType -import com.walletconnect.sign.storage.data.dao.metadata.MetaDataDao -import com.walletconnect.sign.storage.data.dao.namespace.NamespaceDao -import com.walletconnect.sign.storage.data.dao.namespace.NamespaceExtensionsDao -import com.walletconnect.sign.storage.data.dao.proposalnamespace.ProposalNamespaceDao -import com.walletconnect.sign.storage.data.dao.proposalnamespace.ProposalNamespaceExtensionsDao -import com.walletconnect.sign.storage.data.dao.temp.TempNamespaceDao -import com.walletconnect.sign.storage.data.dao.temp.TempNamespaceExtensionsDao -import com.walletconnect.sign.storage.history.JsonRpcHistory -import com.walletconnect.sign.storage.sequence.SequenceStorageRepository import com.walletconnect.sign.util.randomBytes import net.sqlcipher.database.SupportFactory import org.koin.android.ext.koin.androidContext @@ -57,23 +45,6 @@ internal fun storageModule(): Module = module { ) } - single, String>> { - object : ColumnAdapter, String> { - - override fun decode(databaseValue: String) = - if (databaseValue.isEmpty()) { - listOf() - } else { - databaseValue.split(",") - } - - override fun encode(value: List) = value.joinToString(separator = ",") - } - } - - single>(named("MetaDataType")) { - EnumColumnAdapter() - } single { KeyStore.getInstance("AndroidKeyStore").apply { @@ -186,93 +157,7 @@ internal fun storageModule(): Module = module { ) } - single { - Database( - get(), - MetaDataDaoAdapter = MetaDataDao.Adapter( - iconsAdapter = get(), - typeAdapter = get(named("MetaDataType")) - ), - NamespaceDaoAdapter = NamespaceDao.Adapter( - accountsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ), - NamespaceExtensionsDaoAdapter = NamespaceExtensionsDao.Adapter( - accountsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ), - TempNamespaceDaoAdapter = TempNamespaceDao.Adapter( - accountsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ), - TempNamespaceExtensionsDaoAdapter = TempNamespaceExtensionsDao.Adapter( - accountsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ), - ProposalNamespaceDaoAdapter = ProposalNamespaceDao.Adapter( - chainsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ), - ProposalNamespaceExtensionsDaoAdapter = ProposalNamespaceExtensionsDao.Adapter( - chainsAdapter = get(), - methodsAdapter = get(), - eventsAdapter = get() - ) - ) - } - - single { - get().pairingDaoQueries - } - - single { - get().sessionDaoQueries - } - - single { - get().metaDataDaoQueries - } - - single { - get().jsonRpcHistoryQueries - } - - single { - get().namespaceDaoQueries - } - - single { - get().namespaceExtensionDaoQueries - } - - single { - get().tempNamespaceDaoQueries - } - - single { - get().tempNamespaceExtensionDaoQueries - } - - single { - get().proposalNamespaceDaoQueries - } - - single { - get().proposalNamespaceExtensionDaoQueries - } - - single { - SequenceStorageRepository(get(), get(), get(), get(), get(), get(), get(), get(), get()) - } - - single { - JsonRpcHistory(get(named(DITags.RPC_STORE)), get()) - } + includes(sharedStorageModule()) } private fun encode(decodedData: ByteArray): String = Base64.encodeToString(decodedData, Base64.NO_WRAP) From 19a6585275e476eea6cea0bb96265cf495c62c19 Mon Sep 17 00:00:00 2001 From: szymon Date: Fri, 5 Aug 2022 14:38:26 +0200 Subject: [PATCH 13/21] feat: Add GHA --- .github/workflows/ci_relay.yml | 41 ++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 .github/workflows/ci_relay.yml diff --git a/.github/workflows/ci_relay.yml b/.github/workflows/ci_relay.yml new file mode 100644 index 0000000000..9fc10c6aed --- /dev/null +++ b/.github/workflows/ci_relay.yml @@ -0,0 +1,41 @@ +name: Relay Integration + +on: + push: + branches: + - feature/sign/instrumented_tests + pull_request: + branches: + - feature/sign/instrumented_tests + +concurrency: + # Support push/pr as event types with different behaviors each: + # 1. push: queue up builds by branch + # 2. pr: only allow one run per PR + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.ref_name }} + # If there is already a workflow running for the same pull request, cancel it + # For non-PR triggers queue up builds + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + validate: + runs-on: macos-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Java JDK + uses: actions/setup-java@v3.3.0 + with: + distribution: 'zulu' + java-version: '11' + architecture: x86_64 + - name: Instrumentation tests + env: + TEST_RELAY_URL: wss://relay.walletconnect.com + TEST_PROJECT_ID: 2ee94aca5d98e6c05c38bce02bee952a + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: 32 + arch: x86_64 + target: google_apis + script: ./gradlew :sign:connectedCheck \ No newline at end of file From 7c8edb98c179a85edfbc9744c18c6bcf9b9eed4c Mon Sep 17 00:00:00 2001 From: szymon Date: Fri, 5 Aug 2022 15:43:23 +0200 Subject: [PATCH 14/21] feat: Change locking mechanism for instrumented tests --- .../test/utils/WCIntegrationActivityScenarioRule.kt | 9 +++++++++ .../com/walletconnect/sign/client/SignProtocol.kt | 13 +++---------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/WCIntegrationActivityScenarioRule.kt b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/WCIntegrationActivityScenarioRule.kt index f5595d9142..47f87f5027 100644 --- a/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/WCIntegrationActivityScenarioRule.kt +++ b/signSDK/sign/src/androidTest/kotlin/com/walletconnect/sign/test/utils/WCIntegrationActivityScenarioRule.kt @@ -12,6 +12,7 @@ import com.walletconnect.sign.core.scope.scope import com.walletconnect.sign.util.Logger import kotlinx.coroutines.* import kotlinx.coroutines.flow.* +import kotlinx.coroutines.sync.withLock import org.junit.Assert import org.junit.jupiter.api.Assertions.assertTrue import org.junit.rules.ExternalResource @@ -77,6 +78,14 @@ class WCIntegrationActivityScenarioRule : ExternalResource() { relay.connect { } } + private fun SignProtocol.blockUntilInitialized() { + runBlocking(signProtocolScope.coroutineContext) { + mutex.withLock { + checkEngineInitialization() + } + } + } + override fun before() { runBlocking { val isDappReady = MutableStateFlow(false) diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt index d2cb84b016..79cbe0f6a0 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt @@ -23,8 +23,8 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { private val wcKoinApp: KoinApplication = KoinApplication.init() private lateinit var signEngine: SignEngine override val relay: RelayInterface by lazy { wcKoinApp.koin.get() } - private val mutex = Mutex() - private val signProtocolScope = + val mutex = Mutex() + val signProtocolScope = CoroutineScope(SupervisorJob() + Executors.newSingleThreadExecutor().asCoroutineDispatcher()) companion object { @@ -282,16 +282,9 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { } } - fun blockUntilInitialized() { - runBlocking(signProtocolScope.coroutineContext) { - mutex.withLock { - checkEngineInitialization() - } - } - } @Throws(IllegalStateException::class) - private fun checkEngineInitialization() { + fun checkEngineInitialization() { check(::signEngine.isInitialized) { "SignClient needs to be initialized first using the initialize function" } From ca6f100b70946eb0438a0ac557866fe7c909be43 Mon Sep 17 00:00:00 2001 From: szymon Date: Fri, 5 Aug 2022 15:57:30 +0200 Subject: [PATCH 15/21] docs: Add note to GHA --- .github/workflows/ci_relay.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/ci_relay.yml b/.github/workflows/ci_relay.yml index 9fc10c6aed..a30961ebd3 100644 --- a/.github/workflows/ci_relay.yml +++ b/.github/workflows/ci_relay.yml @@ -1,5 +1,7 @@ name: Relay Integration + +# IMPORTANT. GHA only for demo purposes. on: push: branches: From cf1c3dd2c08bc92f2dd76e66ca2c2d0612990ab2 Mon Sep 17 00:00:00 2001 From: szymon Date: Tue, 9 Aug 2022 14:02:56 +0200 Subject: [PATCH 16/21] feat: Remove ci_relay from GHA --- .github/workflows/ci_relay.yml | 86 +++++++++++++++++----------------- 1 file changed, 43 insertions(+), 43 deletions(-) diff --git a/.github/workflows/ci_relay.yml b/.github/workflows/ci_relay.yml index a30961ebd3..b7df53a3f5 100644 --- a/.github/workflows/ci_relay.yml +++ b/.github/workflows/ci_relay.yml @@ -1,43 +1,43 @@ -name: Relay Integration - - -# IMPORTANT. GHA only for demo purposes. -on: - push: - branches: - - feature/sign/instrumented_tests - pull_request: - branches: - - feature/sign/instrumented_tests - -concurrency: - # Support push/pr as event types with different behaviors each: - # 1. push: queue up builds by branch - # 2. pr: only allow one run per PR - group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.ref_name }} - # If there is already a workflow running for the same pull request, cancel it - # For non-PR triggers queue up builds - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - validate: - runs-on: macos-latest - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Setup Java JDK - uses: actions/setup-java@v3.3.0 - with: - distribution: 'zulu' - java-version: '11' - architecture: x86_64 - - name: Instrumentation tests - env: - TEST_RELAY_URL: wss://relay.walletconnect.com - TEST_PROJECT_ID: 2ee94aca5d98e6c05c38bce02bee952a - uses: reactivecircus/android-emulator-runner@v2 - with: - api-level: 32 - arch: x86_64 - target: google_apis - script: ./gradlew :sign:connectedCheck \ No newline at end of file +#name: Relay Integration +# +# +## IMPORTANT. GHA only for demo purposes. +#on: +# push: +# branches: +# - feature/sign/instrumented_tests +# pull_request: +# branches: +# - feature/sign/instrumented_tests +# +#concurrency: +# # Support push/pr as event types with different behaviors each: +# # 1. push: queue up builds by branch +# # 2. pr: only allow one run per PR +# group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.ref_name }} +# # If there is already a workflow running for the same pull request, cancel it +# # For non-PR triggers queue up builds +# cancel-in-progress: ${{ github.event_name == 'pull_request' }} +# +#jobs: +# validate: +# runs-on: macos-latest +# steps: +# - name: Checkout +# uses: actions/checkout@v2 +# - name: Setup Java JDK +# uses: actions/setup-java@v3.3.0 +# with: +# distribution: 'zulu' +# java-version: '11' +# architecture: x86_64 +# - name: Instrumentation tests +# env: +# TEST_RELAY_URL: wss://relay.walletconnect.com +# TEST_PROJECT_ID: 2ee94aca5d98e6c05c38bce02bee952a +# uses: reactivecircus/android-emulator-runner@v2 +# with: +# api-level: 32 +# arch: x86_64 +# target: google_apis +# script: ./gradlew :sign:connectedCheck \ No newline at end of file From f9e8918259e5ade908f48c29e0ce23ddfb1f217b Mon Sep 17 00:00:00 2001 From: kubel Date: Wed, 10 Aug 2022 11:17:25 +0200 Subject: [PATCH 17/21] Add getSettledSessionByTopic to SingInterface --- .../SelectedAccountViewModel.kt | 18 +++-- .../com/walletconnect/sign/client/Sign.kt | 47 +++++++++--- .../sign/client/SignInterface.kt | 2 +- .../walletconnect/sign/client/SignProtocol.kt | 54 +++++++++++--- .../host/request/SessionRequestViewModel.kt | 11 ++- .../details/SessionDetailsViewModel.kt | 74 ++++++++++++++----- 6 files changed, 156 insertions(+), 50 deletions(-) diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt index 9780514451..63a886f01f 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt @@ -13,7 +13,8 @@ import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch class SelectedAccountViewModel : ViewModel() { - private val _uiState: MutableStateFlow = MutableStateFlow(SelectedAccountUI.Initial) + private val _uiState: MutableStateFlow = + MutableStateFlow(SelectedAccountUI.Initial) val uiState: StateFlow = _uiState.asStateFlow() private val _event: MutableSharedFlow = MutableSharedFlow() @@ -32,11 +33,13 @@ class SelectedAccountViewModel : ViewModel() { is Sign.Model.SessionRequestResponse -> { val request = when (walletEvent.result) { is Sign.Model.JsonRpcResponse.JsonRpcResult -> { - val successResult = (walletEvent.result as Sign.Model.JsonRpcResponse.JsonRpcResult) + val successResult = + (walletEvent.result as Sign.Model.JsonRpcResponse.JsonRpcResult) SampleDappEvents.RequestSuccess(successResult.result) } is Sign.Model.JsonRpcResponse.JsonRpcError -> { - val errorResult = (walletEvent.result as Sign.Model.JsonRpcResponse.JsonRpcError) + val errorResult = + (walletEvent.result as Sign.Model.JsonRpcResponse.JsonRpcError) SampleDappEvents.RequestPeerError("Error Message: ${errorResult.message}\n Error Code: ${errorResult.code}") } } @@ -71,13 +74,16 @@ class SelectedAccountViewModel : ViewModel() { SignClient.request(requestParams) { viewModelScope.launch { - _event.emit(SampleDappEvents.RequestError(it.throwable.localizedMessage ?: "Error trying to send request")) + _event.emit( + SampleDappEvents.RequestError( + it.throwable.localizedMessage ?: "Error trying to send request" + ) + ) } } val sessionRequestDeepLinkUri = - SignClient.getListOfSettledSessions() - .find { session -> session.topic == requestParams.sessionTopic }?.metaData?.redirect?.toUri() + SignClient.getSettledSessionByTopic(requestParams.sessionTopic)?.redirect?.toUri() ?: "wc:/${requestParams.sessionTopic}/request".toUri() sendSessionRequestDeepLink(sessionRequestDeepLinkUri) diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt index 2414b15dea..7bb80e3caa 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/Sign.kt @@ -61,7 +61,11 @@ object Sign { val extensions: List?, ) : Namespace() { - data class Extension(val chains: List, val methods: List, val events: List) + data class Extension( + val chains: List, + val methods: List, + val events: List + ) } data class Session( @@ -71,7 +75,11 @@ object Sign { val extensions: List?, ) : Namespace() { - data class Extension(val accounts: List, val methods: List, val events: List) + data class Extension( + val accounts: List, + val methods: List, + val events: List + ) } } @@ -85,7 +93,9 @@ object Sign { } sealed class SessionUpdateResponse : Model() { - data class Result(val topic: String, val namespaces: Map) : SessionUpdateResponse() + data class Result(val topic: String, val namespaces: Map) : + SessionUpdateResponse() + data class Error(val errorMessage: String) : SessionUpdateResponse() } @@ -103,7 +113,10 @@ object Sign { data class Blockchain(val chains: List) : Model() - data class UpdatedSession(val topic: String, val namespaces: Map) : Model() + data class UpdatedSession( + val topic: String, + val namespaces: Map + ) : Model() data class ApprovedSession( val topic: String, @@ -117,7 +130,9 @@ object Sign { val expiry: Long, val namespaces: Map, val metaData: AppMetaData?, - ) : Model() + ) : Model() { + val redirect: String? = metaData?.redirect + } data class SessionEvent( val name: String, @@ -217,7 +232,11 @@ object Sign { private fun String.isValidRelayServerUrl(): Boolean { return this.isNotBlank() && Uri.parse(this)?.let { relayUrl -> - arrayOf("wss", "ws").contains(relayUrl.scheme) && !relayUrl.getQueryParameter("projectId").isNullOrBlank() + arrayOf( + "wss", + "ws" + ).contains(relayUrl.scheme) && !relayUrl.getQueryParameter("projectId") + .isNullOrBlank() } ?: false } } @@ -236,13 +255,20 @@ object Sign { val relayProtocol: String? = null, ) : Params() - data class Reject(val proposerPublicKey: String, val reason: String, val code: Int) : Params() + data class Reject(val proposerPublicKey: String, val reason: String, val code: Int) : + Params() data class Disconnect(val sessionTopic: String) : Params() - data class Response(val sessionTopic: String, val jsonRpcResponse: Model.JsonRpcResponse) : Params() + data class Response(val sessionTopic: String, val jsonRpcResponse: Model.JsonRpcResponse) : + Params() - data class Request(val sessionTopic: String, val method: String, val params: String, val chainId: String) : Params() + data class Request( + val sessionTopic: String, + val method: String, + val params: String, + val chainId: String + ) : Params() data class Update( val sessionTopic: String, @@ -251,7 +277,8 @@ object Sign { data class Ping(val topic: String) : Params() - data class Emit(val topic: String, val event: Model.SessionEvent, val chainId: String) : Params() + data class Emit(val topic: String, val event: Model.SessionEvent, val chainId: String) : + Params() data class Extend(val topic: String) : Params() } diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignInterface.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignInterface.kt index 95ffb3cec0..5034143b72 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignInterface.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignInterface.kt @@ -52,10 +52,10 @@ interface SignInterface { fun ping(ping: Sign.Params.Ping, sessionPing: Sign.Listeners.SessionPing? = null) fun disconnect(disconnect: Sign.Params.Disconnect, onError: (Sign.Model.Error) -> Unit) fun getListOfSettledSessions(): List + fun getSettledSessionByTopic(topic: String): Sign.Model.Session? fun getListOfSettledPairings(): List fun getPendingRequests(topic: String): List - interface Websocket { val relay: RelayInterface diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt index 5e3a16322b..9ec2f915dc 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt @@ -25,7 +25,9 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { override val relay: RelayInterface by lazy { wcKoinApp.koin.get() } private val mutex = Mutex() private val signProtocolScope = - CoroutineScope(SupervisorJob() + Executors.newSingleThreadExecutor().asCoroutineDispatcher()) + CoroutineScope( + SupervisorJob() + Executors.newSingleThreadExecutor().asCoroutineDispatcher() + ) companion object { val instance = SignProtocol() @@ -53,7 +55,14 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { val jwtRepository = wcKoinApp.koin.get() val jwt = jwtRepository.generateJWT(initial.relayServerUrl.strippedUrl()) - wcKoinApp.modules(scarletModule(initial.relayServerUrl.addUserAgent(), jwt, initial.connectionType.toRelayConnectionType(), initial.relay)) + wcKoinApp.modules( + scarletModule( + initial.relayServerUrl.addUserAgent(), + jwt, + initial.connectionType.toRelayConnectionType(), + initial.relay + ) + ) signEngine = wcKoinApp.koin.get() signEngine.handleInitializationErrors { error -> onError(Sign.Model.Error(error)) } } @@ -70,7 +79,9 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { is EngineDO.SessionDelete -> delegate.onSessionDelete(event.toClientDeletedSession()) //Responses is EngineDO.SettledSessionResponse -> delegate.onSessionSettleResponse(event.toClientSettledSessionResponse()) - is EngineDO.SessionUpdateNamespacesResponse -> delegate.onSessionUpdateResponse(event.toClientUpdateSessionNamespacesResponse()) + is EngineDO.SessionUpdateNamespacesResponse -> delegate.onSessionUpdateResponse( + event.toClientUpdateSessionNamespacesResponse() + ) //Utils is EngineDO.ConnectionState -> delegate.onConnectionStateChange(event.toClientConnectionState()) is EngineDO.InternalError -> delegate.onError(event.toClientError()) @@ -135,7 +146,10 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { override fun approveSession(approve: Sign.Params.Approve, onError: (Sign.Model.Error) -> Unit) { awaitLock { try { - signEngine.approve(approve.proposerPublicKey, approve.namespaces.toMapOfEngineNamespacesSession()) { error -> + signEngine.approve( + approve.proposerPublicKey, + approve.namespaces.toMapOfEngineNamespacesSession() + ) { error -> onError(Sign.Model.Error(error)) } } catch (error: Exception) { @@ -174,7 +188,10 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { override fun respond(response: Sign.Params.Response, onError: (Sign.Model.Error) -> Unit) { awaitLock { try { - signEngine.respondSessionRequest(response.sessionTopic, response.jsonRpcResponse.toJsonRpcResponseVO()) { error -> + signEngine.respondSessionRequest( + response.sessionTopic, + response.jsonRpcResponse.toJsonRpcResponseVO() + ) { error -> onError(Sign.Model.Error(error)) } } catch (error: Exception) { @@ -187,7 +204,10 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { override fun update(update: Sign.Params.Update, onError: (Sign.Model.Error) -> Unit) { awaitLock { try { - signEngine.sessionUpdate(update.sessionTopic, update.namespaces.toMapOfEngineNamespacesSession()) + signEngine.sessionUpdate( + update.sessionTopic, + update.namespaces.toMapOfEngineNamespacesSession() + ) { error -> onError(Sign.Model.Error(error)) } } catch (error: Exception) { onError(Sign.Model.Error(error)) @@ -210,7 +230,10 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { override fun emit(emit: Sign.Params.Emit, onError: (Sign.Model.Error) -> Unit) { awaitLock { try { - signEngine.emit(emit.topic, emit.event.toEngineEvent(emit.chainId)) { error -> onError(Sign.Model.Error(error)) } + signEngine.emit( + emit.topic, + emit.event.toEngineEvent(emit.chainId) + ) { error -> onError(Sign.Model.Error(error)) } } catch (error: Exception) { onError(Sign.Model.Error(error)) } @@ -233,7 +256,10 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { } @Throws(IllegalStateException::class) - override fun disconnect(disconnect: Sign.Params.Disconnect, onError: (Sign.Model.Error) -> Unit) { + override fun disconnect( + disconnect: Sign.Params.Disconnect, + onError: (Sign.Model.Error) -> Unit + ) { awaitLock { try { signEngine.disconnect(disconnect.sessionTopic) @@ -250,10 +276,20 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { } } + @Throws(IllegalStateException::class) + override fun getSettledSessionByTopic(topic: String): Sign.Model.Session? { + return awaitLock { + signEngine.getListOfSettledSessions() + .map(EngineDO.Session::toClientSettledSession) + .find { session -> session.topic == topic } + } + } + @Throws(IllegalStateException::class) override fun getListOfSettledPairings(): List { return awaitLock { - signEngine.getListOfSettledPairings().map(EngineDO.PairingSettle::toClientSettledPairing) + signEngine.getListOfSettledPairings() + .map(EngineDO.PairingSettle::toClientSettledPairing) } } diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt index 469cffd521..67a3b6d6e7 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt @@ -14,7 +14,8 @@ import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch class SessionRequestViewModel : ViewModel() { - private val _uiState: MutableStateFlow = MutableStateFlow(SessionRequestUI.Initial) + private val _uiState: MutableStateFlow = + MutableStateFlow(SessionRequestUI.Initial) val uiState: StateFlow = _uiState.asStateFlow() private val _event: MutableSharedFlow = MutableSharedFlow() @@ -29,7 +30,8 @@ class SessionRequestViewModel : ViewModel() { val chain: String? = arrayOfArgs[5] val method: String = arrayOfArgs[6].toString() - _uiState.value = SessionRequestUI.Content(topic, icon, peerName, requestId, param, chain, method) + _uiState.value = + SessionRequestUI.Content(topic, icon, peerName, requestId, param, chain, method) } fun reject(sendSessionRequestResponseDeepLink: (Uri) -> Unit) { @@ -83,8 +85,9 @@ class SessionRequestViewModel : ViewModel() { sessionRequest: SessionRequestUI.Content, sendSessionRequestResponseDeepLink: (Uri) -> Unit, ) { - val session = SignClient.getListOfSettledSessions().find { session -> session.topic == sessionRequest.topic } - val deepLinUri = session?.metaData?.redirect?.toUri() ?: "wc:/${sessionRequest.topic})}/request".toUri() + val session = SignClient.getSettledSessionByTopic(sessionRequest.topic) + val deepLinUri = + session?.redirect?.toUri() ?: "wc:/${sessionRequest.topic})}/request".toUri() sendSessionRequestResponseDeepLink(deepLinUri) } diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsViewModel.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsViewModel.kt index 87a422c595..0ed5ea50f8 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsViewModel.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsViewModel.kt @@ -47,19 +47,23 @@ class SessionDetailsViewModel : ViewModel() { } fun getSessionDetails(sessionTopic: String) { - val state = SignClient.getListOfSettledSessions().find { it.topic == sessionTopic }?.let { selectedSession -> + val state = SignClient.getSettledSessionByTopic(sessionTopic)?.let { selectedSession -> selectedSessionTopic = sessionTopic - val listOfChainAccountInfo = filterAndMapAllWalletAccountsToSelectedSessionAccounts(selectedSession) - val selectedSessionPeerData: Sign.Model.AppMetaData = requireNotNull(selectedSession.metaData) + val listOfChainAccountInfo = + filterAndMapAllWalletAccountsToSelectedSessionAccounts(selectedSession) + val selectedSessionPeerData: Sign.Model.AppMetaData = + requireNotNull(selectedSession.metaData) val uiState = SessionDetailsUI.Content( icon = selectedSessionPeerData.icons.first(), name = selectedSessionPeerData.name, url = selectedSessionPeerData.url, description = selectedSessionPeerData.description, listOfChainAccountInfo = listOfChainAccountInfo, - methods = selectedSession.namespaces.values.flatMap { it.methods }.joinToString("\n"), - events = selectedSession.namespaces.values.flatMap { it.events }.joinToString("\n") + methods = selectedSession.namespaces.values.flatMap { it.methods } + .joinToString("\n"), + events = selectedSession.namespaces.values.flatMap { it.events } + .joinToString("\n") ) uiState @@ -92,7 +96,12 @@ class SessionDetailsViewModel : ViewModel() { override fun onSuccess(pingSuccess: Sign.Model.Ping.Success) { viewModelScope.launch() { - _sessionDetails.emit(SampleWalletEvents.PingSuccess(pingSuccess.topic, System.currentTimeMillis())) + _sessionDetails.emit( + SampleWalletEvents.PingSuccess( + pingSuccess.topic, + System.currentTimeMillis() + ) + ) } } @@ -119,14 +128,23 @@ class SessionDetailsViewModel : ViewModel() { // Right now: Emits first alphabetical event // How it should be: User should be able to emit desired event selectedSessionTopic?.let { topic -> - SignClient.getListOfSettledSessions().find { it.topic == topic }?.let { selectedSession -> + SignClient.getSettledSessionByTopic(topic)?.let { selectedSession -> allApprovedEventsWithChains(selectedSession) .filter { (_, chains) -> chains.isNotEmpty() } .let { eventWithChains -> eventWithChains.keys.minOrNull()?.let { event -> eventWithChains[event]!!.first().let { chain -> - Sign.Params.Emit(topic, Sign.Model.SessionEvent(event, "dummyData"), chain).let { sessionEvent -> - SignClient.emit(sessionEvent) { error -> Log.d("Error", "Extend session error: $error") } + Sign.Params.Emit( + topic, + Sign.Model.SessionEvent(event, "dummyData"), + chain + ).let { sessionEvent -> + SignClient.emit(sessionEvent) { error -> + Log.d( + "Error", + "Extend session error: $error" + ) + } return // So as not to log error below } } @@ -142,7 +160,7 @@ class SessionDetailsViewModel : ViewModel() { // Right now: Expand first (right now there's only eip155) namespace with another account, event and method. Works only once // How it should be: User can toggle every account, method, event and then call this method with state to be updated selectedSessionTopic?.let { topic -> - SignClient.getListOfSettledSessions().find { it.topic == topic }?.let { selectedSession -> + SignClient.getSettledSessionByTopic(topic)?.let { selectedSession -> selectedSession.namespaces.firstNotNullOf { it }.let { (key, namespace) -> val secondAccount = namespace.accounts.firstOrNull()?.let { account -> val (chainNamespace, chainReference, _) = account.split(":") @@ -163,9 +181,13 @@ class SessionDetailsViewModel : ViewModel() { if (!events.contains(anotherEvent)) { events.add(anotherEvent) } - val expandedNamespaces = mapOf(key to Sign.Model.Namespace.Session(accounts, methods, events, null)) - val update = Sign.Params.Update(sessionTopic = topic, namespaces = expandedNamespaces) - SignClient.update(update) { error -> Log.e("Error", "Sending update error: $error") } + val expandedNamespaces = + mapOf(key to Sign.Model.Namespace.Session(accounts, methods, events, null)) + val update = + Sign.Params.Update(sessionTopic = topic, namespaces = expandedNamespaces) + SignClient.update(update) { error -> + Log.e("Error", "Sending update error: $error") + } return } } @@ -182,14 +204,22 @@ class SessionDetailsViewModel : ViewModel() { private fun filterAndMapAllWalletAccountsToSelectedSessionAccounts(selectedSession: Sign.Model.Session): List = mapOfAllAccounts.values .flatMap { accountsMap: Map -> - val accountsMapID = mapOfAllAccounts.entries.associate { it.value to it.key }.getValue(accountsMap) - accountsMap.toList().map { (ethChain, accountAddress) -> Triple(ethChain, accountAddress, accountsMapID) } + val accountsMapID = + mapOfAllAccounts.entries.associate { it.value to it.key }.getValue(accountsMap) + accountsMap.toList().map { (ethChain, accountAddress) -> + Triple( + ethChain, + accountAddress, + accountsMapID + ) + } } .filter { (ethChain: EthChains, _, _) -> - val listOfParentChainsWChainId = selectedSession.namespaces.values.flatMap { it.accounts }.map { - val (chainNamespace, chainReference, _) = it.split(":") - "$chainNamespace:$chainReference" - } + val listOfParentChainsWChainId = + selectedSession.namespaces.values.flatMap { it.accounts }.map { + val (chainNamespace, chainReference, _) = it.split(":") + "$chainNamespace:$chainReference" + } "${ethChain.chainNamespace}:${ethChain.chainReference}" in listOfParentChainsWChainId } @@ -208,7 +238,11 @@ class SessionDetailsViewModel : ViewModel() { "${ethChain.chainNamespace}:${ethChain.chainReference}:$accountAddress" in selectedSession.namespaces.values.flatMap { it.accounts } val addressTitle = "$accountAddress-Account $accountsMapId" - SessionDetailsUI.Content.ChainAccountInfo.Account(isSelected, addressTitle, accountAddress) + SessionDetailsUI.Content.ChainAccountInfo.Account( + isSelected, + addressTitle, + accountAddress + ) } SessionDetailsUI.Content.ChainAccountInfo( From f384233256ebc40f8759261709c55084eb5ba69d Mon Sep 17 00:00:00 2001 From: kubel Date: Wed, 10 Aug 2022 11:20:13 +0200 Subject: [PATCH 18/21] Clean up --- .../com/walletconnect/sign/client/SignProtocol.kt | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt index 4f76cf468b..50162e94d9 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/SignProtocol.kt @@ -53,10 +53,14 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { val jwtRepository = wcKoinApp.koin.get() val jwt = jwtRepository.generateJWT(initial.relayServerUrl.strippedUrl()) - wcKoinApp.modules(scarletModule(initial.relayServerUrl.addUserAgent(), - jwt, - initial.connectionType.toRelayConnectionType(), - initial.relay)) + wcKoinApp.modules( + scarletModule( + initial.relayServerUrl.addUserAgent(), + jwt, + initial.connectionType.toRelayConnectionType(), + initial.relay + ) + ) signEngine = wcKoinApp.koin.get() signEngine.handleInitializationErrors { error -> onError(Sign.Model.Error(error)) } } @@ -256,8 +260,7 @@ internal class SignProtocol : SignInterface, SignInterface.Websocket { @Throws(IllegalStateException::class) override fun getSettledSessionByTopic(topic: String): Sign.Model.Session? { return awaitLock { - signEngine.getListOfSettledSessions() - .map(EngineDO.Session::toClientSettledSession) + signEngine.getListOfSettledSessions().map(EngineDO.Session::toClientSettledSession) .find { session -> session.topic == topic } } } From 370724489f35d56e2703b750c3e7f91abcbcdef3 Mon Sep 17 00:00:00 2001 From: Talha Ali Date: Thu, 11 Aug 2022 01:11:19 -0500 Subject: [PATCH 19/21] Added support for cosmos chain in the sample wallet. Fixed an issue with serializing of Cosmos results --- .../dapp/ui/connect/ConnectViewModel.kt | 4 +- .../connect/chain_select/ChainSelectionUI.kt | 2 +- .../SelectedAccountViewModel.kt | 4 +- .../dapp/ui/session/SessionUI.kt | 2 +- .../dapp/ui/session/SessionViewModel.kt | 6 +- .../sample_common/{EthChains.kt => Chains.kt} | 111 +++++++++++------- .../src/main/res/drawable/ic_cosmos.xml | 36 ++++++ .../RelayDOJsonRpcResultJsonAdapter.kt | 30 +++-- .../wallet/domain/EthTestAccounts.kt | 30 ----- .../wallet/domain/TestAccounts.kt | 32 +++++ .../wallet/domain/WalletDelegate.kt | 1 - .../wallet/ui/accounts/AccountsViewModel.kt | 8 +- .../wallet/ui/host/WalletSampleViewModel.kt | 2 +- .../host/proposal/SessionProposalViewModel.kt | 14 +-- .../host/request/SessionRequestViewModel.kt | 12 +- .../sessions/active/ActiveSessionViewModel.kt | 2 +- .../ui/sessions/details/SessionDetailsUI.kt | 2 +- .../details/SessionDetailsViewModel.kt | 20 ++-- 18 files changed, 201 insertions(+), 117 deletions(-) rename signSDK/samples_common/src/main/kotlin/com/walletconnect/sample_common/{EthChains.kt => Chains.kt} (53%) create mode 100644 signSDK/samples_common/src/main/res/drawable/ic_cosmos.xml delete mode 100644 signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/EthTestAccounts.kt create mode 100644 signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/TestAccounts.kt diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/connect/ConnectViewModel.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/connect/ConnectViewModel.kt index ed67e7f007..b6b064edc2 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/connect/ConnectViewModel.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/connect/ConnectViewModel.kt @@ -6,7 +6,7 @@ import androidx.lifecycle.viewModelScope import com.walletconnect.dapp.domain.DappDelegate import com.walletconnect.dapp.ui.SampleDappEvents import com.walletconnect.dapp.ui.connect.chain_select.ChainSelectionUI -import com.walletconnect.sample_common.EthChains +import com.walletconnect.sample_common.Chains import com.walletconnect.sample_common.tag import com.walletconnect.sign.client.Sign import com.walletconnect.sign.client.SignClient @@ -19,7 +19,7 @@ class ConnectViewModel : ViewModel() { private val _listOfChainUI: MutableList = mutableListOf() get() { return if (field.isEmpty()) { - EthChains.values().mapTo(field) { + Chains.values().mapTo(field) { ChainSelectionUI(it.chainName, it.chainNamespace, it.chainReference, it.icon, it.methods, it.events) } } else { diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/connect/chain_select/ChainSelectionUI.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/connect/chain_select/ChainSelectionUI.kt index edf094d097..b181395727 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/connect/chain_select/ChainSelectionUI.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/connect/chain_select/ChainSelectionUI.kt @@ -3,7 +3,7 @@ package com.walletconnect.dapp.ui.connect.chain_select data class ChainSelectionUI( val chainName: String, val chainNamespace: String, - val chainReference: Int, + val chainReference: String, val icon: Int, val methods: List, val events: List, diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt index 63a886f01f..9d5080d97c 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt @@ -92,8 +92,8 @@ class SelectedAccountViewModel : ViewModel() { fun fetchAccountDetails(selectedAccountInfo: String) { val (chainNamespace, chainReference, account) = selectedAccountInfo.split(":") - val chainDetails = EthChains.values().first { - it.chainNamespace == chainNamespace && it.chainReference == chainReference.toInt() + val chainDetails = Chains.values().first { + it.chainNamespace == chainNamespace && it.chainReference == chainReference } val listOfMethods: List = SignClient.getListOfSettledSessions().filter { session -> session.topic == DappDelegate.selectedSessionTopic diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionUI.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionUI.kt index f6dc926609..f1064107d5 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionUI.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionUI.kt @@ -5,5 +5,5 @@ data class SessionUI( val name: String, val address: String, val chainNamespace: String, - val chainReference: Int, + val chainReference: String, ) diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionViewModel.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionViewModel.kt index 89a2e74c04..724ef068b1 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionViewModel.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/session/SessionViewModel.kt @@ -5,7 +5,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.walletconnect.dapp.domain.DappDelegate import com.walletconnect.dapp.ui.SampleDappEvents -import com.walletconnect.sample_common.EthChains +import com.walletconnect.sample_common.Chains import com.walletconnect.sample_common.tag import com.walletconnect.sign.client.Sign import com.walletconnect.sign.client.SignClient @@ -47,8 +47,8 @@ class SessionViewModel : ViewModel() { settledSession.namespaces.values.flatMap { it.accounts } }.map { caip10Account -> val (chainNamespace, chainReference, account) = caip10Account.split(":") - val chain = EthChains.values().first { chain -> - chain.chainNamespace == chainNamespace && chain.chainReference == chainReference.toInt() + val chain = Chains.values().first { chain -> + chain.chainNamespace == chainNamespace && chain.chainReference == chainReference } SessionUI(chain.icon, chain.name, account, chain.chainNamespace, chain.chainReference) diff --git a/signSDK/samples_common/src/main/kotlin/com/walletconnect/sample_common/EthChains.kt b/signSDK/samples_common/src/main/kotlin/com/walletconnect/sample_common/Chains.kt similarity index 53% rename from signSDK/samples_common/src/main/kotlin/com/walletconnect/sample_common/EthChains.kt rename to signSDK/samples_common/src/main/kotlin/com/walletconnect/sample_common/Chains.kt index c3895aa7a6..86aabd1cf8 100644 --- a/signSDK/samples_common/src/main/kotlin/com/walletconnect/sample_common/EthChains.kt +++ b/signSDK/samples_common/src/main/kotlin/com/walletconnect/sample_common/Chains.kt @@ -2,17 +2,6 @@ package com.walletconnect.sample_common import androidx.annotation.DrawableRes -private const val ETH_CHAIN = "eip155" - -private val defaultEthEvents: List = listOf("chainChanged", "accountChanged") - -private val defaultEthMethods: List = listOf( - "eth_sendTransaction", - "personal_sign", - "eth_sign", - "eth_signTypedData" -) - fun getPersonalSignBody(account: String): String { val msg = "My email is john@doe.com - ${System.currentTimeMillis()}".encodeToByteArray() .joinToString(separator = "", prefix = "0x") { eachByte -> "%02x".format(eachByte) } @@ -33,10 +22,10 @@ fun getEthSignTypedData(account: String): String { return "[\"$account\",[\"0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826\",{\"types\":{\"EIP712Domain\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"version\",\"type\":\"string\"},{\"name\":\"chainId\",\"type\":\"uint256\"},{\"name\":\"verifyingContract\",\"type\":\"address\"}],\"Person\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"wallet\",\"type\":\"address\"}],\"Mail\":[{\"name\":\"from\",\"type\":\"Person\"},{\"name\": \"to\",\"type\":\"Person\"},{\"name\":\"contents\",\"type\":\"string\"}]},\"primaryType\":\"Mail\",\"domain\":{\"name\":\"Ether Mail\",\"version\":\"1\",\"chainId\":\"1\",\"verifyingContract\":\"0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC\"},\"message\":{\"from\": {\"name\":\"Cow\",\"wallet\":\"0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826\"},\"to\":{\"name\":\"Bob\",\"wallet\":\"0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB\"},\"contents\":\"Hello, Bob!\"}}]]" } -enum class EthChains( +enum class Chains( val chainName: String, val chainNamespace: String, - val chainReference: Int, + val chainReference: String, @DrawableRes val icon: Int, val methods: List, val events: List, @@ -45,71 +34,109 @@ enum class EthChains( ETHEREUM_MAIN( chainName = "Ethereum", - chainNamespace = ETH_CHAIN, - chainReference = 1, + chainNamespace = Info.Eth.chain, + chainReference = "1", icon = R.drawable.ic_ethereum, - methods = defaultEthMethods, - events = defaultEthEvents, + methods = Info.Eth.defaultMethods, + events = Info.Eth.defaultEvents, order = 1 ), POLYGON_MATIC( chainName = "Polygon Matic", - chainNamespace = ETH_CHAIN, - chainReference = 137, + chainNamespace = Info.Eth.chain, + chainReference = "137", icon = R.drawable.ic_polygon, - methods = defaultEthMethods, - events = defaultEthEvents, + methods = Info.Eth.defaultMethods, + events = Info.Eth.defaultEvents, order = 2 ), ETHEREUM_KOVAN( chainName = "Ethereum Kovan", - chainNamespace = ETH_CHAIN, - chainReference = 42, + chainNamespace = Info.Eth.chain, + chainReference = "42", icon = R.drawable.ic_ethereum, - methods = defaultEthMethods, - events = defaultEthEvents, + methods = Info.Eth.defaultMethods, + events = Info.Eth.defaultEvents, order = 3 ), OPTIMISM_KOVAN( chainName = "Optimism Kovan", - chainNamespace = ETH_CHAIN, - chainReference = 69, + chainNamespace = Info.Eth.chain, + chainReference = "69", icon = R.drawable.ic_optimism, - methods = defaultEthMethods, - events = defaultEthEvents, + methods = Info.Eth.defaultMethods, + events = Info.Eth.defaultEvents, order = 4 ), POLYGON_MUMBAI( chainName = "Polygon Mumbai", - chainNamespace = ETH_CHAIN, - chainReference = 80001, + chainNamespace = Info.Eth.chain, + chainReference = "80001", icon = R.drawable.ic_polygon, - methods = defaultEthMethods, - events = defaultEthEvents, + methods = Info.Eth.defaultMethods, + events = Info.Eth.defaultEvents, order = 5 ), ARBITRUM_RINKBY( chainName = "Arbitrum Rinkeby", - chainNamespace = ETH_CHAIN, - chainReference = 421611, + chainNamespace = Info.Eth.chain, + chainReference = "421611", icon = R.drawable.ic_arbitrum, - methods = defaultEthMethods, - events = defaultEthEvents, + methods = Info.Eth.defaultMethods, + events = Info.Eth.defaultEvents, order = 6 ), CELO_ALFAJORES( chainName = "Celo Alfajores", - chainNamespace = ETH_CHAIN, - chainReference = 44787, + chainNamespace = Info.Eth.chain, + chainReference = "44787", icon = R.drawable.ic_celo, - methods = defaultEthMethods, - events = defaultEthEvents, + methods = Info.Eth.defaultMethods, + events = Info.Eth.defaultEvents, + order = 7 + ), + COSMOS( + chainName = "Cosmos", + chainNamespace = Info.Cosmos.chain, + chainReference = "cosmoshub-4", + icon = R.drawable.ic_cosmos, + methods = Info.Cosmos.defaultMethods, + events = Info.Cosmos.defaultEvents, order = 7 - ) + ); + + companion object { + + sealed class Info { + abstract val chain: String + abstract val defaultEvents: List + abstract val defaultMethods: List + + object Eth: Info() { + override val chain = "eip155" + override val defaultEvents: List = listOf("chainChanged", "accountChanged") + override val defaultMethods: List = listOf( + "eth_sendTransaction", + "personal_sign", + "eth_sign", + "eth_signTypedData" + ) + } + + object Cosmos: Info() { + override val chain = "cosmos" + override val defaultEvents: List = listOf("chainChanged", "accountChanged") + override val defaultMethods: List = listOf( + "cosmos_signDirect", + "cosmos_signAmino" + ) + } + } + } } \ No newline at end of file diff --git a/signSDK/samples_common/src/main/res/drawable/ic_cosmos.xml b/signSDK/samples_common/src/main/res/drawable/ic_cosmos.xml new file mode 100644 index 0000000000..8617d12005 --- /dev/null +++ b/signSDK/samples_common/src/main/res/drawable/ic_cosmos.xml @@ -0,0 +1,36 @@ + + + + + + + + + diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/adapters/RelayDOJsonRpcResultJsonAdapter.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/adapters/RelayDOJsonRpcResultJsonAdapter.kt index 70a84aeaaf..efffc25609 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/adapters/RelayDOJsonRpcResultJsonAdapter.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/core/adapters/RelayDOJsonRpcResultJsonAdapter.kt @@ -9,6 +9,8 @@ import com.squareup.moshi.Moshi import com.squareup.moshi.internal.Util import com.walletconnect.sign.core.model.vo.clientsync.session.params.SessionParamsVO import com.walletconnect.sign.json_rpc.model.RelayerDO +import org.json.JSONArray +import org.json.JSONObject import java.lang.reflect.Constructor import kotlin.Int import kotlin.Long @@ -26,11 +28,11 @@ internal class RelayDOJsonRpcResultJsonAdapter(moshi: Moshi) : JsonAdapter? = null - public override fun toString(): String = buildString(59) { + override fun toString(): String = buildString(59) { append("GeneratedJsonAdapter(").append("RelayDO.JsonRpcResponse.JsonRpcResult").append(')') } - public override fun fromJson(reader: JsonReader): RelayerDO.JsonRpcResponse.JsonRpcResult { + override fun fromJson(reader: JsonReader): RelayerDO.JsonRpcResponse.JsonRpcResult { var id: Long? = null var jsonrpc: String? = null var result: Any? = null @@ -89,6 +91,7 @@ internal class RelayDOJsonRpcResultJsonAdapter(moshi: Moshi) : JsonAdapter { + val approvalParamsString = approvalParamsAdapter.toJson(value_.result) + writer.valueSink().use { + it.writeUtf8(approvalParamsString) + } } - } else { - anyAdapter.toJson(writer, value_.result) + value_.result is String && value_.result.startsWith("{") -> { + writer.valueSink().use { + it.writeUtf8(JSONObject(value_.result).toString()) + } + } + value_.result is String && value_.result.startsWith("[") -> { + writer.valueSink().use { + it.writeUtf8(JSONArray(value_.result).toString()) + } + } + else -> anyAdapter.toJson(writer, value_.result) } writer.endObject() } diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/EthTestAccounts.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/EthTestAccounts.kt deleted file mode 100644 index b8b001bcfa..0000000000 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/EthTestAccounts.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.walletconnect.wallet.domain - -import com.walletconnect.sample_common.EthChains - -const val ACCOUNTS_1_ID = 1 -val mapOfAccounts1: Map = mapOf( - EthChains.ETHEREUM_MAIN to "0x022c0c42a80bd19EA4cF0F94c4F9F96645759716", - EthChains.POLYGON_MATIC to "0x022c0c42a80bd19EA4cF0F94c4F9F96645759716", - EthChains.ETHEREUM_KOVAN to "0x022c0c42a80bd19EA4cF0F94c4F9F96645759716", - EthChains.OPTIMISM_KOVAN to "0xf5de760f2e916647fd766b4ad9e85ff943ce3a2b", - EthChains.POLYGON_MUMBAI to "0x5A9D8a83fF2a032123954174280Af60B6fa32781", - EthChains.ARBITRUM_RINKBY to "0x682570add15588df8c3506eef2e737db29266de2", - EthChains.CELO_ALFAJORES to "0xdD5Cb02066fde415dda4f04EE53fBb652066afEE" -) - -const val ACCOUNTS_2_ID = 2 -val mapOfAccounts2: Map = mapOf( - EthChains.ETHEREUM_MAIN to "0x5496858C1f2f469Eb6A6D378C332e7a4E1dc1B4D", - EthChains.POLYGON_MATIC to "0x5496858C1f2f469Eb6A6D378C332e7a4E1dc1B4D", - EthChains.ETHEREUM_KOVAN to "0x5496858C1f2f469Eb6A6D378C332e7a4E1dc1B4D", - EthChains.OPTIMISM_KOVAN to "0xe16821547bb816ea3f25c67c15a634b104695a32", - EthChains.POLYGON_MUMBAI to "0x5496858C1f2f469Eb6A6D378C332e7a4E1dc1B4D", - EthChains.ARBITRUM_RINKBY to "0x49d07a0e25d3d1881bfd1545bb9b12ac2eb00f12", - EthChains.CELO_ALFAJORES to "0x3a20c11fa54dfbb73f907e3953684a5d93e719a7" -) - -val mapOfAllAccounts = mapOf( - ACCOUNTS_1_ID to mapOfAccounts1, - ACCOUNTS_2_ID to mapOfAccounts2 -) \ No newline at end of file diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/TestAccounts.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/TestAccounts.kt new file mode 100644 index 0000000000..90a3d500c0 --- /dev/null +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/TestAccounts.kt @@ -0,0 +1,32 @@ +package com.walletconnect.wallet.domain + +import com.walletconnect.sample_common.Chains + +const val ACCOUNTS_1_ID = 1 +val mapOfAccounts1: Map = mapOf( + Chains.ETHEREUM_MAIN to "0x022c0c42a80bd19EA4cF0F94c4F9F96645759716", + Chains.POLYGON_MATIC to "0x022c0c42a80bd19EA4cF0F94c4F9F96645759716", + Chains.ETHEREUM_KOVAN to "0x022c0c42a80bd19EA4cF0F94c4F9F96645759716", + Chains.OPTIMISM_KOVAN to "0xf5de760f2e916647fd766b4ad9e85ff943ce3a2b", + Chains.POLYGON_MUMBAI to "0x5A9D8a83fF2a032123954174280Af60B6fa32781", + Chains.ARBITRUM_RINKBY to "0x682570add15588df8c3506eef2e737db29266de2", + Chains.CELO_ALFAJORES to "0xdD5Cb02066fde415dda4f04EE53fBb652066afEE", + Chains.COSMOS to "cosmos1w605a5ejjlhp04eahjqxhjhmg8mj6nqhp8v6xc" +) + +const val ACCOUNTS_2_ID = 2 +val mapOfAccounts2: Map = mapOf( + Chains.ETHEREUM_MAIN to "0x5496858C1f2f469Eb6A6D378C332e7a4E1dc1B4D", + Chains.POLYGON_MATIC to "0x5496858C1f2f469Eb6A6D378C332e7a4E1dc1B4D", + Chains.ETHEREUM_KOVAN to "0x5496858C1f2f469Eb6A6D378C332e7a4E1dc1B4D", + Chains.OPTIMISM_KOVAN to "0xe16821547bb816ea3f25c67c15a634b104695a32", + Chains.POLYGON_MUMBAI to "0x5496858C1f2f469Eb6A6D378C332e7a4E1dc1B4D", + Chains.ARBITRUM_RINKBY to "0x49d07a0e25d3d1881bfd1545bb9b12ac2eb00f12", + Chains.CELO_ALFAJORES to "0x3a20c11fa54dfbb73f907e3953684a5d93e719a7", + Chains.COSMOS to "cosmos1ywk2tpsahzn2qh5g6flhfyh40qvdf50urcmuf9" +) + +val mapOfAllAccounts = mapOf( + ACCOUNTS_1_ID to mapOfAccounts1, + ACCOUNTS_2_ID to mapOfAccounts2 +) \ No newline at end of file diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/WalletDelegate.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/WalletDelegate.kt index c72cc65039..5b9b2c6f26 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/WalletDelegate.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/domain/WalletDelegate.kt @@ -45,7 +45,6 @@ object WalletDelegate : SignClient.WalletDelegate { } } - override fun onSessionSettleResponse(settleSessionResponse: Sign.Model.SettledSessionResponse) { sessionProposal = null diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/accounts/AccountsViewModel.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/accounts/AccountsViewModel.kt index 3144f54689..f685c9ee20 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/accounts/AccountsViewModel.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/accounts/AccountsViewModel.kt @@ -2,7 +2,7 @@ package com.walletconnect.wallet.ui.accounts import android.util.Log import androidx.lifecycle.ViewModel -import com.walletconnect.sample_common.EthChains +import com.walletconnect.sample_common.Chains import com.walletconnect.sample_common.tag import com.walletconnect.wallet.domain.WalletDelegate import com.walletconnect.wallet.domain.mapOfAccounts1 @@ -23,7 +23,7 @@ class AccountsViewModel : ViewModel() { SignClient.pair(pairingParams) { error -> Log.e(tag(this), error.throwable.stackTraceToString()) } val selectedAccountInfoSet: Set> = _accountUI.value.first { it.isSelected }.chainAddressList.map { it.chainName to it.accountAddress }.toSet() - val allAccountsMappedToUIDomainSetWAccountId: Map>, Int> = mapOfAllAccounts.map { (accountsId: Int, mapOfAccounts: Map) -> + val allAccountsMappedToUIDomainSetWAccountId: Map>, Int> = mapOfAllAccounts.map { (accountsId: Int, mapOfAccounts: Map) -> mapOfAccounts.map { it.key.chainName to it.value }.toSet() to accountsId }.toMap() val uiDomainSetWAccountIdsMatchingSelectedAccounts: Map>, Int> = allAccountsMappedToUIDomainSetWAccountId.filter { (uiDomainMappedSet: Set>, _) -> @@ -41,10 +41,10 @@ class AccountsViewModel : ViewModel() { } private companion object { - val INITIAL_CHAIN_ADDRESS_LIST_1: List = mapOfAccounts1.map { (chain: EthChains, accountAddress: String) -> + val INITIAL_CHAIN_ADDRESS_LIST_1: List = mapOfAccounts1.map { (chain: Chains, accountAddress: String) -> ChainAddressUI(chain.icon, chain.chainName, accountAddress) } - val INITIAL_CHAIN_ADDRESS_LIST_2: List = mapOfAccounts2.map { (chain: EthChains, accountAddress: String) -> + val INITIAL_CHAIN_ADDRESS_LIST_2: List = mapOfAccounts2.map { (chain: Chains, accountAddress: String) -> ChainAddressUI(chain.icon, chain.chainName, accountAddress) } val INITIAL_ACCOUNTS_LIST = listOf( diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/WalletSampleViewModel.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/WalletSampleViewModel.kt index d03430e14e..4d87c34343 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/WalletSampleViewModel.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/WalletSampleViewModel.kt @@ -15,7 +15,7 @@ class WalletSampleViewModel : ViewModel() { is Sign.Model.SessionProposal -> SampleWalletEvents.SessionProposal is Sign.Model.SessionRequest -> { val topic = wcEvent.topic - val icon = wcEvent.peerMetaData?.icons?.first() + val icon = wcEvent.peerMetaData?.icons?.firstOrNull() val peerName = wcEvent.peerMetaData?.name val requestId = wcEvent.request.id.toString() val params = wcEvent.request.params diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/proposal/SessionProposalViewModel.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/proposal/SessionProposalViewModel.kt index 4ed1b0272d..3d6172c03b 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/proposal/SessionProposalViewModel.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/proposal/SessionProposalViewModel.kt @@ -2,7 +2,7 @@ package com.walletconnect.wallet.ui.host.proposal import android.util.Log import androidx.lifecycle.ViewModel -import com.walletconnect.sample_common.EthChains +import com.walletconnect.sample_common.Chains import com.walletconnect.sample_common.tag import com.walletconnect.sign.client.Sign import com.walletconnect.sign.client.SignClient @@ -22,14 +22,14 @@ class SessionProposalViewModel : ViewModel() { fun approve() { if (WalletDelegate.sessionProposal != null && WalletDelegate.selectedChainAddressId in mapOfAllAccounts.keys) { - val selectedAccounts: Map = mapOfAllAccounts[WalletDelegate.selectedChainAddressId] ?: throw Exception("Can't find account") + val selectedAccounts: Map = mapOfAllAccounts[WalletDelegate.selectedChainAddressId] ?: throw Exception("Can't find account") val sessionProposal: Sign.Model.SessionProposal = requireNotNull(WalletDelegate.sessionProposal) - val sessionNamespaces: Map = selectedAccounts.filter { (chain: EthChains, _) -> + val sessionNamespaces: Map = selectedAccounts.filter { (chain: Chains, _) -> "${chain.chainNamespace}:${chain.chainReference}" in sessionProposal.requiredNamespaces.values.flatMap { it.chains } - }.toList().groupBy { (chain: EthChains, _: String) -> + }.toList().groupBy { (chain: Chains, _: String) -> chain.chainNamespace - }.map { (namespaceKey: String, chainData: List>) -> - val accounts = chainData.map { (chain: EthChains, accountAddress: String) -> + }.map { (namespaceKey: String, chainData: List>) -> + val accounts = chainData.map { (chain: Chains, accountAddress: String) -> "${chain.chainNamespace}:${chain.chainReference}:${accountAddress}" } val methods = sessionProposal.requiredNamespaces.values.flatMap { it.methods } @@ -70,7 +70,7 @@ class SessionProposalViewModel : ViewModel() { private fun generateSessionProposalEvent(sessionProposal: Sign.Model.SessionProposal): SessionProposalUI { return SessionProposalUI( - peerIcon = sessionProposal.icons.first().toString(), + peerIcon = sessionProposal.icons.firstOrNull().toString(), peerName = sessionProposal.name, proposalUri = sessionProposal.url, peerDescription = sessionProposal.description, diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt index 67a3b6d6e7..bc9789e999 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt @@ -5,6 +5,7 @@ import android.util.Log import androidx.core.net.toUri import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import com.walletconnect.sample_common.Chains import com.walletconnect.sample_common.tag import com.walletconnect.sign.client.Sign import com.walletconnect.sign.client.SignClient @@ -60,15 +61,20 @@ class SessionRequestViewModel : ViewModel() { fun approve(sendSessionRequestResponseDeepLink: (Uri) -> Unit) { (uiState.value as? SessionRequestUI.Content)?.let { sessionRequest -> - val result = Sign.Params.Response( + val result: String = when { + sessionRequest.chain?.contains(Chains.Companion.Info.Eth.chain, true) == true -> """0xa3f20717a250c2b0b729b7e5becbff67fdaef7e0699da4de7ca5895b02a170a12d887fd3b17bfdce3481f10bea41f45ba9f709d39ce8325427b57afcfc994cee1b""" + sessionRequest.chain?.contains(Chains.Companion.Info.Cosmos.chain, true) == true -> """{"signature":"pBvp1bMiX6GiWmfYmkFmfcZdekJc19GbZQanqaGa\/kLPWjoYjaJWYttvm17WoDMyn4oROas4JLu5oKQVRIj911==","pub_key":{"value":"psclI0DNfWq6cOlGrKD9wNXPxbUsng6Fei77XjwdkPSt","type":"tendermint\/PubKeySecp256k1"}}""" + else -> throw Exception("Unsupported Chain") + } + val response = Sign.Params.Response( sessionTopic = sessionRequest.topic, jsonRpcResponse = Sign.Model.JsonRpcResponse.JsonRpcResult( sessionRequest.requestId, - "0xa3f20717a250c2b0b729b7e5becbff67fdaef7e0699da4de7ca5895b02a170a12d887fd3b17bfdce3481f10bea41f45ba9f709d39ce8325427b57afcfc994cee1b" + result ) ) - SignClient.respond(result) { error -> + SignClient.respond(response) { error -> Log.e(tag(this), error.throwable.stackTraceToString()) } diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/active/ActiveSessionViewModel.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/active/ActiveSessionViewModel.kt index a256bb8f0b..52f64a3dc1 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/active/ActiveSessionViewModel.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/active/ActiveSessionViewModel.kt @@ -18,7 +18,7 @@ class ActiveSessionViewModel : ViewModel() { wcSession.metaData != null }.map { wcSession -> ActiveSessionUI( - icon = wcSession.metaData!!.icons.first(), + icon = wcSession.metaData?.icons?.firstOrNull(), name = wcSession.metaData!!.name, url = wcSession.metaData!!.url, topic = wcSession.topic diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsUI.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsUI.kt index 332d0ec1c4..7ec8166c83 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsUI.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsUI.kt @@ -18,7 +18,7 @@ sealed class SessionDetailsUI { val chainName: String, @DrawableRes val chainIcon: Int, val chainNamespace: String, - val chainReference: Int, + val chainReference: String, val listOfAccounts: List ) { diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsViewModel.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsViewModel.kt index 0ed5ea50f8..cc94458fa2 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsViewModel.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/sessions/details/SessionDetailsViewModel.kt @@ -3,7 +3,7 @@ package com.walletconnect.wallet.ui.sessions.details import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope -import com.walletconnect.sample_common.EthChains +import com.walletconnect.sample_common.Chains import com.walletconnect.sample_common.tag import com.walletconnect.sign.client.Sign import com.walletconnect.sign.client.SignClient @@ -55,7 +55,7 @@ class SessionDetailsViewModel : ViewModel() { val selectedSessionPeerData: Sign.Model.AppMetaData = requireNotNull(selectedSession.metaData) val uiState = SessionDetailsUI.Content( - icon = selectedSessionPeerData.icons.first(), + icon = selectedSessionPeerData.icons.firstOrNull(), name = selectedSessionPeerData.name, url = selectedSessionPeerData.url, description = selectedSessionPeerData.description, @@ -165,7 +165,7 @@ class SessionDetailsViewModel : ViewModel() { val secondAccount = namespace.accounts.firstOrNull()?.let { account -> val (chainNamespace, chainReference, _) = account.split(":") mapOfAccounts2 - .filter { (ethChain, _) -> ethChain.chainNamespace == chainNamespace && ethChain.chainReference == chainReference.toInt() } + .filter { (ethChain, _) -> ethChain.chainNamespace == chainNamespace && ethChain.chainReference == chainReference } .map { (ethChain, address) -> "${ethChain.chainNamespace}:${ethChain.chainReference}:${address}" } .firstOrNull() } @@ -203,7 +203,7 @@ class SessionDetailsViewModel : ViewModel() { private fun filterAndMapAllWalletAccountsToSelectedSessionAccounts(selectedSession: Sign.Model.Session): List = mapOfAllAccounts.values - .flatMap { accountsMap: Map -> + .flatMap { accountsMap: Map -> val accountsMapID = mapOfAllAccounts.entries.associate { it.value to it.key }.getValue(accountsMap) accountsMap.toList().map { (ethChain, accountAddress) -> @@ -214,7 +214,7 @@ class SessionDetailsViewModel : ViewModel() { ) } } - .filter { (ethChain: EthChains, _, _) -> + .filter { (ethChain: Chains, _, _) -> val listOfParentChainsWChainId = selectedSession.namespaces.values.flatMap { it.accounts }.map { val (chainNamespace, chainReference, _) = it.split(":") @@ -223,17 +223,17 @@ class SessionDetailsViewModel : ViewModel() { "${ethChain.chainNamespace}:${ethChain.chainReference}" in listOfParentChainsWChainId } - .sortedBy { (ethChain: EthChains, _, _) -> ethChain.order } - .groupBy { (ethChain: EthChains, _: String, _: Int) -> ethChain }.values - .map { it: List> -> - val chainDetails: EthChains = it.first().first + .sortedBy { (ethChain: Chains, _, _) -> ethChain.order } + .groupBy { (ethChain: Chains, _: String, _: Int) -> ethChain }.values + .map { it: List> -> + val chainDetails: Chains = it.first().first val chainName = chainDetails.chainName val chainIcon = chainDetails.icon val parentChain = chainDetails.chainNamespace val chainId = chainDetails.chainReference val listOfAccounts: List = - it.map { (ethChain: EthChains, accountAddress: String, accountsMapId: Int) -> + it.map { (ethChain: Chains, accountAddress: String, accountsMapId: Int) -> val isSelected = "${ethChain.chainNamespace}:${ethChain.chainReference}:$accountAddress" in selectedSession.namespaces.values.flatMap { it.accounts } val addressTitle = "$accountAddress-Account $accountsMapId" From 90adce635005a13072ac0afbb0e819c201fc32a0 Mon Sep 17 00:00:00 2001 From: szymon Date: Thu, 11 Aug 2022 15:59:15 +0200 Subject: [PATCH 20/21] fix: Invalid deeplinks --- .../ui/selected_account/SelectedAccountViewModel.kt | 7 ++----- .../ui/host/request/SessionRequestViewModel.kt | 13 ++++++------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt index 9d5080d97c..8f691a6be5 100644 --- a/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt +++ b/signSDK/dapp/src/main/kotlin/com/walletconnect/dapp/ui/selected_account/SelectedAccountViewModel.kt @@ -82,11 +82,8 @@ class SelectedAccountViewModel : ViewModel() { } } - val sessionRequestDeepLinkUri = - SignClient.getSettledSessionByTopic(requestParams.sessionTopic)?.redirect?.toUri() - ?: "wc:/${requestParams.sessionTopic}/request".toUri() - - sendSessionRequestDeepLink(sessionRequestDeepLinkUri) + SignClient.getSettledSessionByTopic(requestParams.sessionTopic)?.redirect?.toUri() + ?.let { deepLinkUri -> sendSessionRequestDeepLink(deepLinkUri) } } } diff --git a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt index bc9789e999..585ec233ea 100644 --- a/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt +++ b/signSDK/wallet/src/main/kotlin/com/walletconnect/wallet/ui/host/request/SessionRequestViewModel.kt @@ -62,8 +62,10 @@ class SessionRequestViewModel : ViewModel() { fun approve(sendSessionRequestResponseDeepLink: (Uri) -> Unit) { (uiState.value as? SessionRequestUI.Content)?.let { sessionRequest -> val result: String = when { - sessionRequest.chain?.contains(Chains.Companion.Info.Eth.chain, true) == true -> """0xa3f20717a250c2b0b729b7e5becbff67fdaef7e0699da4de7ca5895b02a170a12d887fd3b17bfdce3481f10bea41f45ba9f709d39ce8325427b57afcfc994cee1b""" - sessionRequest.chain?.contains(Chains.Companion.Info.Cosmos.chain, true) == true -> """{"signature":"pBvp1bMiX6GiWmfYmkFmfcZdekJc19GbZQanqaGa\/kLPWjoYjaJWYttvm17WoDMyn4oROas4JLu5oKQVRIj911==","pub_key":{"value":"psclI0DNfWq6cOlGrKD9wNXPxbUsng6Fei77XjwdkPSt","type":"tendermint\/PubKeySecp256k1"}}""" + sessionRequest.chain?.contains(Chains.Companion.Info.Eth.chain, + true) == true -> """0xa3f20717a250c2b0b729b7e5becbff67fdaef7e0699da4de7ca5895b02a170a12d887fd3b17bfdce3481f10bea41f45ba9f709d39ce8325427b57afcfc994cee1b""" + sessionRequest.chain?.contains(Chains.Companion.Info.Cosmos.chain, + true) == true -> """{"signature":"pBvp1bMiX6GiWmfYmkFmfcZdekJc19GbZQanqaGa\/kLPWjoYjaJWYttvm17WoDMyn4oROas4JLu5oKQVRIj911==","pub_key":{"value":"psclI0DNfWq6cOlGrKD9wNXPxbUsng6Fei77XjwdkPSt","type":"tendermint\/PubKeySecp256k1"}}""" else -> throw Exception("Unsupported Chain") } val response = Sign.Params.Response( @@ -91,10 +93,7 @@ class SessionRequestViewModel : ViewModel() { sessionRequest: SessionRequestUI.Content, sendSessionRequestResponseDeepLink: (Uri) -> Unit, ) { - val session = SignClient.getSettledSessionByTopic(sessionRequest.topic) - val deepLinUri = - session?.redirect?.toUri() ?: "wc:/${sessionRequest.topic})}/request".toUri() - - sendSessionRequestResponseDeepLink(deepLinUri) + SignClient.getSettledSessionByTopic(sessionRequest.topic)?.redirect?.toUri() + ?.let { deepLinkUri -> sendSessionRequestResponseDeepLink(deepLinkUri) } } } \ No newline at end of file From 45a21d1be4205ac1778d0023eea2cba7a4ba7f08 Mon Sep 17 00:00:00 2001 From: Talha Ali Date: Thu, 11 Aug 2022 09:12:27 -0500 Subject: [PATCH 21/21] bumped user agent version --- .../kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt index cef153ddab..7d36baef37 100644 --- a/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt +++ b/signSDK/sign/src/main/kotlin/com/walletconnect/sign/client/mapper/ClientMapper.kt @@ -220,7 +220,7 @@ internal fun String.strippedUrl() = Uri.parse(this).run { internal fun String.addUserAgent(): String { return Uri.parse(this).buildUpon() // TODO: Setup env variable for version and tag. Use env variable here instead of hard coded version - .appendQueryParameter("ua", """wc-2/kotlin-2.0.0-rc.0/android-${Build.VERSION.RELEASE}""") + .appendQueryParameter("ua", """wc-2/kotlin-2.0.0-rc.2/android-${Build.VERSION.RELEASE}""") .build() .toString() } \ No newline at end of file