From bad25d053c28676f3501aa77b9ff771c252d7e78 Mon Sep 17 00:00:00 2001 From: creeppak <59798783+creeppak@users.noreply.github.com> Date: Tue, 22 Oct 2024 16:43:59 +0100 Subject: [PATCH] WalletConnect transforms into Reown (#1199) * Replaced WalletConnect with Reown * Added 'Set Primary Chain' functionality to Web3 Settings Editor * Fixed local wallet connection * Fixed namespace building process for Reown * Improved Reown session management and redirection to local wallet procedure * Added wallet filters for Desktop and Mobile for Reown * Removed commented out code * Added WithForceNewSession extension method for ReownConfigAsset also * Added Reown logo * Moved the BuildUriParameters method into HttpUtils.cs * Updated Packages build process to include Reown * Updated a Reown log message * Linter fixes * Removed commented out code * Reown integration polishing * Linter --- ChainSafe.Gaming.sln | 2 +- ChainSafe.Gaming.sln.DotSettings | 3 +- .../Editor/ConnectionHandlerEditor.cs | 2 +- .../Editor/{WalletConnect.meta => Reown.meta} | 0 .../Editor/Reown/ReownConfigEditor.cs | 10 + .../ReownConfigEditor.cs.meta} | 0 .../Editor/Reown/ReownConfigEditorBase.cs | 29 ++ .../ReownConfigEditorBase.cs.meta} | 0 .../Reown/ReownConnectionProviderEditor.cs | 10 + .../ReownConnectionProviderEditor.cs.meta} | 0 .../WalletConnectConfigEditor.cs | 70 ---- .../WalletConnectConfigSOEditor.cs | 9 - .../WalletConnectConnectionProviderEditor.cs | 10 - .../Web3SettingsEditor.ChainSettings.cs | 10 + .../Editor/Web3SettingsEditor.cs | 27 +- .../Editor/chainsafe.web3-unity.Editor.asmdef | 2 +- .../Runtime/GUI/GuiCoordinationSystem.cs | 16 +- .../Runtime/GUI/GuiInfoOverlay.cs | 6 +- .../Runtime/GUI/GuiLayer.cs | 4 +- .../Runtime/GUI/GuiManager.cs | 12 +- .../Runtime/GUI/GuiOrientationSystem.cs | 2 +- .../Runtime/GUI/GuiOverlayManager.cs | 6 +- .../Runtime/GUI/GuiScreen.cs | 10 +- .../Runtime/GUI/GuiScreenFactory.cs | 2 +- .../Runtime/GUI/IGuiScreen.cs | 2 +- .../{Wallet Connect.meta => Reown.meta} | 0 .../Predefined Wallet Button.prefab | 0 .../Predefined Wallet Button.prefab.meta | 0 .../Reown Dialog.prefab} | 2 +- .../Reown Dialog.prefab.meta} | 0 .../dialog-hide.anim | 0 .../dialog-hide.anim.meta | 0 .../dialog-show.anim | 0 .../dialog-show.anim.meta | 0 .../Runtime/Prefabs/Web3Unity.prefab | 2 +- .../Runtime/Scripts/ConnectToWallet.cs | 6 +- .../Scripts/Connection/ConnectionProvider.cs | 12 +- ...Provider.cs => ReownConnectionProvider.cs} | 79 ++-- .../ReownConnectionProvider.cs.meta | 13 + .../WalletConnectConnectionProvider.cs.meta | 11 - .../{WalletConnect.meta => Reown.meta} | 0 .../AotConfiguration.cs | 10 +- .../AotConfiguration.cs.meta | 0 .../{WalletConnect => Reown}/Dialog.meta | 0 .../Dialog/ConnectionDialogBase.cs | 14 +- .../Dialog/ConnectionDialogBase.cs.meta | 0 .../Dialog/ConnectionDialogChainSafe.cs | 3 +- .../Dialog/ConnectionDialogChainSafe.cs.meta | 0 .../Dialog/ConnectionHandlerBehaviour.cs | 4 +- .../Dialog/ConnectionHandlerBehaviour.cs.meta | 0 .../Dialog/ConnectionHandlerProviderAsset.cs | 11 + .../ConnectionHandlerProviderAsset.cs.meta} | 0 .../ConnectionHandlerProviderChainSafe.cs | 8 +- ...ConnectionHandlerProviderChainSafe.cs.meta | 0 .../Dialog/LocalWalletButton.cs | 32 +- .../Dialog/LocalWalletButton.cs.meta | 0 .../Dialog/QrCodeBuilder.cs | 2 +- .../Dialog/QrCodeBuilder.cs.meta | 0 .../NativeWebSocketConnectionBuilder.cs | 12 +- .../NativeWebSocketConnectionBuilder.cs.meta | 0 .../ReownConfigAsset.cs} | 32 +- .../ReownConfigAsset.cs.meta} | 0 .../Scripts/Reown/ReownConfigExtensions.cs | 31 ++ .../ReownConfigExtensions.cs.meta} | 0 .../ReownWeb3.cs} | 17 +- .../ReownWeb3.cs.meta} | 0 .../WebSocketConnection.cs | 31 +- .../WebSocketConnection.cs.meta | 0 .../Runtime/Scripts/Samples/Samples.cs | 2 +- .../Runtime/Scripts/UI/ConnectScreen.cs | 10 +- .../Scripts/UI/ConnectionProviderButton.cs | 2 +- .../Dialog/ConnectionHandlerProviderSO.cs | 11 - .../WalletConnectConfigExtensions.cs | 20 - .../Runtime/Scripts/Web3Unity.cs | 4 +- .../Runtime/Sprites/reown-logo.png | Bin 0 -> 4453 bytes .../Runtime/Sprites/reown-logo.png.meta | 127 +++++++ .../Tests/Runtime/EvmCustomResponseTests.cs | 2 +- .../Tests/Runtime/SampleTestsBase.cs | 5 +- ...ctProviderConfig.cs => StubReownConfig.cs} | 2 +- ...Config.cs.meta => StubReownConfig.cs.meta} | 0 ...onnectProvider.cs => StubReownProvider.cs} | 8 +- ...ider.cs.meta => StubReownProvider.cs.meta} | 0 .../chainsafe.web3-unity.RuntimeTests.asmdef | 4 +- Setup/dependencies.json | 22 +- .../InProcessTransactionExecutor.cs | 3 +- .../NetCoreHttpClient.cs | 87 ++--- .../ChainSafe.Gaming.Reown.csproj} | 5 +- .../Connection/ConnectionHandlerConfig.cs | 5 +- .../Connection/IConnectionHandler.cs | 2 +- .../Connection/IConnectionHandlerProvider.cs | 2 +- .../Delegates.cs | 2 +- .../IConnectionHelper.cs | 4 +- .../IReownConfig.cs} | 63 ++-- .../Methods/EthSendTransaction.cs | 10 +- .../Methods/EthSignMessage.cs | 8 +- .../Methods/EthSignTransaction.cs | 10 +- .../Methods/EthSignTypedData.cs | 9 +- .../Methods/WalletSwitchEthereumChain.cs | 8 +- .../Models/TransactionModel.cs | 4 +- .../Models/WalletModel.cs | 40 ++ .../RedirectionHandler.cs | 129 +++++++ src/ChainSafe.Gaming.Reown/ReownExtensions.cs | 78 ++++ src/ChainSafe.Gaming.Reown/ReownHttpClient.cs | 43 +++ .../ReownIntegrationException.cs | 21 ++ .../ReownLogLevel.cs} | 4 +- .../ReownLogWriter.cs} | 22 +- .../ReownProvider.cs} | 345 +++++++++--------- .../ReownSubCategory.cs} | 6 +- .../Storage/ReownStorageFactory.cs | 55 +++ .../Wallets/IWalletRegistry.cs | 25 ++ .../Wallets/ReownWalletRegistry.cs | 106 ++++++ .../Wallets}/WalletLocationOption.cs | 2 +- .../WalletLocationOptionsExtensions.cs | 2 +- .../Wallets/WalletRegistryResponse.cs | 15 + .../ChainSafe.Gaming.Tests.csproj | 2 +- .../Core/StubHttpClient.cs | 16 +- .../WalletConnectDeepLinksTests.cs | 5 +- .../ChainSafe.Gaming.Unity.csproj | 2 +- src/ChainSafe.Gaming.Unity/UnityHttpClient.cs | 108 ++---- src/ChainSafe.Gaming.Unity/link.xml | 2 +- .../Models/ChainModel.cs | 48 --- .../Models/ImageUrlsModel.cs | 28 -- .../Models/WalletLinkModel.cs | 24 -- .../Models/WalletModel.cs | 52 --- .../RedirectionHandler.cs | 180 --------- .../Storage/DataStorage.cs | 116 ------ .../Storage/LocalData.cs | 18 - .../WalletConnectException.cs | 21 -- .../WalletConnectExtensions.cs | 81 ---- .../Wallets/IWalletRegistry.cs | 26 -- .../Wallets/WalletRegistry.cs | 107 ------ .../Wallets/WalletRegistryResponse.cs | 12 - .../Web3/Core/Environment/Http/HttpHeader.cs | 9 + .../Web3/Core/Environment/Http/HttpUtils.cs | 17 + .../Web3/Core/Environment/IHttpClient.cs | 50 ++- .../Resources/ReownConnectionProvider.asset | 35 ++ ...eta => ReownConnectionProvider.asset.meta} | 4 +- .../WalletConnectConnectionProvider.asset | 44 --- src/UnitySampleProject/Assets/link.xml | 12 +- .../UnitySampleProject.sln.DotSettings | 3 +- 140 files changed, 1429 insertions(+), 1503 deletions(-) rename Packages/io.chainsafe.web3-unity/Editor/{WalletConnect.meta => Reown.meta} (100%) create mode 100644 Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditor.cs rename Packages/io.chainsafe.web3-unity/Editor/{WalletConnect/WalletConnectConfigSOEditor.cs.meta => Reown/ReownConfigEditor.cs.meta} (100%) create mode 100644 Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditorBase.cs rename Packages/io.chainsafe.web3-unity/Editor/{WalletConnect/WalletConnectConfigEditor.cs.meta => Reown/ReownConfigEditorBase.cs.meta} (100%) create mode 100644 Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConnectionProviderEditor.cs rename Packages/io.chainsafe.web3-unity/Editor/{WalletConnect/WalletConnectConnectionProviderEditor.cs.meta => Reown/ReownConnectionProviderEditor.cs.meta} (100%) delete mode 100644 Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigEditor.cs delete mode 100644 Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigSOEditor.cs delete mode 100644 Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConnectionProviderEditor.cs rename Packages/io.chainsafe.web3-unity/Runtime/Prefabs/{Wallet Connect.meta => Reown.meta} (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Prefabs/{Wallet Connect => Reown}/Predefined Wallet Button.prefab (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Prefabs/{Wallet Connect => Reown}/Predefined Wallet Button.prefab.meta (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Prefabs/{Wallet Connect/WalletConnect Dialog.prefab => Reown/Reown Dialog.prefab} (99%) rename Packages/io.chainsafe.web3-unity/Runtime/Prefabs/{Wallet Connect/WalletConnect Dialog.prefab.meta => Reown/Reown Dialog.prefab.meta} (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Prefabs/{Wallet Connect => Reown}/dialog-hide.anim (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Prefabs/{Wallet Connect => Reown}/dialog-hide.anim.meta (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Prefabs/{Wallet Connect => Reown}/dialog-show.anim (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Prefabs/{Wallet Connect => Reown}/dialog-show.anim.meta (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/{WalletConnectConnectionProvider.cs => ReownConnectionProvider.cs} (60%) create mode 100644 Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/ReownConnectionProvider.cs.meta delete mode 100644 Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/WalletConnectConnectionProvider.cs.meta rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect.meta => Reown.meta} (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/AotConfiguration.cs (80%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/AotConfiguration.cs.meta (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog.meta (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/ConnectionDialogBase.cs (91%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/ConnectionDialogBase.cs.meta (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/ConnectionDialogChainSafe.cs (97%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/ConnectionDialogChainSafe.cs.meta (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/ConnectionHandlerBehaviour.cs (74%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/ConnectionHandlerBehaviour.cs.meta (100%) create mode 100644 Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerProviderAsset.cs rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect/Dialog/ConnectionHandlerProviderSO.cs.meta => Reown/Dialog/ConnectionHandlerProviderAsset.cs.meta} (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/ConnectionHandlerProviderChainSafe.cs (75%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/ConnectionHandlerProviderChainSafe.cs.meta (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/LocalWalletButton.cs (70%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/LocalWalletButton.cs.meta (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/QrCodeBuilder.cs (95%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/Dialog/QrCodeBuilder.cs.meta (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/NativeWebSocketConnectionBuilder.cs (74%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/NativeWebSocketConnectionBuilder.cs.meta (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect/WalletConnectConfigSO.cs => Reown/ReownConfigAsset.cs} (69%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect/WalletConnectConfigSO.cs.meta => Reown/ReownConfigAsset.cs.meta} (100%) create mode 100644 Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownConfigExtensions.cs rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect/WalletConnectConfigExtensions.cs.meta => Reown/ReownConfigExtensions.cs.meta} (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect/WalletConnectWeb3.cs => Reown/ReownWeb3.cs} (60%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect/WalletConnectWeb3.cs.meta => Reown/ReownWeb3.cs.meta} (100%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/WebSocketConnection.cs (90%) rename Packages/io.chainsafe.web3-unity/Runtime/Scripts/{WalletConnect => Reown}/WebSocketConnection.cs.meta (100%) delete mode 100644 Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerProviderSO.cs delete mode 100644 Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectConfigExtensions.cs create mode 100644 Packages/io.chainsafe.web3-unity/Runtime/Sprites/reown-logo.png create mode 100644 Packages/io.chainsafe.web3-unity/Runtime/Sprites/reown-logo.png.meta rename Packages/io.chainsafe.web3-unity/Tests/Runtime/{StubWalletConnectProviderConfig.cs => StubReownConfig.cs} (89%) rename Packages/io.chainsafe.web3-unity/Tests/Runtime/{StubWalletConnectProviderConfig.cs.meta => StubReownConfig.cs.meta} (100%) rename Packages/io.chainsafe.web3-unity/Tests/Runtime/{StubWalletConnectProvider.cs => StubReownProvider.cs} (83%) rename Packages/io.chainsafe.web3-unity/Tests/Runtime/{StubWalletConnectProvider.cs.meta => StubReownProvider.cs.meta} (100%) rename src/{ChainSafe.Gaming.WalletConnect/ChainSafe.Gaming.WalletConnect.csproj => ChainSafe.Gaming.Reown/ChainSafe.Gaming.Reown.csproj} (74%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown}/Connection/ConnectionHandlerConfig.cs (92%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown}/Connection/IConnectionHandler.cs (87%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown}/Connection/IConnectionHandlerProvider.cs (81%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown}/Delegates.cs (82%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown}/IConnectionHelper.cs (74%) rename src/{ChainSafe.Gaming.WalletConnect/IWalletConnectConfig.cs => ChainSafe.Gaming.Reown/IReownConfig.cs} (64%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown}/Methods/EthSendTransaction.cs (84%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown}/Methods/EthSignMessage.cs (82%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown}/Methods/EthSignTransaction.cs (77%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown}/Methods/EthSignTypedData.cs (80%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown}/Methods/WalletSwitchEthereumChain.cs (82%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown}/Models/TransactionModel.cs (87%) create mode 100644 src/ChainSafe.Gaming.Reown/Models/WalletModel.cs create mode 100644 src/ChainSafe.Gaming.Reown/RedirectionHandler.cs create mode 100644 src/ChainSafe.Gaming.Reown/ReownExtensions.cs create mode 100644 src/ChainSafe.Gaming.Reown/ReownHttpClient.cs create mode 100644 src/ChainSafe.Gaming.Reown/ReownIntegrationException.cs rename src/{ChainSafe.Gaming.WalletConnect/WalletConnectLogLevel.cs => ChainSafe.Gaming.Reown/ReownLogLevel.cs} (50%) rename src/{ChainSafe.Gaming.WalletConnect/WCLogWriter.cs => ChainSafe.Gaming.Reown/ReownLogWriter.cs} (65%) rename src/{ChainSafe.Gaming.WalletConnect/WalletConnectProvider.cs => ChainSafe.Gaming.Reown/ReownProvider.cs} (55%) rename src/{ChainSafe.Gaming.WalletConnect/WalletConnectSubCategory.cs => ChainSafe.Gaming.Reown/ReownSubCategory.cs} (54%) create mode 100644 src/ChainSafe.Gaming.Reown/Storage/ReownStorageFactory.cs create mode 100644 src/ChainSafe.Gaming.Reown/Wallets/IWalletRegistry.cs create mode 100644 src/ChainSafe.Gaming.Reown/Wallets/ReownWalletRegistry.cs rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown/Wallets}/WalletLocationOption.cs (81%) rename src/{ChainSafe.Gaming.WalletConnect => ChainSafe.Gaming.Reown/Wallets}/WalletLocationOptionsExtensions.cs (96%) create mode 100644 src/ChainSafe.Gaming.Reown/Wallets/WalletRegistryResponse.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/Models/ChainModel.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/Models/ImageUrlsModel.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/Models/WalletLinkModel.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/Models/WalletModel.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/RedirectionHandler.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/Storage/DataStorage.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/Storage/LocalData.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/WalletConnectException.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/WalletConnectExtensions.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/Wallets/IWalletRegistry.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/Wallets/WalletRegistry.cs delete mode 100644 src/ChainSafe.Gaming.WalletConnect/Wallets/WalletRegistryResponse.cs create mode 100644 src/ChainSafe.Gaming/Web3/Core/Environment/Http/HttpHeader.cs create mode 100644 src/ChainSafe.Gaming/Web3/Core/Environment/Http/HttpUtils.cs create mode 100644 src/UnitySampleProject/Assets/Resources/ReownConnectionProvider.asset rename src/UnitySampleProject/Assets/Resources/{WalletConnectConnectionProvider.asset.meta => ReownConnectionProvider.asset.meta} (64%) delete mode 100644 src/UnitySampleProject/Assets/Resources/WalletConnectConnectionProvider.asset diff --git a/ChainSafe.Gaming.sln b/ChainSafe.Gaming.sln index dcbc2726a..58c9d95e1 100644 --- a/ChainSafe.Gaming.sln +++ b/ChainSafe.Gaming.sln @@ -21,7 +21,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChainSafe.Gaming.Unity.ThirdParty", "src\ChainSafe.Gaming.Unity.ThirdParty\ChainSafe.Gaming.Unity.ThirdParty.csproj", "{9EC71CB4-9401-4E02-AC63-FC13B3D1AA53}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChainSafe.Gaming.WalletConnect", "src\ChainSafe.Gaming.WalletConnect\ChainSafe.Gaming.WalletConnect.csproj", "{99E7A645-CAC5-441B-848D-1253405D6400}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChainSafe.Gaming.Reown", "src\ChainSafe.Gaming.Reown\ChainSafe.Gaming.Reown.csproj", "{99E7A645-CAC5-441B-848D-1253405D6400}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChainSafe.Gaming.InProcessSigner", "src\ChainSafe.Gaming.InProcessSigner\ChainSafe.Gaming.InProcessSigner.csproj", "{3C01FD36-4D44-4886-A971-4786D99CBFCC}" EndProject diff --git a/ChainSafe.Gaming.sln.DotSettings b/ChainSafe.Gaming.sln.DotSettings index f1d07a668..52ba3def7 100644 --- a/ChainSafe.Gaming.sln.DotSettings +++ b/ChainSafe.Gaming.sln.DotSettings @@ -1,3 +1,4 @@  True - True \ No newline at end of file + True + True \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Editor/ConnectionHandlerEditor.cs b/Packages/io.chainsafe.web3-unity/Editor/ConnectionHandlerEditor.cs index b50d22fff..841ecaeb6 100644 --- a/Packages/io.chainsafe.web3-unity/Editor/ConnectionHandlerEditor.cs +++ b/Packages/io.chainsafe.web3-unity/Editor/ConnectionHandlerEditor.cs @@ -171,7 +171,7 @@ public override void OnInspectorGUI() _allProviders.Add(newProvider); _editorFoldouts[providerType] = true; - + providersProperty.InsertArrayElementAtIndex(providersProperty.arraySize); providersProperty.GetArrayElementAtIndex(providersProperty.arraySize - 1).objectReferenceValue = newProvider; diff --git a/Packages/io.chainsafe.web3-unity/Editor/WalletConnect.meta b/Packages/io.chainsafe.web3-unity/Editor/Reown.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Editor/WalletConnect.meta rename to Packages/io.chainsafe.web3-unity/Editor/Reown.meta diff --git a/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditor.cs b/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditor.cs new file mode 100644 index 000000000..f78c3fd0b --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditor.cs @@ -0,0 +1,10 @@ +using ChainSafe.Gaming.Reown; +using UnityEditor; + +namespace ChainSafe.Gaming.Editor.Reown +{ + [CustomEditor(typeof(ReownConfigAsset))] + public class ReownConfigEditor : ReownConfigEditorBase + { + } +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigSOEditor.cs.meta b/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditor.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigSOEditor.cs.meta rename to Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditor.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditorBase.cs b/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditorBase.cs new file mode 100644 index 000000000..8cfe568bb --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditorBase.cs @@ -0,0 +1,29 @@ +using ChainSafe.Gaming.Reown.Wallets; +using UnityEditor; +using UnityEngine; + +namespace ChainSafe.Gaming.Editor.Reown +{ + public class ReownConfigEditorBase : UnityEditor.Editor + { + public override void OnInspectorGUI() + { + base.OnInspectorGUI(); + + GUILayout.Space(10); + + using (new EditorGUILayout.HorizontalScope()) + { + if (GUILayout.Button("List Wallet Providers", GUILayout.ExpandWidth(false))) + { + ListWalletProviders(); + } + } + } + + private void ListWalletProviders() + { + Application.OpenURL(ReownWalletRegistry.RegistryUri); + } + } +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigEditor.cs.meta b/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditorBase.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigEditor.cs.meta rename to Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConfigEditorBase.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConnectionProviderEditor.cs b/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConnectionProviderEditor.cs new file mode 100644 index 000000000..5576d10fd --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConnectionProviderEditor.cs @@ -0,0 +1,10 @@ +using ChainSafe.Gaming.UnityPackage.Connection; +using UnityEditor; + +namespace ChainSafe.Gaming.Editor.Reown +{ + [CustomEditor(typeof(ReownConnectionProvider))] + public class ReownConnectionProviderEditor : ReownConfigEditorBase + { + } +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConnectionProviderEditor.cs.meta b/Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConnectionProviderEditor.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConnectionProviderEditor.cs.meta rename to Packages/io.chainsafe.web3-unity/Editor/Reown/ReownConnectionProviderEditor.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigEditor.cs b/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigEditor.cs deleted file mode 100644 index 0ab11633e..000000000 --- a/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigEditor.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.IO; -using ChainSafe.Gaming.UnityPackage.Connection; -using ChainSafe.Gaming.WalletConnect.Storage; -using ChainSafe.Gaming.WalletConnect.Wallets; -using UnityEditor; -using UnityEngine; - -namespace ChainSafe.Gaming.WalletConnect.Editor -{ - public class WalletConnectConfigEditor : UnityEditor.Editor - { - public override void OnInspectorGUI() - { - base.OnInspectorGUI(); - - GUILayout.Space(10); - - using (new EditorGUILayout.HorizontalScope()) - { - if (GUILayout.Button("List Wallet Providers", GUILayout.ExpandWidth(false))) - { - ListWalletProviders(); - } - - if (GUILayout.Button("Clear cache", GUILayout.ExpandWidth(false))) - { - DeleteStorage(); - } - } - } - - private void ListWalletProviders() - { - var config = (IWalletConnectConfig)target; - - if (string.IsNullOrWhiteSpace(config.ProjectId)) - { - Debug.LogError("Project Id required."); - return; - } - - var uri = WalletRegistry.BuildRegistryUri(config.ProjectId); - Application.OpenURL(uri); - } - - private void DeleteStorage() - { - var config = (IWalletConnectConfig)target; - - if (string.IsNullOrEmpty(config.StoragePath)) - { - Debug.LogError("StoragePath is empty."); - return; - } - - var storageFolderPath = - DataStorage.BuildStoragePath(Application.persistentDataPath, config.StoragePath); - - if (!Directory.Exists(storageFolderPath)) - { - Debug.Log("WalletConnect cache is already cleared."); - return; - } - - Directory.Delete(storageFolderPath, true); - - Debug.Log("WalletConnect cache cleared."); - } - } -} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigSOEditor.cs b/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigSOEditor.cs deleted file mode 100644 index f60f4ec1d..000000000 --- a/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConfigSOEditor.cs +++ /dev/null @@ -1,9 +0,0 @@ -using UnityEditor; - -namespace ChainSafe.Gaming.WalletConnect.Editor -{ - [CustomEditor(typeof(WalletConnectConfigSO))] - public class WalletConnectConfigSOEditor : WalletConnectConfigEditor - { - } -} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConnectionProviderEditor.cs b/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConnectionProviderEditor.cs deleted file mode 100644 index aed82d9fb..000000000 --- a/Packages/io.chainsafe.web3-unity/Editor/WalletConnect/WalletConnectConnectionProviderEditor.cs +++ /dev/null @@ -1,10 +0,0 @@ -using ChainSafe.Gaming.UnityPackage.Connection; -using UnityEditor; - -namespace ChainSafe.Gaming.WalletConnect.Editor -{ - [CustomEditor(typeof(WalletConnectConnectionProvider))] - public class WalletConnectConnectionProviderEditor : WalletConnectConfigEditor - { - } -} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Editor/Web3SettingsEditor.ChainSettings.cs b/Packages/io.chainsafe.web3-unity/Editor/Web3SettingsEditor.ChainSettings.cs index 5b28e9677..76a49e18c 100644 --- a/Packages/io.chainsafe.web3-unity/Editor/Web3SettingsEditor.ChainSettings.cs +++ b/Packages/io.chainsafe.web3-unity/Editor/Web3SettingsEditor.ChainSettings.cs @@ -40,6 +40,16 @@ public void OnGUI() EditorGUILayout.BeginHorizontal(); GUILayout.Label(title, EditorStyles.boldLabel); GUILayout.FlexibleSpace(); + if (window.IsPrimaryChain(chainConfig)) + { + GUI.enabled = false; + GUILayout.Button("Primary Chain"); + GUI.enabled = true; + } + else if (GUILayout.Button("Set as Primary")) + { + window.SetPrimaryChain(chainConfig); + } if (GUILayout.Button("Remove")) { OnRemoveClick(); diff --git a/Packages/io.chainsafe.web3-unity/Editor/Web3SettingsEditor.cs b/Packages/io.chainsafe.web3-unity/Editor/Web3SettingsEditor.cs index 526d970fb..be391366d 100644 --- a/Packages/io.chainsafe.web3-unity/Editor/Web3SettingsEditor.cs +++ b/Packages/io.chainsafe.web3-unity/Editor/Web3SettingsEditor.cs @@ -221,6 +221,22 @@ private void DrawFooter() GUILayout.Label("ChainSafe Gaming", EditorStyles.centeredGreyMiniLabel); } + private bool IsPrimaryChain(ChainConfigEntry entry) + { + return web3Config.ChainConfigs.Any() && web3Config.ChainConfigs[0] == entry; + } + + private void SetPrimaryChain(ChainConfigEntry entry) + { + var indexOf = web3Config.ChainConfigs.IndexOf(entry); + + web3Config.ChainConfigs.RemoveAt(indexOf); + web3Config.ChainConfigs.Insert(0, entry); + + InitializeChainItems(); + chainsScrollPosition = Vector2.zero; + } + private void RemoveChainConfigEntry(string chainId) { var index = web3Config.ChainConfigs.FindIndex(entry => entry.ChainId == chainId); @@ -315,9 +331,7 @@ private void OnChainListFetched() { if (web3Config.ChainConfigs.Count != 0) { - chainSettingPanels = web3Config.ChainConfigs - .Select((chainConfig) => new ChainSettingsPanel(this, chainConfig)) - .ToList(); + InitializeChainItems(); } else { @@ -332,6 +346,13 @@ private void OnChainListFetched() } } + private void InitializeChainItems() + { + chainSettingPanels = web3Config.ChainConfigs + .Select((chainConfig) => new ChainSettingsPanel(this, chainConfig)) + .ToList(); + } + private class ValidateProjectIDResponse { [JsonProperty("response")] public bool Response { get; set; } diff --git a/Packages/io.chainsafe.web3-unity/Editor/chainsafe.web3-unity.Editor.asmdef b/Packages/io.chainsafe.web3-unity/Editor/chainsafe.web3-unity.Editor.asmdef index 52bf03291..6f2a43992 100644 --- a/Packages/io.chainsafe.web3-unity/Editor/chainsafe.web3-unity.Editor.asmdef +++ b/Packages/io.chainsafe.web3-unity/Editor/chainsafe.web3-unity.Editor.asmdef @@ -1,6 +1,6 @@ { "name": "chainsafe.web3-unity.Editor", - "rootNamespace": "", + "rootNamespace": "ChainSafe.Gaming.Editor", "references": [ "GUID:5426c6b788696eb4c88f4198b59839eb" ], diff --git a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiCoordinationSystem.cs b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiCoordinationSystem.cs index d19f48372..714b4ec1d 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiCoordinationSystem.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiCoordinationSystem.cs @@ -16,16 +16,16 @@ public ScreenRecord(IGuiScreen screen) Visible = false; } } - + private readonly List activeScreens = new(); private int currentVisibleSortOrder = int.MinValue; - + public void Register(IGuiScreen screen) { activeScreens.Add(new ScreenRecord(screen)); UpdateStackVisibility(); } - + public void Unregister(IGuiScreen screen) { var record = activeScreens.Find(r => r.Screen == screen); @@ -50,11 +50,11 @@ private void UpdateStackVisibility() var opaqueScreenLayers = activeScreens .Select(r => r.Screen.Layer) .Where(l => !l.Transparent); - + var newVisibleSortOrder = opaqueScreenLayers.Any() ? opaqueScreenLayers.Max(l => l.SortOrder) : int.MinValue; - + if (newVisibleSortOrder == currentVisibleSortOrder) return; currentVisibleSortOrder = newVisibleSortOrder; @@ -62,19 +62,19 @@ private void UpdateStackVisibility() foreach (var activeScreen in activeScreens) { var show = activeScreen.Screen.Layer.SortOrder >= currentVisibleSortOrder; - + if (show && !activeScreen.Visible) { ShowScreen(activeScreen); continue; } - + if (!show && activeScreen.Visible) { HideScreen(activeScreen); continue; } - + // ignore } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiInfoOverlay.cs b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiInfoOverlay.cs index 7d6628fed..653b93758 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiInfoOverlay.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiInfoOverlay.cs @@ -11,7 +11,7 @@ public class GuiInfoOverlay : MonoBehaviour public GameObject ErrorIcon; public GameObject LoadingIcon; public Button CloseButton; - + private bool closeOnClick; private Action onClose; private Action onRelease; @@ -29,7 +29,7 @@ public void Initialize(int id, GuiOverlayType type, string message, bool closeOn this.onClose = onClose; this.closeOnClick = closeOnClick; onRelease = release; - + ErrorIcon.SetActive(type == GuiOverlayType.Error); LoadingIcon.SetActive(type == GuiOverlayType.Loading); Message.text = message; @@ -41,7 +41,7 @@ private void OnScreenClick() { return; } - + Hide(); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiLayer.cs b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiLayer.cs index 4384d9ad6..bff70c6a8 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiLayer.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiLayer.cs @@ -3,6 +3,6 @@ [CreateAssetMenu(menuName = "ChainSafe/Misc/GUI Layer", fileName = "New GUI Layer", order = 1000)] public class GuiLayer : ScriptableObject { - [field:SerializeField] public int SortOrder { get; private set; } - [field:SerializeField] public bool Transparent { get; private set; } + [field: SerializeField] public int SortOrder { get; private set; } + [field: SerializeField] public bool Transparent { get; private set; } } \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiManager.cs b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiManager.cs index a319ae115..38409c459 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiManager.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiManager.cs @@ -14,21 +14,21 @@ private static GuiManager LoadPrefab() { var prefab = Resources.Load(ResourceName); var manager = Instantiate(prefab); - + if (manager.HideInHierarchy) { manager.gameObject.hideFlags = HideFlags.HideInHierarchy; } - + DontDestroyOnLoad(manager); return manager; } - + [SerializeField] private bool HideInHierarchy = true; - [field:SerializeField] public GuiOrientationSystem Orientation { get; private set; } - [field:SerializeField] public GuiOverlayManager Overlays { get; private set; } - + [field: SerializeField] public GuiOrientationSystem Orientation { get; private set; } + [field: SerializeField] public GuiOverlayManager Overlays { get; private set; } + public GuiCoordinationSystem Coordination { get; } = new(); } } \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiOrientationSystem.cs b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiOrientationSystem.cs index d604a52b1..e04c0421a 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiOrientationSystem.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiOrientationSystem.cs @@ -7,7 +7,7 @@ public class GuiOrientationSystem : MonoBehaviour public float AspectRatioThreshold = 1f; public bool Debug; public GuiOrientation DebugOrientationValue; - + public GuiOrientation Initial { get; private set; } private void Awake() diff --git a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiOverlayManager.cs b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiOverlayManager.cs index 4fc85d51c..6858a6f9b 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiOverlayManager.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiOverlayManager.cs @@ -9,11 +9,11 @@ public class GuiOverlayManager : MonoBehaviour { public GuiScreenFactory screenFactory; public Transform container; - + private readonly List activeOverlays = new(); private ObjectPool pool; - + private int overlayCounter = 1000; // offset to detect when default integer value is sent to one of the methods private void Awake() @@ -37,7 +37,7 @@ public void Hide(int overlayId) { throw new InvalidOperationException($"There is no active Overlay with id {overlayId} to hide."); } - + overlay.Hide(); activeOverlays.Remove(overlay); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiScreen.cs b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiScreen.cs index da1e18ab2..6c8dc67fe 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiScreen.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiScreen.cs @@ -4,12 +4,12 @@ namespace ChainSafe.Gaming.GUI { public class GuiScreen : MonoBehaviour, IGuiScreen { - [field:SerializeField] public GuiLayer Layer { get; set; } - + [field: SerializeField] public GuiLayer Layer { get; set; } + public Canvas Canvas; // set layer sort order to canvas sort order? public GameObject Content; public Animation Animation; - + private void OnEnable() { GuiManager.Instance.Coordination.Register(this); @@ -33,7 +33,7 @@ public void OnShowing() { Canvas.enabled = true; Content.gameObject.SetActive(true); - + if (Animation) { Animation.Play(); @@ -44,7 +44,7 @@ public void OnHiding() { Canvas.enabled = false; Content.gameObject.SetActive(false); - + if (Animation) { Animation.Stop(); diff --git a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiScreenFactory.cs b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiScreenFactory.cs index 0da5dffba..ddfac124e 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiScreenFactory.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/GUI/GuiScreenFactory.cs @@ -17,7 +17,7 @@ public T GetSingle() singleScreen = BuildInternal(); singleScreen.gameObject.SetActive(false); } - + return singleScreen.GetComponent(); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/GUI/IGuiScreen.cs b/Packages/io.chainsafe.web3-unity/Runtime/GUI/IGuiScreen.cs index 4d10b3fef..8d8b3f9db 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/GUI/IGuiScreen.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/GUI/IGuiScreen.cs @@ -3,7 +3,7 @@ public interface IGuiScreen { GuiLayer Layer { get; } - + void OnShowing(); void OnHiding(); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect.meta b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/Predefined Wallet Button.prefab b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/Predefined Wallet Button.prefab similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/Predefined Wallet Button.prefab rename to Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/Predefined Wallet Button.prefab diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/Predefined Wallet Button.prefab.meta b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/Predefined Wallet Button.prefab.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/Predefined Wallet Button.prefab.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/Predefined Wallet Button.prefab.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/WalletConnect Dialog.prefab b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/Reown Dialog.prefab similarity index 99% rename from Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/WalletConnect Dialog.prefab rename to Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/Reown Dialog.prefab index 93eb7d2df..19edec7ac 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/WalletConnect Dialog.prefab +++ b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/Reown Dialog.prefab @@ -1027,7 +1027,7 @@ GameObject: - component: {fileID: 5250797134093199903} - component: {fileID: 8916565415885596037} m_Layer: 5 - m_Name: WalletConnect Dialog + m_Name: Reown Dialog m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/WalletConnect Dialog.prefab.meta b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/Reown Dialog.prefab.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/WalletConnect Dialog.prefab.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/Reown Dialog.prefab.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/dialog-hide.anim b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/dialog-hide.anim similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/dialog-hide.anim rename to Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/dialog-hide.anim diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/dialog-hide.anim.meta b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/dialog-hide.anim.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/dialog-hide.anim.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/dialog-hide.anim.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/dialog-show.anim b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/dialog-show.anim similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/dialog-show.anim rename to Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/dialog-show.anim diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/dialog-show.anim.meta b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/dialog-show.anim.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/dialog-show.anim.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Reown/dialog-show.anim.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Web3Unity.prefab b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Web3Unity.prefab index c55e17dc4..e2f0d3282 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Web3Unity.prefab +++ b/Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Web3Unity.prefab @@ -49,8 +49,8 @@ MonoBehaviour: providers: - {fileID: 11400000, guid: 835338196b5038d4b9351fadba9dac38, type: 2} - {fileID: 11400000, guid: e5b50e2ca9fe0504daf70376bceb84ac, type: 2} - - {fileID: 11400000, guid: 0d7bd7ae4b3e79d489bbc54514343f5c, type: 2} - {fileID: 11400000, guid: e56cb66917f860e489d3ed4480b4681c, type: 2} + - {fileID: 11400000, guid: cad6fa48701480044a2a6f2d9c9dae1e, type: 2} --- !u!114 &29625373239180716 MonoBehaviour: m_ObjectHideFlags: 0 diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/ConnectToWallet.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/ConnectToWallet.cs index f944beb42..f36cb3d8d 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/ConnectToWallet.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/ConnectToWallet.cs @@ -16,15 +16,15 @@ public class ConnectToWallet : ServiceAdapter, IWeb3InitializedHandler, ILogoutH { [SerializeField] private bool rememberMe = true; - [Space] [SerializeField] private Button connectButton; + [Space][SerializeField] private Button connectButton; [SerializeField] private Button disconnectButton; - [Space] [SerializeField] private TextMeshProUGUI addressText; + [Space][SerializeField] private TextMeshProUGUI addressText; [SerializeField] private Button copyAddressButton; - [Space] [SerializeField] private Transform connectedTransform; + [Space][SerializeField] private Transform connectedTransform; [SerializeField] private Transform disconnectedTransform; diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/ConnectionProvider.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/ConnectionProvider.cs index de6e2a04a..74b7fe875 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/ConnectionProvider.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/ConnectionProvider.cs @@ -18,22 +18,22 @@ public abstract class ConnectionProvider : ScriptableObject, IServiceAdapter /// Could be platform specific or other conditions. /// public abstract bool IsAvailable { get; } - + /// /// Icon of the button to connect to the wallet. /// public abstract Sprite ButtonIcon { get; protected set; } - + /// /// Text of the button to connect to the wallet. /// public abstract string ButtonText { get; protected set; } - + /// /// Should loading overlay be shown when initiating a connection using this ConnectionProvider; /// public abstract bool DisplayLoadingOnConnection { get; } - + protected bool RememberSession { get; private set; } /// @@ -76,13 +76,13 @@ public Web3Builder ConfigureServices(Web3Builder web3Builder) /// /// Service collection to add services to. protected abstract void ConfigureServices(IWeb3ServiceCollection services); - + /// /// Check if a saved session is available. /// /// True if a saved session is available. public abstract Task SavedSessionAvailable(); - + /// /// Handle exception thrown during connection. /// Different providers might handler it differently. diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/WalletConnectConnectionProvider.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/ReownConnectionProvider.cs similarity index 60% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/WalletConnectConnectionProvider.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/ReownConnectionProvider.cs index cf2631fb4..e44c880f1 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/WalletConnectConnectionProvider.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/ReownConnectionProvider.cs @@ -1,24 +1,29 @@ using System.Collections.Generic; using System.Threading.Tasks; -using ChainSafe.Gaming.WalletConnect; -using ChainSafe.Gaming.WalletConnect.Connection; -using ChainSafe.Gaming.WalletConnect.Dialog; +using ChainSafe.Gaming.Reown; +using ChainSafe.Gaming.Reown.Connection; +using ChainSafe.Gaming.Reown.Dialog; +using ChainSafe.Gaming.Reown.Wallets; using ChainSafe.Gaming.Web3.Build; using ChainSafe.Gaming.Web3.Evm.Wallet; +using Reown.Core; +using Reown.Core.Network; +using Reown.Core.Network.Interfaces; using UnityEngine; -using WalletConnectSharp.Core; -using WalletConnectSharp.Network.Interfaces; -using WConnectionHandler = ChainSafe.Gaming.WalletConnect.Connection.IConnectionHandler; -using UnityEngine.UI; +using ReownConnectionHandler = ChainSafe.Gaming.Reown.Connection.IConnectionHandler; namespace ChainSafe.Gaming.UnityPackage.Connection { /// - /// WalletConnect connection provider used for connecting to a wallet using WalletConnect. + /// Reown connection provider used for connecting to a wallet using Reown. /// - [CreateAssetMenu(menuName = "ChainSafe/Connection Provider/Wallet Connect", fileName = nameof(WalletConnectConnectionProvider))] - public class WalletConnectConnectionProvider : ConnectionProvider, IWalletConnectConfig, IConnectionHandlerProvider + [CreateAssetMenu(menuName = "ChainSafe/Connection Provider/Reown", fileName = nameof(ReownConnectionProvider))] + public class ReownConnectionProvider : ConnectionProvider, IReownConfig, IConnectionHandlerProvider { + [SerializeField] private ConnectionHandlerBehaviour handlerPrefab; + [SerializeField] private List includeWalletIds; + [SerializeField] private List excludeWalletIds; + [field: SerializeField] public string ProjectId { get; private set; } [field: SerializeField] public string ProjectName { get; private set; } @@ -29,49 +34,34 @@ public class WalletConnectConnectionProvider : ConnectionProvider, IWalletConnec [field: SerializeField] public Metadata Metadata { get; private set; } - [field: SerializeField] public string StoragePath { get; private set; } = "wallet-connect/"; - [field: SerializeField] public string OverrideRegistryUri { get; private set; } - [DefaultAssetValue("Packages/io.chainsafe.web3-unity/Runtime/Prefabs/Wallet Connect/WalletConnect Dialog.prefab")] - [SerializeField] private ConnectionHandlerBehaviour handlerPrefab; - - [SerializeField] private List enabledWallets; - - [SerializeField] private List disabledWallets; - - [field: SerializeField] public WalletConnectLogLevel LogLevel { get; private set; } = WalletConnectLogLevel.ErrorOnly; + [field: SerializeField] public ReownLogLevel LogLevel { get; private set; } = ReownLogLevel.ErrorOnly; [field: SerializeField] public WalletLocationOption WalletLocationOption { get; private set; } = WalletLocationOption.LocalAndRemote; - [field: SerializeField, DefaultAssetValue("Packages/io.chainsafe.web3-unity/Runtime/Sprites/Logo_WalletConnect.png")] + [field: SerializeField] public override Sprite ButtonIcon { get; protected set; } - [field: SerializeField] public override string ButtonText { get; protected set; } = "WalletConnect"; + [field: SerializeField] public override string ButtonText { get; protected set; } = "Reown"; - public override bool DisplayLoadingOnConnection => true; - private bool _storedSessionAvailable; - private ConnectionHandlerBehaviour _loadedHandler; - - public string SignMessageRpcMethodName => "personal_sign"; - public string SignTypedMessageRpcMethodName => "eth_signTypedData"; - - public IList EnabledWallets => enabledWallets; - public IList DisabledWallets => disabledWallets; - - bool IWalletConnectConfig.RememberSession => RememberSession || _storedSessionAvailable; - - public IConnectionHandlerProvider ConnectionHandlerProvider => this; + private IConnectionBuilder _connectionBuilder; public bool ForceNewSession { get; set; } + bool IReownConfig.RememberSession => RememberSession || _storedSessionAvailable; + public override bool DisplayLoadingOnConnection => true; + public IList IncludeWalletIds => includeWalletIds; + public IList ExcludeWalletIds => excludeWalletIds; + public IConnectionHandlerProvider ConnectionHandlerProvider => this; + public IRelayUrlBuilder RelayUrlBuilder => null; + public string SignMessageRpcMethodName => "personal_sign"; + public string SignTypedMessageRpcMethodName => "eth_signTypedData"; public override bool IsAvailable => true; - private IConnectionBuilder _connectionBuilder; - public IConnectionBuilder ConnectionBuilder { get @@ -105,29 +95,30 @@ public IConnectionBuilder ConnectionBuilder protected override void ConfigureServices(IWeb3ServiceCollection services) { - services.UseWalletConnect(this) - .UseWalletSigner().UseWalletTransactionExecutor(); + services.UseReown(this) + .UseWalletSigner() + .UseWalletTransactionExecutor(); } public override async Task SavedSessionAvailable() { - await using (var lightWeb3 = await WalletConnectWeb3.BuildLightweightWeb3(this)) + await using (var lightWeb3 = await ReownWeb3.BuildLightweightWeb3(this)) { - _storedSessionAvailable = lightWeb3.WalletConnect().ConnectionHelper().StoredSessionAvailable; + _storedSessionAvailable = lightWeb3.Reown().ConnectionHelper().StoredSessionAvailable; } return _storedSessionAvailable; } - public Task ProvideHandler() + public Task ProvideHandler() { if (_loadedHandler != null) { - return Task.FromResult((WConnectionHandler)_loadedHandler); + return Task.FromResult((ReownConnectionHandler)_loadedHandler); } _loadedHandler = Instantiate(handlerPrefab); - return Task.FromResult((WConnectionHandler)_loadedHandler); + return Task.FromResult((ReownConnectionHandler)_loadedHandler); } } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/ReownConnectionProvider.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/ReownConnectionProvider.cs.meta new file mode 100644 index 000000000..88ae9c564 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/ReownConnectionProvider.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: 582efc0fde77aab43a77ee4237ba305a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: + - handlerPrefab: {fileID: 5250797134093199901, guid: 0c7c312ad6c521f4b8346ed8e9d7c664, type: 3} + - k__BackingField: {fileID: 21300000, guid: 9af22e71d3035844ca8ae6e9f2a538f5, type: 3} + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/WalletConnectConnectionProvider.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/WalletConnectConnectionProvider.cs.meta deleted file mode 100644 index 339cfb980..000000000 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Connection/WalletConnectConnectionProvider.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 582efc0fde77aab43a77ee4237ba305a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/AotConfiguration.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/AotConfiguration.cs similarity index 80% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/AotConfiguration.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/AotConfiguration.cs index 66d59f08b..57d8a327f 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/AotConfiguration.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/AotConfiguration.cs @@ -1,12 +1,10 @@ using System; +using Reown.Core.Controllers; +using Reown.Sign.Models.Engine.Methods; using UnityEngine; using UnityEngine.Scripting; -using WalletConnectSharp.Core.Controllers; -using WalletConnectSharp.Events; -using WalletConnectSharp.Events.Model; -using WalletConnectSharp.Sign.Models.Engine.Methods; -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown { [Preserve] internal class AotConfiguration @@ -26,7 +24,7 @@ void SetupAOT() Debug.Log(historyFactory.JsonRpcHistoryOfType().GetType().FullName); Debug.Log(historyFactory.JsonRpcHistoryOfType().GetType().FullName); Debug.Log(historyFactory.JsonRpcHistoryOfType().GetType().FullName); - EventManager>.InstanceOf(null).PropagateEvent(null, null); + // EventManager>.InstanceOf(null).PropagateEvent(null, null); todo there is no "Events" nuget package for Reown, this might break something throw new InvalidOperationException("This method is only for AOT code generation."); } #endif diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/AotConfiguration.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/AotConfiguration.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/AotConfiguration.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/AotConfiguration.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionDialogBase.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionDialogBase.cs similarity index 91% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionDialogBase.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionDialogBase.cs index dc5b43872..854cfabba 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionDialogBase.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionDialogBase.cs @@ -2,12 +2,12 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using ChainSafe.Gaming.WalletConnect.Connection; -using ChainSafe.Gaming.WalletConnect.Models; -using ChainSafe.Gaming.WalletConnect.Storage; +using ChainSafe.Gaming.Reown.Connection; +using ChainSafe.Gaming.Reown.Models; +using ChainSafe.Gaming.Reown.Wallets; using UnityEngine; -namespace ChainSafe.Gaming.WalletConnect.Dialog +namespace ChainSafe.Gaming.Reown.Dialog { public abstract class ConnectionDialogBase : ConnectionHandlerBehaviour { @@ -60,7 +60,7 @@ public override Task ConnectUserWallet(ConnectionHandlerConfig config) SetRedirectOptionsVisible(true); var walletOptionConfigs = config.LocalWalletOptions - .Select(data => new WalletOptionConfig(data, () => OnLocalWalletButtonClick(data.Name))) + .Select(data => new WalletOptionConfig(data, () => OnLocalWalletButtonClick(data.Id))) .ToList(); SpawnRedirectOptions(walletOptionConfigs); @@ -121,11 +121,11 @@ private void ResetDialog() ClearDynamicElements(); } - private void OnLocalWalletButtonClick(string walletName) + private void OnLocalWalletButtonClick(string walletId) { try { - config.RedirectToWallet(walletName); + config.RedirectToWallet(walletId); } catch (Exception e) { diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionDialogBase.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionDialogBase.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionDialogBase.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionDialogBase.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionDialogChainSafe.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionDialogChainSafe.cs similarity index 97% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionDialogChainSafe.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionDialogChainSafe.cs index 0c06062fe..2900c5533 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionDialogChainSafe.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionDialogChainSafe.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; @@ -6,7 +5,7 @@ using UnityEngine.UI; using ZXing.QrCode; -namespace ChainSafe.Gaming.WalletConnect.Dialog +namespace ChainSafe.Gaming.Reown.Dialog { public class ConnectionDialogChainSafe : ConnectionDialogBase { diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionDialogChainSafe.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionDialogChainSafe.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionDialogChainSafe.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionDialogChainSafe.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerBehaviour.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerBehaviour.cs similarity index 74% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerBehaviour.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerBehaviour.cs index 55d69c6a9..d159f2e2f 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerBehaviour.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerBehaviour.cs @@ -1,8 +1,8 @@ using System.Threading.Tasks; -using ChainSafe.Gaming.WalletConnect.Connection; +using ChainSafe.Gaming.Reown.Connection; using UnityEngine; -namespace ChainSafe.Gaming.WalletConnect.Dialog +namespace ChainSafe.Gaming.Reown.Dialog { public abstract class ConnectionHandlerBehaviour : MonoBehaviour, IConnectionHandler { diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerBehaviour.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerBehaviour.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerBehaviour.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerBehaviour.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerProviderAsset.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerProviderAsset.cs new file mode 100644 index 000000000..c364046f5 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerProviderAsset.cs @@ -0,0 +1,11 @@ +using System.Threading.Tasks; +using ChainSafe.Gaming.Reown.Connection; +using UnityEngine; + +namespace ChainSafe.Gaming.Reown.Dialog +{ + public abstract class ConnectionHandlerProviderAsset : ScriptableObject, IConnectionHandlerProvider + { + public abstract Task ProvideHandler(); + } +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerProviderSO.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerProviderAsset.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerProviderSO.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerProviderAsset.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerProviderChainSafe.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerProviderChainSafe.cs similarity index 75% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerProviderChainSafe.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerProviderChainSafe.cs index b6d72e966..75fca54e7 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerProviderChainSafe.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerProviderChainSafe.cs @@ -1,15 +1,15 @@ using System.Threading.Tasks; -using ChainSafe.Gaming.WalletConnect.Connection; +using ChainSafe.Gaming.Reown.Connection; using UnityEngine; -namespace ChainSafe.Gaming.WalletConnect.Dialog +namespace ChainSafe.Gaming.Reown.Dialog { /// /// Simple version of connection handler provider. /// Lacking Pool functionality and loading from Addressables. /// - [CreateAssetMenu(menuName = "ChainSafe/WalletConnect/Connection Handler Provider", fileName = "ConnectionHandlerProvider", order = 0)] - public class ConnectionHandlerProviderChainSafe : ConnectionHandlerProviderSO + [CreateAssetMenu(menuName = "ChainSafe/Reown/Connection Handler Provider", fileName = "ConnectionHandlerProvider", order = 0)] + public class ConnectionHandlerProviderChainSafe : ConnectionHandlerProviderAsset { [SerializeField] private ConnectionHandlerBehaviour handlerPrefab; diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerProviderChainSafe.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerProviderChainSafe.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerProviderChainSafe.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/ConnectionHandlerProviderChainSafe.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/LocalWalletButton.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/LocalWalletButton.cs similarity index 70% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/LocalWalletButton.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/LocalWalletButton.cs index dc7dc54f0..205fd0d76 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/LocalWalletButton.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/LocalWalletButton.cs @@ -1,12 +1,12 @@ using System; using System.Threading.Tasks; -using ChainSafe.Gaming.WalletConnect.Models; +using ChainSafe.Gaming.Reown.Models; using TMPro; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; -namespace ChainSafe.Gaming.WalletConnect.Dialog +namespace ChainSafe.Gaming.Reown.Dialog { public class LocalWalletButton : MonoBehaviour { @@ -28,20 +28,20 @@ public async void Set(WalletModel data, Action onClick) IconStub.gameObject.SetActive(true); Icon.gameObject.SetActive(false); - if (data.Images == null || string.IsNullOrEmpty(data.Images.SmallUrl)) - { - return; - } - - var icon = await DownloadIcon(data.Images.SmallUrl); - if (icon == null) - { - return; - } - - Icon.sprite = icon; - Icon.gameObject.SetActive(true); - IconStub.gameObject.SetActive(false); + // if (data.Images == null || string.IsNullOrEmpty(data.Images.SmallUrl)) // todo implement image downloading + // { + // return; + // } + // + // var icon = await DownloadIcon(data.Images.SmallUrl); + // if (icon == null) + // { + // return; + // } + // + // Icon.sprite = icon; + // Icon.gameObject.SetActive(true); + // IconStub.gameObject.SetActive(false); } private static async Task DownloadIcon(string url) diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/LocalWalletButton.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/LocalWalletButton.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/LocalWalletButton.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/LocalWalletButton.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/QrCodeBuilder.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/QrCodeBuilder.cs similarity index 95% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/QrCodeBuilder.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/QrCodeBuilder.cs index c35ffa6a4..e461cfd05 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/QrCodeBuilder.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/QrCodeBuilder.cs @@ -2,7 +2,7 @@ using ZXing; using ZXing.QrCode; -namespace ChainSafe.Gaming.WalletConnect.Dialog +namespace ChainSafe.Gaming.Reown.Dialog { public class QrCodeBuilder { diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/QrCodeBuilder.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/QrCodeBuilder.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/QrCodeBuilder.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/Dialog/QrCodeBuilder.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/NativeWebSocketConnectionBuilder.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/NativeWebSocketConnectionBuilder.cs similarity index 74% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/NativeWebSocketConnectionBuilder.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/NativeWebSocketConnectionBuilder.cs index b42f49f63..312d3c229 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/NativeWebSocketConnectionBuilder.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/NativeWebSocketConnectionBuilder.cs @@ -1,21 +1,19 @@ - using System.Threading.Tasks; -using ChainSafe.Gaming.Evm.Unity; +using Reown.Core.Network; +using Reown.Core.Network.Interfaces; using UnityEngine; -using WalletConnectSharp.Network; -using WalletConnectSharp.Network.Interfaces; -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown { /// - /// This is a custom connection builder for Wallet Connect. + /// This is a custom connection builder for Reown. /// We need this because of Unity's IL2CPP build code stripping and reachability issue. /// For version 2022 and above this issue has been fixed by Unity as stated here https://blog.unity.com/engine-platform/il2cpp-full-generic-sharing-in-unity-2022-1-beta so this custom implementation isn't needed. /// public class NativeWebSocketConnectionBuilder : MonoBehaviour, IConnectionBuilder { /// - /// Create WebSocket connection for Wallet Connect. + /// Create WebSocket connection for Reown. /// /// /// Created connection. diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/NativeWebSocketConnectionBuilder.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/NativeWebSocketConnectionBuilder.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/NativeWebSocketConnectionBuilder.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/NativeWebSocketConnectionBuilder.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectConfigSO.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownConfigAsset.cs similarity index 69% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectConfigSO.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownConfigAsset.cs index 42f70cdc4..cdca5a59e 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectConfigSO.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownConfigAsset.cs @@ -1,35 +1,41 @@ using System.Collections.Generic; -using ChainSafe.Gaming.WalletConnect.Connection; -using ChainSafe.Gaming.WalletConnect.Dialog; +using ChainSafe.Gaming.Reown.Connection; +using ChainSafe.Gaming.Reown.Dialog; +using ChainSafe.Gaming.Reown.Wallets; +using Reown.Core; +using Reown.Core.Network; +using Reown.Core.Network.Interfaces; using UnityEngine; -using WalletConnectSharp.Core; -using WalletConnectSharp.Network.Interfaces; -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown { - [CreateAssetMenu(menuName = "ChainSafe/WalletConnect/WalletConnect Config", fileName = "WalletConnectConfig", order = 0)] - public class WalletConnectConfigSO : ScriptableObject, IWalletConnectConfig + [CreateAssetMenu(menuName = "ChainSafe/Reown/Reown Config", fileName = "ReownConfig", order = 0)] + public class ReownConfigAsset : ScriptableObject, IReownConfig { public string SignMessageRpcMethodName => "personal_sign"; public string SignTypedMessageRpcMethodName => "eth_signTypedData"; + [SerializeField] private List includeWalletIds; + [SerializeField] private List excludeWalletIds; + [field: SerializeField] public bool AutoRenewSession { get; set; } = true; [field: SerializeField] public string ProjectName { get; set; } [field: SerializeField] public string ProjectId { get; set; } [field: SerializeField] public string BaseContext { get; set; } = "unity-game"; [field: SerializeField] public Metadata Metadata { get; set; } + [field: SerializeField] public string StoragePath { get; set; } = "wallet-connect/"; [field: SerializeField] public string OverrideRegistryUri { get; set; } - [field: SerializeField] public WalletConnectLogLevel LogLevel { get; set; } = WalletConnectLogLevel.ErrorOnly; - [SerializeField] private List enabledWallets; - [SerializeField] private List disabledWallets; - [SerializeField] private ConnectionHandlerProviderSO connectionHandlerProvider; + [field: SerializeField] public ReownLogLevel LogLevel { get; set; } = ReownLogLevel.ErrorOnly; + [SerializeField] private ConnectionHandlerProviderAsset connectionHandlerProvider; [field: SerializeField] public WalletLocationOption WalletLocationOption { get; set; } public bool RememberSession { get; set; } public bool ForceNewSession { get; set; } - public IList EnabledWallets => enabledWallets; - public IList DisabledWallets => disabledWallets; + public IRelayUrlBuilder RelayUrlBuilder => null; // todo; + + public IList IncludeWalletIds => includeWalletIds; + public IList ExcludeWalletIds => excludeWalletIds; public IConnectionHandlerProvider ConnectionHandlerProvider => connectionHandlerProvider; private IConnectionBuilder connectionBuilder; diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectConfigSO.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownConfigAsset.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectConfigSO.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownConfigAsset.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownConfigExtensions.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownConfigExtensions.cs new file mode 100644 index 000000000..9b84871c6 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownConfigExtensions.cs @@ -0,0 +1,31 @@ +using ChainSafe.Gaming.UnityPackage.Connection; + +namespace ChainSafe.Gaming.Reown +{ + public static class ReownConfigExtensions + { + /// + /// Sets property of this config object. + /// + /// The config object. + /// New value for ForceNewSession property. + /// Updated object. + public static ReownConnectionProvider WithForceNewSession(this ReownConnectionProvider provider, bool forceNewSession) + { + provider.ForceNewSession = forceNewSession; + return provider; + } + + /// + /// Sets property of this config object. + /// + /// The config object. + /// New value for ForceNewSession property. + /// Updated object. + public static ReownConfigAsset WithForceNewSession(this ReownConfigAsset config, bool forceNewSession) + { + config.ForceNewSession = forceNewSession; + return config; + } + } +} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectConfigExtensions.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownConfigExtensions.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectConfigExtensions.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownConfigExtensions.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectWeb3.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownWeb3.cs similarity index 60% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectWeb3.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownWeb3.cs index fba83c645..329dd37e8 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectWeb3.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownWeb3.cs @@ -1,25 +1,24 @@ using System.Threading.Tasks; -using ChainSafe.Gaming.EVM.Events; using ChainSafe.Gaming.Evm.JsonRpc; using ChainSafe.Gaming.UnityPackage; using ChainSafe.Gaming.Web3; using ChainSafe.Gaming.Web3.Build; using ChainSafe.Gaming.Web3.Unity; -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown { /// - /// Helper class to build preconfigured Web3 clients for WalletConnect. + /// Helper class to build preconfigured Web3 clients for Reown. /// - public static class WalletConnectWeb3 + public static class ReownWeb3 { /// - /// Builds a lightweight Web3 client with basic WalletConnect functionality. + /// Builds a lightweight Web3 client with basic Reown functionality. /// - /// Your WalletConnect config. + /// Your Reown config. /// ChainSafe SDK project configuration (optional). - /// A lightweight version of Web3 client with basic WalletConnect functionality. - public static ValueTask BuildLightweightWeb3(IWalletConnectConfig wcConfig, ICompleteProjectConfig projectConfig = null) + /// A lightweight version of Web3 client with basic Reown functionality. + public static ValueTask BuildLightweightWeb3(IReownConfig reownConfig, ICompleteProjectConfig projectConfig = null) { projectConfig ??= ProjectConfigUtilities.Load(); @@ -27,7 +26,7 @@ public static class WalletConnectWeb3 { services.UseUnityEnvironment(); services.UseRpcProvider(); - services.UseWalletConnect(wcConfig); + services.UseReown(reownConfig); }).LaunchAsync(); } } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectWeb3.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownWeb3.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectWeb3.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/ReownWeb3.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WebSocketConnection.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/WebSocketConnection.cs similarity index 90% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WebSocketConnection.cs rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/WebSocketConnection.cs index f5ac9d18b..f19745ba9 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WebSocketConnection.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/WebSocketConnection.cs @@ -1,25 +1,18 @@ - using System; using System.IO; -using System.Text; using System.Threading.Tasks; using ChainSafe.Gaming.Evm.Unity; using NativeWebSocket; using Newtonsoft.Json; -using UnityEngine; -using WalletConnectSharp.Common; -using WalletConnectSharp.Common.Logging; -using WalletConnectSharp.Common.Utils; -using WalletConnectSharp.Events; -using WalletConnectSharp.Events.Model; -using WalletConnectSharp.Network; -using WalletConnectSharp.Network.Models; -using WalletConnectSharp.Network.Websocket; - -namespace ChainSafe.Gaming.WalletConnect +using Reown.Core.Common; +using Reown.Core.Common.Logging; +using Reown.Core.Network; +using Reown.Core.Network.Models; + +namespace ChainSafe.Gaming.Reown { /// - /// Custom web socket implementation for Wallet Connect, based on NativeWebSocket https://github.com/endel/NativeWebSocket. + /// Custom web socket implementation for Reown, based on NativeWebSocket https://github.com/endel/NativeWebSocket. /// public class WebSocketConnection : IJsonRpcConnection, IModule { @@ -88,7 +81,7 @@ async Task IJsonRpcConnection.Close() if (_disposed) throw new ObjectDisposedException(nameof(WebSocketConnection)); - WCLogger.Log("Closing websocket due to Close() being called"); + ReownLogger.Log("Closing websocket due to Close() being called"); await _socket.Close(); OnClose(WebSocketCloseCode.Normal); @@ -105,7 +98,7 @@ async Task IJsonRpcConnection.SendRequest(IJsonRpcRequest requestPayload, try { var json = JsonConvert.SerializeObject(requestPayload); - WCLogger.Log($"[WebSocketConnection-{Context}] Sending request {json}"); + ReownLogger.Log($"[WebSocketConnection-{Context}] Sending request {json}"); await _socket.SendText(json); @@ -206,7 +199,7 @@ private void OnMessage(byte[] data) { var json = System.Text.Encoding.UTF8.GetString(data); - WCLogger.Log($"[WebSocketConnection-{Context}] Got payload: \n{json}"); + ReownLogger.Log($"[WebSocketConnection-{Context}] Got payload: \n{json}"); if (string.IsNullOrWhiteSpace(json)) return; @@ -225,7 +218,7 @@ private void OnDisconnect(WebSocketCloseCode obj) private void OnError(string message) { ErrorReceived?.Invoke(this, new Exception(message)); - WCLogger.LogError(Connecting + ReownLogger.LogError(Connecting ? $"[{Name}-{Context}] Error happened during connection. Make sure Project ID is valid. Error message: {message}" : $"[{Name}-{Context}] Error: {message}"); } @@ -247,7 +240,7 @@ private void OnError(IJsonRpcPayload ogPayload, Exception e) PayloadReceived?.Invoke(this, json); } - WCLogger.LogError(e); + ReownLogger.LogError(e); } private void OnClose(WebSocketCloseCode obj) diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WebSocketConnection.cs.meta b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/WebSocketConnection.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WebSocketConnection.cs.meta rename to Packages/io.chainsafe.web3-unity/Runtime/Scripts/Reown/WebSocketConnection.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Samples/Samples.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Samples/Samples.cs index a1c8db595..db8bb9af7 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Samples/Samples.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Samples/Samples.cs @@ -85,7 +85,7 @@ private async void TryExecute(MethodInfo method, ISample instance) || e is ServiceNotBoundWeb3Exception) { Web3Unity.ConnectScreen.Open(); - + throw new AggregateException(new Web3Exception("Connection not found. Please connect your wallet first."), e); } diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/UI/ConnectScreen.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/UI/ConnectScreen.cs index 0f8240eb7..e597aee49 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/UI/ConnectScreen.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/UI/ConnectScreen.cs @@ -15,7 +15,7 @@ public class ConnectScreen : MonoBehaviour [SerializeField] private RectTransform providerContainer; [SerializeField] private ConnectionProviderButton providerButtonPrefab; [SerializeField] private Button closeButton; - + private int loadingOverlayId; private void Awake() @@ -39,7 +39,7 @@ async void ConnectClicked(ConnectionProvider provider) await TryConnect(provider); } } - + /// /// Try to Connect and displays error and throws exception on a failed attempt. /// @@ -60,7 +60,7 @@ private async Task TryConnect(ConnectionProvider provider) { DisplayError( "Connection failed, please try again."); - + Debug.LogException(e); } } @@ -82,7 +82,7 @@ public void Close() { gameObject.SetActive(false); } - + /// /// Display Error. /// @@ -101,7 +101,7 @@ private void ShowLoading(string message) DisableButtons(); loadingOverlayId = GuiManager.Instance.Overlays.Show(GuiOverlayType.Loading, message, false, EnableButtons); } - + /// /// Hide Loading overlay. /// diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/UI/ConnectionProviderButton.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/UI/ConnectionProviderButton.cs index 2bd351273..3b27d811e 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/UI/ConnectionProviderButton.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/UI/ConnectionProviderButton.cs @@ -10,7 +10,7 @@ public class ConnectionProviderButton : MonoBehaviour public Image Icon; public TMP_Text Text; public Button Button; - + private Action onClick; private void Awake() diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerProviderSO.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerProviderSO.cs deleted file mode 100644 index 9d880667c..000000000 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/Dialog/ConnectionHandlerProviderSO.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Threading.Tasks; -using ChainSafe.Gaming.WalletConnect.Connection; -using UnityEngine; - -namespace ChainSafe.Gaming.WalletConnect.Dialog -{ - public abstract class ConnectionHandlerProviderSO : ScriptableObject, IConnectionHandlerProvider - { - public abstract Task ProvideHandler(); - } -} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectConfigExtensions.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectConfigExtensions.cs deleted file mode 100644 index ffc63ac3f..000000000 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/WalletConnect/WalletConnectConfigExtensions.cs +++ /dev/null @@ -1,20 +0,0 @@ -using ChainSafe.Gaming.UnityPackage.Connection; -using UnityEngine; - -namespace ChainSafe.Gaming.WalletConnect -{ - public static class WalletConnectConfigExtensions - { - /// - /// Sets property of this config object. - /// - /// The config object. - /// New value for ForceNewSession property. - /// Updated object. - public static WalletConnectConnectionProvider WithForceNewSession(this WalletConnectConnectionProvider provider, bool forceNewSession) - { - provider.ForceNewSession = forceNewSession; - return provider; - } - } -} \ No newline at end of file diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Web3Unity.cs b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Web3Unity.cs index d41132293..61225ad00 100644 --- a/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Web3Unity.cs +++ b/Packages/io.chainsafe.web3-unity/Runtime/Scripts/Web3Unity.cs @@ -74,7 +74,7 @@ public static ConnectScreen ConnectScreen } [SerializeField] private GuiScreenFactory connectScreenFactory; - + private CWeb3 _web3; private ConnectionHandler _connectionHandler; private ConnectScreen _connectScreen; @@ -272,7 +272,7 @@ public Task OnWeb3Initialized(CWeb3 web3) { _connectScreen.Close(); } - + Web3Initialized?.Invoke((_web3, _web3.ServiceProvider.GetService(typeof(ISigner)) == null)); return Task.CompletedTask; diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Sprites/reown-logo.png b/Packages/io.chainsafe.web3-unity/Runtime/Sprites/reown-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..58282b63ef51efba8f59c88a93ae2e68549a8f75 GIT binary patch literal 4453 zcmds4`8$;D+n>djeT&JyG_ubOvWGNA*0N?DhRBv=5b?;6NtP)+hS5Vp$dD{OS%;A= z89cH^mbS5n$dc`Q_q^ZtINrbE{o%UrBV6;dyn+w#CO%)oH(519bg6t$1&?CJ;yDYj~9^iL^)g25o z1Ubx5=aryXDQ5tCJZJ@yE&7R4Pw=I;5%~Gl-=L;VmA35f*M7w)aXauG2uA0=KN2KC z%oFNScW@%g-`-onEwjbDv>4iRIt~Tjm@Mn=b5QmHPet3M5<#>63?G=ky5*NY9w%wM11i>K_;BxWl=wSz{b$^3fCni7v)$A=ZWLbGS1IQGFlUo zO?doU*d_IkO^2=EobNK?Dz1w8U-&uN*z-;7h~psjM?~E1^9b@=1DzjgxR$U@FX)Ww zaAV8U9Luly;(IVAPYZr?7KBym&}#uae* zBuWy5#!yJzX>etwIr@x!eCr60h2Tl&{q84)L%&cqZK?*oz?2tD1W)1R9Zqas8)@7l z)4iB6++-jF>5ZtmyMZjf`c7u1?HYyECajfHb1a{I>t+acm&=~Eby$e3`2At}%ZOm9 z6kfQDI^t_2@}%!bdAUR|D)d=4l0EN!*V%(O(tbr%j^#unj*J|ok2@4lHMlE5MKLQX zx670B#hp*ou{ZAhO`kE`IY}FNGr-e_+|Ntva(Xr2Sg=qcwd(EMtHoGKu1sRpAvo!6 z3(!WsDpXstkICuG`oR4M|IkJw&bpp3Ec8`3SGFFe_%<(;sAuR`w=XJsbZhFpPQxz! zNVom2oDx*oTjRN9pL15f5yZ9r!0K;({s?`}oJ=deAuG>B zH;vqM`bn~r^{liWl zRGg7?M@NT*eniUQ{*KUtE>s+GSXPur33oSfad8pn?VaF_eB0T{^0*YGt&O>UU9G>r zAGAQM4?3J_5-Y5Xh=`cm*+0Po33yB#oc9e6e^gqkAQiuhqgTF;DHoI{3NX=fnI^+p zRUVCR8u9bbD=SY+J%IW<*^Ea{PEP)#m4TK6Q%W~DePD$$O-)S=_<3HVf(K|h0uF{Q zwv&ooK|Ox_cqNK7&fmcilWDE6DtKBdZS!b<&A|>e-Bz)z|0#@;Z*a@r!2#Hd1(|_g z+EP;YYPEK9B6~_&ofcHZwotaWqb~jJ>MutW`0*yFCHQgoP_g+bNlCL|tq9Ma`As0O z?q5Hb0|Nr8kJrpvVw_BeYN)=yvtk^dx3m-_c>nGpzl=!Q(Bx!l)w2B?jzqu2)>fk` zuQpp5ewoaRPnY$DgoIQ*o3dWN*1lJ)dd>$Xi>Op~RTQq32GJvYkN4&a%Brdc)Ni(= z!Z4JReZtOD-_j7Ra~*uf&uVKmt~XaLuS_@Zw64Vnpwf{lnpUY*RqCPBO@3E;DqC~N zDp!7dPD4ztN+{u2{4CV`fHbY|#RbBF=y3bntH8!1!|=3Z80KxNUm};N`uawX^wb4h zgy)&eib zY`K$cdj46IBe4V5)ZASD{JBi7^<Iv=ve;o+f2TYP?MD(95y zMs(ifq#OJf)?T24L+?bg>9*EYPzMsA9gGWH_65GAq z?)k}OdJjH17kKOdMx{R#=ws=5AU$94veojhI_b17ml_{dgQ%7Dhyp8xPNXTO@_bg| z<%L!-836n@$8ImkHro^fyumpGcryTQxx5MxsBvM$hch?#ChD#|2ruCRV&--!u}~EL z3?yMUj``Vi>@uZC`cB>p_j<_ip%zt!D4-#jfdQyqvyWBvMav09txk3onWY&TYv>69 zhvw;%D6`ESe)wVuW}+%mTv|#T8*~1a?j!r#kTaR%UPn}K(X#%RFJD3?stH6Qn@L6? zQqyiNHQBX>>M|R*$wQ;j9Isp{%djSO`K-*)+%1Y-p2vQBQ@ORht)Z(Mz?VD}ncv%M zk&W=OwX#YZ{-g(xq`GDjo}Zr|c&I+sk|TjIL6_iq` z@3e`2PXK=ViSLW}zzAqL9OCWx^mPB~RQ+#!NdUgiFR}fvuTM#kMq&VKP<&g#RgFLd z*Z}WDku->^zS=7|g{BsLCv)xG++J~2$F>CMY`^IB866#cRbOu)`9uYPT-*GC)Zg+CnDMw#?)N#Kgs2>-;l5CMij1rdKVpK)_Tg6{th6?u=G` zi#>=pmho4DJ4fCM3wwBU6yF?SF+DammhCK9PV&t-LcfpW6nfCJ+6Exhd=w(9Qy$@h zSpW)SKtPI#j5p%FXj)hFdOQ1vMtoV>?2g7235WCJ3dT>(g0#B2 zVJu_}$sMa!%VhfhhT2f%mcHZooD11{`0Ui_$E7$JTf!kmW%<~L^4{C2#^`X%VW7bH zlAmA6xwWp_&q8>Thj^4cRV6g74W-UV@M>ykJkk#BMRH>>7~rDq&_d5EN@bT8UQPjW z5fmJJopwe+!KFD$&HZ(V!0NR*3XZ$uX=7t(qWQ7jPh90SxZ$1<2V9h6guwCJ#al)OZW@fP4YqK{H;oymi zA8k7`u^}HD?DlGWHE%lJAHn=Vb*<#p$cg??ch^+5ySsbEe3yvh=e<`x>p0k*A--w{ zdZR_6X7<7~Gvu>~g@v-ee*JQ3iLN>K%4=Bb^M>w=X7_JBK_VU-o4^{M?DvI%VrOjg z=9v9|?Hn7DaStS=0ZU>E`WsZ?{4#3$e!ftrfNLyD1+ks3UD>^`vMYHI-F5A`>s zot&Ju6*mAPzP>SQi-cvF_qvAJ7^nBGhZu7=6cq%w%Nfh3A~%Ok-g0u0s z_3&Gcjg^aJRm~?=k4_}Z!_#FLU`a}tKF5Fm=L!*X24%%zry95TX(QhZP>jQL=7jp~ z^1kQ1+y;`#eGPy8s~m1c&Jl<08q(V(rpyqLr$z`Bw&tHS*uq0ZX(N6n?CN^J(%sWN zQGh})8X{=^p0xcRKNf1a)`hJ?T9REhl*Y*4t6ONlSoSl+{08I3q|?pLCka0^30UhQV+371&tVPca_j z*vc`G6Rjq{sd9G$G@+V~zpaeHi3svpiTTCS^=DTA3EY6t@y|wrf|2*`IA$v;o;k%n z_Gj#Yi?$=6w>6lUQl)oLdSN*FE98iNz<>n(uT+HcgN~pf$~Q0DhD%MD9zA$eSD1)Z zM*UWuu!N>^gu0Ta2Wdm?GM|UaXVia%YDh(Q9Pa`5nwm;hXG@jOW7d|6f0eCApDK+@ zLe(FwJ}1MBBtsB@px498yOUMP#^9I2vNC0Q+%0az&1j&5(6yFo%v>{#e`zBbCX0t{ z>c1n10#dc(Yp(d7n8N+VRW9BYet0o|2gne701Z(5+UNIKe(nsT&9@e&%0hE2n)|32f%;KFf%46=C~z5K z%2RONqbUXq$oDZTI5S^7IU8AC37vts&Bs2K`-ioKH;x%0;~MrSR@pA=qhj~6x)C%A zIzfugLtKKa)r7y!E#F)=7hO0FT-0VMjAi^ob*8In^1Ji|7Sy>3`i>H+jD zz2U{e#G2=9lLQ)F-8)8r6eEtmU(73WSFe6XCCe1(T&zN~-XjC&!B1GUp|j92NCoPS zU2vJvA%*9&9m7ccX_n_r2rIWCaeQ`i z8RS@O*I{xEH4#}ftFp@1;JNH)QE}UMpq3v5Y6ETWN}=Cv^B-bg{6qR#`;1IOopGID zr7TJlq<=}FIkBK8`0Bi<@*Fr~u2kpoBl0Pe6>~J}yE@U7cs|j|LTq+RLi0?3g#KC{aI+^{d$6N_m?gS&98vltK~Yac4JZC&hJ&gA`|q*xgJAw; zRwAK{aGjni9M6OonTM~jTA~M;!J;n!AJ<34SNTDjtn{6PpY%1z4&;{L^^IRIkEhQ^ zB!r|dC{_B>k0Hkww#e2uAZ2eS_9jIFUt_Z=OBqpIAc5Q@LrE6l%q%4kn%e=C0xJda qqpZO)J`{*aCz3TG1;+^z=nw|U5&xerIOf|AOAtx4G=KSjN&X*{P#bmt literal 0 HcmV?d00001 diff --git a/Packages/io.chainsafe.web3-unity/Runtime/Sprites/reown-logo.png.meta b/Packages/io.chainsafe.web3-unity/Runtime/Sprites/reown-logo.png.meta new file mode 100644 index 000000000..98b0937a4 --- /dev/null +++ b/Packages/io.chainsafe.web3-unity/Runtime/Sprites/reown-logo.png.meta @@ -0,0 +1,127 @@ +fileFormatVersion: 2 +guid: 9af22e71d3035844ca8ae6e9f2a538f5 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 13 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + flipGreenChannel: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + vTOnly: 0 + ignoreMipmapLimit: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 1 + aniso: 1 + mipBias: 0 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: WebGL + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/io.chainsafe.web3-unity/Tests/Runtime/EvmCustomResponseTests.cs b/Packages/io.chainsafe.web3-unity/Tests/Runtime/EvmCustomResponseTests.cs index b7e303344..b61140bee 100644 --- a/Packages/io.chainsafe.web3-unity/Tests/Runtime/EvmCustomResponseTests.cs +++ b/Packages/io.chainsafe.web3-unity/Tests/Runtime/EvmCustomResponseTests.cs @@ -177,7 +177,7 @@ private IEnumerator BuildWeb3WithTestResponse(string testResponse) { var buildWeb3Task = SampleTestsBase.BuildTestWeb3(services => { - services.Replace(ServiceDescriptor.Singleton(new StubWalletConnectProviderConfig + services.Replace(ServiceDescriptor.Singleton(new StubReownConfig { StubResponse = testResponse })); }); diff --git a/Packages/io.chainsafe.web3-unity/Tests/Runtime/SampleTestsBase.cs b/Packages/io.chainsafe.web3-unity/Tests/Runtime/SampleTestsBase.cs index 1ef2a3b8d..ae68f9988 100644 --- a/Packages/io.chainsafe.web3-unity/Tests/Runtime/SampleTestsBase.cs +++ b/Packages/io.chainsafe.web3-unity/Tests/Runtime/SampleTestsBase.cs @@ -5,7 +5,6 @@ using ChainSafe.Gaming.Evm.JsonRpc; using ChainSafe.Gaming.MultiCall; using ChainSafe.Gaming.UnityPackage; -using ChainSafe.Gaming.WalletConnect; using ChainSafe.Gaming.Web3; using ChainSafe.Gaming.Web3.Build; using ChainSafe.Gaming.Web3.Evm.Wallet; @@ -64,9 +63,9 @@ internal static ValueTask BuildTestWeb3(Web3Builder.ConfigureServicesDeleg services.UseMultiCall(); services.UseRpcProvider(); - var config = new StubWalletConnectProviderConfig(); + var config = new StubReownConfig(); services.AddSingleton(config); // can be replaced - services.UseWalletProvider(config); + services.UseWalletProvider(config); services.UseWalletSigner(); services.UseWalletTransactionExecutor(); services.UseEvents(); diff --git a/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProviderConfig.cs b/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubReownConfig.cs similarity index 89% rename from Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProviderConfig.cs rename to Packages/io.chainsafe.web3-unity/Tests/Runtime/StubReownConfig.cs index ab0ed0823..a7d25d3d7 100644 --- a/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProviderConfig.cs +++ b/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubReownConfig.cs @@ -2,7 +2,7 @@ namespace Tests.Runtime { - public class StubWalletConnectProviderConfig : IWalletProviderConfig + public class StubReownConfig : IWalletProviderConfig { public const string DefaultWalletAddress = "0x55ffe9E30347266f02b9BdAe20aD3a86493289ea"; public const string DefaultProjectId = "f4bff60eb260841f46b1c77588cd8acb"; diff --git a/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProviderConfig.cs.meta b/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubReownConfig.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProviderConfig.cs.meta rename to Packages/io.chainsafe.web3-unity/Tests/Runtime/StubReownConfig.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProvider.cs b/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubReownProvider.cs similarity index 83% rename from Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProvider.cs rename to Packages/io.chainsafe.web3-unity/Tests/Runtime/StubReownProvider.cs index 26857b6cd..0fa0dc96a 100644 --- a/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProvider.cs +++ b/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubReownProvider.cs @@ -9,13 +9,13 @@ namespace Tests.Runtime { - public class StubWalletConnectProvider : WalletProvider + public class StubReownProvider : WalletProvider { - private readonly StubWalletConnectProviderConfig config; + private readonly StubReownConfig config; private readonly IChainConfig chainConfig; private readonly IHttpClient httpClient; - public StubWalletConnectProvider(StubWalletConnectProviderConfig config, Web3Environment environment, IChainConfig chainConfig) : base(environment, chainConfig) + public StubReownProvider(StubReownConfig config, Web3Environment environment, IChainConfig chainConfig) : base(environment, chainConfig) { this.config = config; this.chainConfig = chainConfig; @@ -42,7 +42,7 @@ public override async Task Request(string method, params object[] paramete case "eth_sendTransaction": return (T)Convert.ChangeType(config.StubResponse, typeof(T)); default: - // Direct RPC request via WalletConnect RPC url. + // Direct RPC request via Reown RPC url. // Using WalletConnect Blockchain API: https://docs.walletconnect.com/cloud/blockchain-api var url = $"https://rpc.walletconnect.com/v1?chainId=eip155:{chainConfig.ChainId}&projectId={config.ProjectId}"; diff --git a/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProvider.cs.meta b/Packages/io.chainsafe.web3-unity/Tests/Runtime/StubReownProvider.cs.meta similarity index 100% rename from Packages/io.chainsafe.web3-unity/Tests/Runtime/StubWalletConnectProvider.cs.meta rename to Packages/io.chainsafe.web3-unity/Tests/Runtime/StubReownProvider.cs.meta diff --git a/Packages/io.chainsafe.web3-unity/Tests/Runtime/chainsafe.web3-unity.RuntimeTests.asmdef b/Packages/io.chainsafe.web3-unity/Tests/Runtime/chainsafe.web3-unity.RuntimeTests.asmdef index 017811d11..46a5d29c2 100644 --- a/Packages/io.chainsafe.web3-unity/Tests/Runtime/chainsafe.web3-unity.RuntimeTests.asmdef +++ b/Packages/io.chainsafe.web3-unity/Tests/Runtime/chainsafe.web3-unity.RuntimeTests.asmdef @@ -18,9 +18,9 @@ "ChainSafe.Gaming.dll", "ChainSafe.Gaming.Unity.dll", "ChainSafe.Gaming.Gelato.dll", - "ChainSafe.Gaming.WalletConnect.dll", "Nethereum.RPC.dll", - "Newtonsoft.Json.dll" + "Newtonsoft.Json.dll", + "ChainSafe.Gaming.Reown.dll" ], "autoReferenced": false, "defineConstraints": [ diff --git a/Setup/dependencies.json b/Setup/dependencies.json index 0ca9b64ca..50da88bd8 100644 --- a/Setup/dependencies.json +++ b/Setup/dependencies.json @@ -22,7 +22,6 @@ "Nethereum.Web3", "ChainSafe.Gaming.Unity", "System.Buffers", - "ChainSafe.Gaming.WalletConnect", "System.Memory", "ChainSafe.Gaming", "System.Numerics.Vectors", @@ -43,24 +42,14 @@ "NBitcoin", "System.Threading.Tasks.Extensions", "Nethereum.ABI", - "WalletConnectSharp.Auth", "Nethereum.Accounts", - "WalletConnectSharp.Common", - "WalletConnectSharp.Events", "Nethereum.BlockchainProcessing", - "WalletConnectSharp.Core", "Nethereum.Contracts", - "WalletConnectSharp.Crypto", "Nethereum.Hex", "Nethereum.JsonRpc.Client", - "WalletConnectSharp.Network.Websocket", - "WalletConnectSharp.Network", "Nethereum.JsonRpc.RpcClient", - "WalletConnectSharp.Sign", "Nethereum.KeyStore", - "WalletConnectSharp.Storage", "Nethereum.Merkle.Patricia", - "WalletConnectSharp.Web3Wallet", "Nethereum.Merkle", "Websocket.Client", "Nethereum.Siwe.Core", @@ -68,7 +57,16 @@ "Nethereum.UI", "ChainSafe.Gaming.Unity.MetaMask", "ChainSafe.Gaming.Marketplace", - "ChainSafe.Gaming.Unity.EthereumWindow" + "ChainSafe.Gaming.Unity.EthereumWindow", + "ChainSafe.Gaming.Reown", + "Reown.Core", + "Reown.Core.Common", + "Reown.Core.Crypto", + "Reown.Core.Network", + "Reown.Core.Network.WebSocket", + "Reown.Core.Storage", + "Reown.Sign", + "Reown.WalletKit" ] }, { diff --git a/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs b/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs index 6a86f2e4b..2e887876c 100644 --- a/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs +++ b/src/ChainSafe.Gaming.InProcessTransactionExecutor/InProcessTransactionExecutor.cs @@ -36,8 +36,7 @@ public InProcessTransactionExecutor(IAccountProvider accountProvider, IRpcProvid /// /// Implementation of . - /// Send a transaction using Wallet Connect. - /// This prompts user to approve a transaction on a connected wallet. + /// Sends a transaction. /// /// Transaction to send. /// Hash response of a successfully executed transaction. diff --git a/src/ChainSafe.Gaming.NetCore/NetCoreHttpClient.cs b/src/ChainSafe.Gaming.NetCore/NetCoreHttpClient.cs index a666b4b5d..37559beba 100644 --- a/src/ChainSafe.Gaming.NetCore/NetCoreHttpClient.cs +++ b/src/ChainSafe.Gaming.NetCore/NetCoreHttpClient.cs @@ -1,9 +1,9 @@ -using System.IO; -using System.Net.Http; +using System.Net.Http; +using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using ChainSafe.Gaming.Web3.Environment; -using Newtonsoft.Json; +using ChainSafe.Gaming.Web3.Environment.Http; namespace ChainSafe.Gaming.NetCore { @@ -22,68 +22,49 @@ public NetCoreHttpClient() originalClient = new HttpClient(); } - private static async ValueTask> ResponseToNetworkResponse(HttpResponseMessage response) + public async ValueTask> GetRaw(string url, params HttpHeader[] headers) { - if (response.IsSuccessStatusCode) - { - return NetworkResponse.Success(await response.Content.ReadAsStringAsync()); - } - else + var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + foreach (var header in headers) { - return NetworkResponse.Failure($"{response.StatusCode}: {await response.Content.ReadAsStringAsync()}"); + request.Headers.Add(header.Name, header.Value); } - } - /// - /// Get Raw response from http request with a GET method. - /// - /// Url of request to be made. - /// Raw response to the request. - public async ValueTask> GetRaw(string url) - { - var response = await originalClient.GetAsync(url); + var response = await originalClient.SendAsync(request); return await ResponseToNetworkResponse(response); } - /// - /// Get Raw response from http request with a POST method. - /// - /// Url of request to be made. - /// Request data/body. - /// Content type request header. - /// Raw response to the request. - public async ValueTask> PostRaw(string url, string data, string contentType) + public async ValueTask> PostRaw( + string url, + string data, + string contentType, + params HttpHeader[] headers) { - var requestContent = new StringContent(data, Encoding.UTF8, contentType); - var response = await originalClient.PostAsync(url, requestContent); - return await ResponseToNetworkResponse(response); - } + var request = new HttpRequestMessage(HttpMethod.Post, url); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - /// - /// Get response as from http request with a GET method. - /// - /// Url of request to be made. - /// Response body model type. - /// Response as a . - public async ValueTask> Get(string url) - { - var response = await GetRaw(url); - return response.Map(x => JsonConvert.DeserializeObject(x)); + foreach (var header in headers) + { + request.Headers.Add(header.Name, header.Value); + } + + request.Content = new StringContent(data, Encoding.UTF8, contentType); + var response = await originalClient.SendAsync(request); + return await ResponseToNetworkResponse(response); } - /// - /// Get response as from http request with a GET method. - /// - /// Url of request to be made. - /// Request data/body. - /// Request data/body model type. - /// Response data/body type. - /// Response as a . - public async ValueTask> Post(string url, TRequest data) + private static async ValueTask> ResponseToNetworkResponse(HttpResponseMessage response) { - var requestJson = JsonConvert.SerializeObject(data); - var response = await PostRaw(url, requestJson, "application/json"); - return response.Map(x => JsonConvert.DeserializeObject(x)); + if (response.IsSuccessStatusCode) + { + return NetworkResponse.Success(await response.Content.ReadAsStringAsync()); + } + else + { + return NetworkResponse.Failure($"{response.StatusCode}: {await response.Content.ReadAsStringAsync()}"); + } } } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/ChainSafe.Gaming.WalletConnect.csproj b/src/ChainSafe.Gaming.Reown/ChainSafe.Gaming.Reown.csproj similarity index 74% rename from src/ChainSafe.Gaming.WalletConnect/ChainSafe.Gaming.WalletConnect.csproj rename to src/ChainSafe.Gaming.Reown/ChainSafe.Gaming.Reown.csproj index cb6b3a307..526176303 100644 --- a/src/ChainSafe.Gaming.WalletConnect/ChainSafe.Gaming.WalletConnect.csproj +++ b/src/ChainSafe.Gaming.Reown/ChainSafe.Gaming.Reown.csproj @@ -3,7 +3,7 @@ netstandard2.1 9.0 - ChainSafe.Gaming.WalletConnect + ChainSafe.Gaming.Reown True ../../global.ruleset Debug;Release;Test @@ -16,8 +16,7 @@ - - + diff --git a/src/ChainSafe.Gaming.WalletConnect/Connection/ConnectionHandlerConfig.cs b/src/ChainSafe.Gaming.Reown/Connection/ConnectionHandlerConfig.cs similarity index 92% rename from src/ChainSafe.Gaming.WalletConnect/Connection/ConnectionHandlerConfig.cs rename to src/ChainSafe.Gaming.Reown/Connection/ConnectionHandlerConfig.cs index 5aded5eff..eeee9afea 100644 --- a/src/ChainSafe.Gaming.WalletConnect/Connection/ConnectionHandlerConfig.cs +++ b/src/ChainSafe.Gaming.Reown/Connection/ConnectionHandlerConfig.cs @@ -1,8 +1,9 @@ using System; using System.Collections.Generic; -using ChainSafe.Gaming.WalletConnect.Models; +using ChainSafe.Gaming.Reown.Models; +using ChainSafe.Gaming.Reown.Wallets; -namespace ChainSafe.Gaming.WalletConnect.Connection +namespace ChainSafe.Gaming.Reown.Connection { /// /// The config object class used to configure the . diff --git a/src/ChainSafe.Gaming.WalletConnect/Connection/IConnectionHandler.cs b/src/ChainSafe.Gaming.Reown/Connection/IConnectionHandler.cs similarity index 87% rename from src/ChainSafe.Gaming.WalletConnect/Connection/IConnectionHandler.cs rename to src/ChainSafe.Gaming.Reown/Connection/IConnectionHandler.cs index 3befea056..7ed15a675 100644 --- a/src/ChainSafe.Gaming.WalletConnect/Connection/IConnectionHandler.cs +++ b/src/ChainSafe.Gaming.Reown/Connection/IConnectionHandler.cs @@ -1,6 +1,6 @@ using System.Threading.Tasks; -namespace ChainSafe.Gaming.WalletConnect.Connection +namespace ChainSafe.Gaming.Reown.Connection { /// /// Connection handler used to choose a wallet when connecting a new session. diff --git a/src/ChainSafe.Gaming.WalletConnect/Connection/IConnectionHandlerProvider.cs b/src/ChainSafe.Gaming.Reown/Connection/IConnectionHandlerProvider.cs similarity index 81% rename from src/ChainSafe.Gaming.WalletConnect/Connection/IConnectionHandlerProvider.cs rename to src/ChainSafe.Gaming.Reown/Connection/IConnectionHandlerProvider.cs index fad6eb33e..a170c8027 100644 --- a/src/ChainSafe.Gaming.WalletConnect/Connection/IConnectionHandlerProvider.cs +++ b/src/ChainSafe.Gaming.Reown/Connection/IConnectionHandlerProvider.cs @@ -1,6 +1,6 @@ using System.Threading.Tasks; -namespace ChainSafe.Gaming.WalletConnect.Connection +namespace ChainSafe.Gaming.Reown.Connection { /// /// Provider of . diff --git a/src/ChainSafe.Gaming.WalletConnect/Delegates.cs b/src/ChainSafe.Gaming.Reown/Delegates.cs similarity index 82% rename from src/ChainSafe.Gaming.WalletConnect/Delegates.cs rename to src/ChainSafe.Gaming.Reown/Delegates.cs index f500ecdd2..d48f8572f 100644 --- a/src/ChainSafe.Gaming.WalletConnect/Delegates.cs +++ b/src/ChainSafe.Gaming.Reown/Delegates.cs @@ -1,4 +1,4 @@ -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown { /// /// Delegate used to redirect user to one of the locally installed wallets. diff --git a/src/ChainSafe.Gaming.WalletConnect/IConnectionHelper.cs b/src/ChainSafe.Gaming.Reown/IConnectionHelper.cs similarity index 74% rename from src/ChainSafe.Gaming.WalletConnect/IConnectionHelper.cs rename to src/ChainSafe.Gaming.Reown/IConnectionHelper.cs index 4fafe1499..4f8411421 100644 --- a/src/ChainSafe.Gaming.WalletConnect/IConnectionHelper.cs +++ b/src/ChainSafe.Gaming.Reown/IConnectionHelper.cs @@ -1,7 +1,7 @@ -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown { /// - /// Helper class for the WalletConnect login procedure. + /// Helper class for the Reown login procedure. /// public interface IConnectionHelper { diff --git a/src/ChainSafe.Gaming.WalletConnect/IWalletConnectConfig.cs b/src/ChainSafe.Gaming.Reown/IReownConfig.cs similarity index 64% rename from src/ChainSafe.Gaming.WalletConnect/IWalletConnectConfig.cs rename to src/ChainSafe.Gaming.Reown/IReownConfig.cs index 5269fbf99..d9b47bd68 100644 --- a/src/ChainSafe.Gaming.WalletConnect/IWalletConnectConfig.cs +++ b/src/ChainSafe.Gaming.Reown/IReownConfig.cs @@ -1,16 +1,19 @@ #nullable enable using System.Collections.Generic; -using ChainSafe.Gaming.WalletConnect.Connection; +using ChainSafe.Gaming.Reown.Connection; +using ChainSafe.Gaming.Reown.Wallets; +using ChainSafe.Gaming.Web3.Environment; using ChainSafe.Gaming.Web3.Evm.Wallet; -using WalletConnectSharp.Core; -using WalletConnectSharp.Network.Interfaces; +using Reown.Core; +using Reown.Core.Network; +using Reown.Core.Network.Interfaces; -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown { /// - /// Interface for WalletConnect configuration. + /// Interface for Reown configuration. /// - public interface IWalletConnectConfig : IWalletProviderConfig + public interface IReownConfig : IWalletProviderConfig { /// /// Set to true if you want to store this session on a disk for the next time. @@ -33,50 +36,31 @@ public interface IWalletConnectConfig : IWalletProviderConfig string ProjectName { get; } /// - /// Project ID provided to you by WalletConnect. + /// Project ID provided to you by Reown. /// string ProjectId { get; } /// - /// Name of the context to be used by WalletConnect. + /// Name of the context to be used by Reown. /// string BaseContext { get; } /// - /// Used to set custom to support Unity versions before 2022.1. - /// - IConnectionBuilder ConnectionBuilder { get; } - - /// - /// WalletConnect metadata. + /// Reown metadata. /// Metadata Metadata { get; } - /// - /// Relative path to folder where storage files should be place. - /// - /// The path is relative to the app's data folder. - string StoragePath { get; } - /// /// List of the wallets that you want to show to your user as local wallet connect options. /// Keep this empty to enable all of the wallets supported for the platform. /// - /// - /// Use either or . - /// If both are provided will be ignored. - /// - IList? EnabledWallets { get; } + IList? IncludeWalletIds { get; } /// /// List of the wallets that you want to disable. - /// Disabled wallet won't be shown to the user as local connect options. + /// Disabled wallet won't be shown to the user as local connect option. /// - /// - /// Use either or . - /// If both are provided will be ignored. - /// - IList? DisabledWallets { get; } + IList? ExcludeWalletIds { get; } /// /// Use this to set Local, Remote or Both wallet connection options for the user. @@ -91,10 +75,23 @@ public interface IWalletConnectConfig : IWalletProviderConfig IConnectionHandlerProvider ConnectionHandlerProvider { get; } /// - /// Override for the registry URI used to download the list of wallets supported by WalletConnect. + /// Override for the registry URI used to download the list of wallets supported by Reown. /// string? OverrideRegistryUri { get; } - WalletConnectLogLevel LogLevel { get; } + /// + /// Configure log level filter for Reown logs. + /// + ReownLogLevel LogLevel { get; } + + /// + /// I honestly don't know what this is for. + /// + IRelayUrlBuilder RelayUrlBuilder { get; } + + /// + /// Used to set custom to support Unity versions before 2022.1. + /// + IConnectionBuilder ConnectionBuilder { get; } } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/Methods/EthSendTransaction.cs b/src/ChainSafe.Gaming.Reown/Methods/EthSendTransaction.cs similarity index 84% rename from src/ChainSafe.Gaming.WalletConnect/Methods/EthSendTransaction.cs rename to src/ChainSafe.Gaming.Reown/Methods/EthSendTransaction.cs index 3b87f2235..ee769d09f 100644 --- a/src/ChainSafe.Gaming.WalletConnect/Methods/EthSendTransaction.cs +++ b/src/ChainSafe.Gaming.Reown/Methods/EthSendTransaction.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; -using ChainSafe.Gaming.WalletConnect.Models; +using ChainSafe.Gaming.Reown.Models; using Nethereum.RPC.Eth.DTOs; -using WalletConnectSharp.Common.Utils; -using WalletConnectSharp.Network.Models; +using Reown.Core.Common.Utils; +using Reown.Core.Network.Models; -namespace ChainSafe.Gaming.WalletConnect.Methods +namespace ChainSafe.Gaming.Reown.Methods { /// - /// Send Transaction Wallet Connect Json RPC method params. + /// Send Transaction Reown Json RPC method params. /// [RpcMethod("eth_sendTransaction")] [RpcRequestOptions(Clock.ONE_MINUTE, 99999)] diff --git a/src/ChainSafe.Gaming.WalletConnect/Methods/EthSignMessage.cs b/src/ChainSafe.Gaming.Reown/Methods/EthSignMessage.cs similarity index 82% rename from src/ChainSafe.Gaming.WalletConnect/Methods/EthSignMessage.cs rename to src/ChainSafe.Gaming.Reown/Methods/EthSignMessage.cs index 8726ebbfd..72e8df274 100644 --- a/src/ChainSafe.Gaming.WalletConnect/Methods/EthSignMessage.cs +++ b/src/ChainSafe.Gaming.Reown/Methods/EthSignMessage.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; -using WalletConnectSharp.Common.Utils; -using WalletConnectSharp.Network.Models; +using Reown.Core.Common.Utils; +using Reown.Core.Network.Models; -namespace ChainSafe.Gaming.WalletConnect.Methods +namespace ChainSafe.Gaming.Reown.Methods { /// - /// Sign message Wallet Connect Json RPC method params. + /// Sign message Reown Json RPC method params. /// [RpcMethod("personal_sign")] [RpcRequestOptions(Clock.ONE_MINUTE, 99997)] diff --git a/src/ChainSafe.Gaming.WalletConnect/Methods/EthSignTransaction.cs b/src/ChainSafe.Gaming.Reown/Methods/EthSignTransaction.cs similarity index 77% rename from src/ChainSafe.Gaming.WalletConnect/Methods/EthSignTransaction.cs rename to src/ChainSafe.Gaming.Reown/Methods/EthSignTransaction.cs index 01c08682d..95bce9039 100644 --- a/src/ChainSafe.Gaming.WalletConnect/Methods/EthSignTransaction.cs +++ b/src/ChainSafe.Gaming.Reown/Methods/EthSignTransaction.cs @@ -1,12 +1,12 @@ using System.Collections.Generic; -using ChainSafe.Gaming.WalletConnect.Models; -using WalletConnectSharp.Common.Utils; -using WalletConnectSharp.Network.Models; +using ChainSafe.Gaming.Reown.Models; +using Reown.Core.Common.Utils; +using Reown.Core.Network.Models; -namespace ChainSafe.Gaming.WalletConnect.Methods +namespace ChainSafe.Gaming.Reown.Methods { /// - /// Sign Transaction Wallet Connect Json RPC method params. + /// Sign Transaction Reown Json RPC method params. /// [RpcMethod("eth_signTransaction")] [RpcRequestOptions(Clock.ONE_MINUTE, 99996)] diff --git a/src/ChainSafe.Gaming.WalletConnect/Methods/EthSignTypedData.cs b/src/ChainSafe.Gaming.Reown/Methods/EthSignTypedData.cs similarity index 80% rename from src/ChainSafe.Gaming.WalletConnect/Methods/EthSignTypedData.cs rename to src/ChainSafe.Gaming.Reown/Methods/EthSignTypedData.cs index e2da8bf78..a5bc26237 100644 --- a/src/ChainSafe.Gaming.WalletConnect/Methods/EthSignTypedData.cs +++ b/src/ChainSafe.Gaming.Reown/Methods/EthSignTypedData.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; -using ChainSafe.Gaming.Web3.Core.Evm; -using WalletConnectSharp.Common.Utils; -using WalletConnectSharp.Network.Models; +using Reown.Core.Common.Utils; +using Reown.Core.Network.Models; -namespace ChainSafe.Gaming.WalletConnect.Methods +namespace ChainSafe.Gaming.Reown.Methods { /// - /// Sign Typed Data Wallet Connect Json RPC method params. + /// Sign Typed Data Reown Json RPC method params. /// [RpcMethod("eth_signTypedData")] [RpcRequestOptions(Clock.ONE_MINUTE, 99998)] diff --git a/src/ChainSafe.Gaming.WalletConnect/Methods/WalletSwitchEthereumChain.cs b/src/ChainSafe.Gaming.Reown/Methods/WalletSwitchEthereumChain.cs similarity index 82% rename from src/ChainSafe.Gaming.WalletConnect/Methods/WalletSwitchEthereumChain.cs rename to src/ChainSafe.Gaming.Reown/Methods/WalletSwitchEthereumChain.cs index de58f7500..412c0a1af 100644 --- a/src/ChainSafe.Gaming.WalletConnect/Methods/WalletSwitchEthereumChain.cs +++ b/src/ChainSafe.Gaming.Reown/Methods/WalletSwitchEthereumChain.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; -using WalletConnectSharp.Common.Utils; -using WalletConnectSharp.Network.Models; +using Reown.Core.Common.Utils; +using Reown.Core.Network.Models; -namespace ChainSafe.Gaming.WalletConnect.Methods +namespace ChainSafe.Gaming.Reown.Methods { /// - /// Switch Ethereum Chain Wallet Connect Json RPC method params. + /// Switch Ethereum Chain Reown Json RPC method params. /// [RpcMethod("wallet_switchEthereumChain")] [RpcRequestOptions(Clock.ONE_MINUTE, 99995)] diff --git a/src/ChainSafe.Gaming.WalletConnect/Models/TransactionModel.cs b/src/ChainSafe.Gaming.Reown/Models/TransactionModel.cs similarity index 87% rename from src/ChainSafe.Gaming.WalletConnect/Models/TransactionModel.cs rename to src/ChainSafe.Gaming.Reown/Models/TransactionModel.cs index 31673cfc2..41a726dfd 100644 --- a/src/ChainSafe.Gaming.WalletConnect/Models/TransactionModel.cs +++ b/src/ChainSafe.Gaming.Reown/Models/TransactionModel.cs @@ -1,9 +1,9 @@ using Newtonsoft.Json; -namespace ChainSafe.Gaming.WalletConnect.Models +namespace ChainSafe.Gaming.Reown.Models { /// - /// Transaction Model used for Wallet Connect Json RPC params, see https://docs.walletconnect.com/advanced/rpc-reference/ethereum-rpc#eth_sendtransaction. + /// Transaction Model used for Reown Json RPC params, see https://docs.walletconnect.com/advanced/rpc-reference/ethereum-rpc#eth_sendtransaction. /// public class TransactionModel { diff --git a/src/ChainSafe.Gaming.Reown/Models/WalletModel.cs b/src/ChainSafe.Gaming.Reown/Models/WalletModel.cs new file mode 100644 index 000000000..8818587a8 --- /dev/null +++ b/src/ChainSafe.Gaming.Reown/Models/WalletModel.cs @@ -0,0 +1,40 @@ +using Newtonsoft.Json; + +namespace ChainSafe.Gaming.Reown.Models +{ + /// + /// Reown wallet model used for identifying and redirecting wallets. + /// + public class WalletModel + { + [JsonProperty("id")] + public string Id { get; set; } + + [JsonProperty("name")] + public string Name { get; set; } + + [JsonProperty("homepage")] + public string Homepage { get; set; } + + [JsonProperty("image_id")] + public string ImageId { get; set; } + + [JsonProperty("order")] + public int Order { get; set; } + + [JsonProperty("mobile_link")] + public string MobileLink { get; set; } + + [JsonProperty("desktop_link")] + public string DesktopLink { get; set; } + + [JsonProperty("webapp_link")] + public string WebappLink { get; set; } + + [JsonProperty("app_store")] + public string AppStore { get; set; } + + [JsonProperty("play_store")] + public string PlayStore { get; set; } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.Reown/RedirectionHandler.cs b/src/ChainSafe.Gaming.Reown/RedirectionHandler.cs new file mode 100644 index 000000000..32ab59e35 --- /dev/null +++ b/src/ChainSafe.Gaming.Reown/RedirectionHandler.cs @@ -0,0 +1,129 @@ +using System; +using ChainSafe.Gaming.Reown.Models; +using ChainSafe.Gaming.Reown.Wallets; +using ChainSafe.Gaming.Web3.Environment; + +namespace ChainSafe.Gaming.Reown +{ + /// + /// Component responsible for redirection to a wallet app. + /// + public class RedirectionHandler + { + private readonly IWalletRegistry walletRegistry; + private readonly IOperatingSystemMediator osMediator; + private readonly ILogWriter logWriter; + + public RedirectionHandler(IWalletRegistry walletRegistry, IOperatingSystemMediator osMediator, ILogWriter logWriter) + { + this.logWriter = logWriter; + this.osMediator = osMediator; + this.walletRegistry = walletRegistry; + } + + /// + /// Redirect for connection using the pre-selected wallet. + /// + /// The connection URI provided by Reown. + /// The name of the wallet to redirect user to. + public void RedirectConnection(string connectionUri, string walletId) + { + var walletData = walletRegistry.GetWallet(walletId); + var deeplink = BuildConnectionDeeplink(walletData, connectionUri); + + logWriter.Log($"Generated deep link: {deeplink}"); + + if (osMediator.IsMobilePlatform && osMediator.IsEditor) + { + logWriter.LogError("Can't open mobile deeplink in editor. Ignoring..."); + return; + } + + osMediator.OpenUrl(deeplink); + } + + /// + /// Delegate redirection for connection to the OS. + /// + /// The connection URI provided by Reown. + public void RedirectConnectionOsManaged(string connectionUri) + { + if (osMediator.IsMobilePlatform && osMediator.IsEditor) + { + logWriter.LogError($"Can't open mobile connection URI in editor. Ignoring... Connection URI: {connectionUri}"); + return; + } + + logWriter.Log($"Connection URI: {connectionUri}"); + + osMediator.OpenUrl(connectionUri); + } + + /// + /// Redirect to the pre-selected wallet using the wallet name. + /// + public void Redirect(string walletId) + { + var walletData = walletRegistry.GetWallet(walletId); + Redirect(walletData); + } + + /// + /// Redirect to the pre-selected wallet. + /// + public void Redirect(WalletModel walletData) + { + var deepLink = GetWalletAppDeeplink(walletData); + osMediator.OpenUrl(deepLink); + } + + /// + /// Used to get a redirection deeplink for the . + /// + /// Data of the wallet that we want to redirect to. + /// Deeplink for redirection. + public string GetWalletAppDeeplink(WalletModel walletData) + { + return osMediator.IsMobilePlatform ? walletData.MobileLink : walletData.DesktopLink; + } + + /// + /// Used to get a connection deeplink for the particular wallet. + /// + /// Data of the wallet that we want to connect. + /// The connection URI provided by Reown. + /// Deeplink for connection. + /// Invalid format of deeplink registered for the provided wallet. + public string BuildConnectionDeeplink(WalletModel walletData, string wcUri) + { + if (string.IsNullOrWhiteSpace(wcUri)) + { + throw new ReownIntegrationException( + "Can not build a connection deep link. The connection URI is empty."); + } + + var appLink = GetWalletAppDeeplink(walletData); + + if (string.IsNullOrWhiteSpace(appLink)) + { + throw new ReownIntegrationException("[Linker] Native link cannot be empty."); + } + + var safeAppUrl = appLink; + if (!safeAppUrl.Contains("://")) + { + safeAppUrl = safeAppUrl.Replace("/", string.Empty).Replace(":", string.Empty); + safeAppUrl = $"{safeAppUrl}://"; + } + + if (!safeAppUrl.EndsWith('/')) + { + safeAppUrl = $"{safeAppUrl}/"; + } + + var encodedWcUrl = Uri.EscapeDataString(wcUri); + + return $"{safeAppUrl}wc?uri={encodedWcUrl}"; + } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.Reown/ReownExtensions.cs b/src/ChainSafe.Gaming.Reown/ReownExtensions.cs new file mode 100644 index 000000000..2078c2e50 --- /dev/null +++ b/src/ChainSafe.Gaming.Reown/ReownExtensions.cs @@ -0,0 +1,78 @@ +using ChainSafe.Gaming.Reown.Wallets; +using ChainSafe.Gaming.Web3.Build; +using ChainSafe.Gaming.Web3.Core; +using ChainSafe.Gaming.Web3.Evm.Wallet; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace ChainSafe.Gaming.Reown +{ + public static class ReownExtensions + { + /// + /// Use this to configure Reown for this instance of Web3. + /// + /// The same service collection that was passed in. This enables fluent style. + public static IWeb3ServiceCollection ConfigureReown(this IWeb3ServiceCollection services, IReownConfig config) + { + services.Replace(ServiceDescriptor.Singleton(typeof(IReownConfig), config)); + + return services; + } + + /// + /// Use this to enable Reown functionality for this instance of Web3. + /// + /// The same service collection that was passed in. This enables fluent style. + public static IWeb3ServiceCollection UseReown(this IWeb3ServiceCollection services, IReownConfig config) + { + services.AssertServiceNotBound(); + + services.ConfigureReown(config); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.UseWalletProvider(config); + + return services; + } + + /// + /// Access additional services related to Reown. + /// + /// The Reown subcategory of services. + public static ReownSubCategory Reown(this Web3.Web3 web3) + { + return new ReownSubCategory(web3); + } + + /// + /// Access the service. + /// + /// The service. + public static IWalletRegistry WalletRegistry(this ReownSubCategory reown) + { + return ((IWeb3SubCategory)reown).Web3.ServiceProvider.GetRequiredService(); + } + + /// + /// Access the service. + /// + /// The service. + public static RedirectionHandler RedirectionHandler(this ReownSubCategory reown) + { + return ((IWeb3SubCategory)reown).Web3.ServiceProvider.GetRequiredService(); + } + + /// + /// Access the service. + /// + /// The service. + public static IConnectionHelper ConnectionHelper(this ReownSubCategory reown) + { + return ((IWeb3SubCategory)reown).Web3.ServiceProvider.GetRequiredService(); + } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.Reown/ReownHttpClient.cs b/src/ChainSafe.Gaming.Reown/ReownHttpClient.cs new file mode 100644 index 000000000..da10d73ae --- /dev/null +++ b/src/ChainSafe.Gaming.Reown/ReownHttpClient.cs @@ -0,0 +1,43 @@ +using System.Linq; +using System.Threading.Tasks; +using ChainSafe.Gaming.Web3.Environment; +using ChainSafe.Gaming.Web3.Environment.Http; + +namespace ChainSafe.Gaming.Reown +{ + /// + /// An HTTP client wrapper that adds the HTTP headers required by the Reown API to each request. + /// + public class ReownHttpClient : IHttpClient + { + private readonly IHttpClient originalClient; + private readonly HttpHeader[] reownHeaders; + + public ReownHttpClient(IHttpClient originalClient, IReownConfig reownConfig) + { + this.originalClient = originalClient; + + reownHeaders = new[] + { + new HttpHeader { Name = "x-project-id", Value = reownConfig.ProjectId }, + new HttpHeader { Name = "x-sdk-type", Value = "appkit" }, + new HttpHeader { Name = "x-sdk-version", Value = "unity-appkit-v1.0.0" }, + }; + } + + public ValueTask> GetRaw(string url, params HttpHeader[] headers) + { + return originalClient.GetRaw(url, AppendReownHeaders(headers)); + } + + public ValueTask> PostRaw(string url, string data, string contentType, params HttpHeader[] headers) + { + return originalClient.PostRaw(url, data, contentType, AppendReownHeaders(headers)); + } + + private HttpHeader[] AppendReownHeaders(HttpHeader[] originalHeaders) + { + return reownHeaders.Concat(originalHeaders).ToArray(); + } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.Reown/ReownIntegrationException.cs b/src/ChainSafe.Gaming.Reown/ReownIntegrationException.cs new file mode 100644 index 000000000..7460a1922 --- /dev/null +++ b/src/ChainSafe.Gaming.Reown/ReownIntegrationException.cs @@ -0,0 +1,21 @@ +using System; +using ChainSafe.Gaming.Web3; + +namespace ChainSafe.Gaming.Reown +{ + /// + /// Represents exception related to the Reown integration. + /// + public class ReownIntegrationException : Web3Exception + { + public ReownIntegrationException(string message) + : base(message) + { + } + + public ReownIntegrationException(string message, Exception innerException) + : base(message, innerException) + { + } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/WalletConnectLogLevel.cs b/src/ChainSafe.Gaming.Reown/ReownLogLevel.cs similarity index 50% rename from src/ChainSafe.Gaming.WalletConnect/WalletConnectLogLevel.cs rename to src/ChainSafe.Gaming.Reown/ReownLogLevel.cs index bce982750..6c1e567f5 100644 --- a/src/ChainSafe.Gaming.WalletConnect/WalletConnectLogLevel.cs +++ b/src/ChainSafe.Gaming.Reown/ReownLogLevel.cs @@ -1,6 +1,6 @@ -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown { - public enum WalletConnectLogLevel + public enum ReownLogLevel { Disabled = 0, ErrorOnly = 1, diff --git a/src/ChainSafe.Gaming.WalletConnect/WCLogWriter.cs b/src/ChainSafe.Gaming.Reown/ReownLogWriter.cs similarity index 65% rename from src/ChainSafe.Gaming.WalletConnect/WCLogWriter.cs rename to src/ChainSafe.Gaming.Reown/ReownLogWriter.cs index 495ea4a2c..ac0d399fb 100644 --- a/src/ChainSafe.Gaming.WalletConnect/WCLogWriter.cs +++ b/src/ChainSafe.Gaming.Reown/ReownLogWriter.cs @@ -1,24 +1,24 @@ using System; using ChainSafe.Gaming.Web3.Environment; -using ILogger = WalletConnectSharp.Common.Logging.ILogger; +using Reown.Core.Common.Logging; -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown { /// - /// Writes Wallet Connect logs to the . + /// Writes Reown logs to the . /// - public class WCLogWriter : ILogger + public class ReownLogWriter : ILogger { - private const string Label = "[WalletConnect SDK]"; + private const string Label = "[Reown]"; private readonly ILogWriter logWriter; - private readonly IWalletConnectConfig config; + private readonly IReownConfig config; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Log Writer used for logging. - public WCLogWriter(ILogWriter logWriter, IWalletConnectConfig config) + public ReownLogWriter(ILogWriter logWriter, IReownConfig config) { this.config = config; this.logWriter = logWriter; @@ -30,7 +30,7 @@ public WCLogWriter(ILogWriter logWriter, IWalletConnectConfig config) /// Message to be logged. public void Log(string message) { - if (config.LogLevel < WalletConnectLogLevel.Enabled) + if (config.LogLevel < ReownLogLevel.Enabled) { return; } @@ -44,7 +44,7 @@ public void Log(string message) /// Error message to be logged. public void LogError(string message) { - if (config.LogLevel < WalletConnectLogLevel.ErrorOnly) + if (config.LogLevel < ReownLogLevel.ErrorOnly) { return; } @@ -58,7 +58,7 @@ public void LogError(string message) /// Exception to be logged. public void LogError(Exception e) { - if (config.LogLevel < WalletConnectLogLevel.ErrorOnly) + if (config.LogLevel < ReownLogLevel.ErrorOnly) { return; } diff --git a/src/ChainSafe.Gaming.WalletConnect/WalletConnectProvider.cs b/src/ChainSafe.Gaming.Reown/ReownProvider.cs similarity index 55% rename from src/ChainSafe.Gaming.WalletConnect/WalletConnectProvider.cs rename to src/ChainSafe.Gaming.Reown/ReownProvider.cs index 5366eebd1..0a3f7dac4 100644 --- a/src/ChainSafe.Gaming.WalletConnect/WalletConnectProvider.cs +++ b/src/ChainSafe.Gaming.Reown/ReownProvider.cs @@ -2,81 +2,102 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using ChainSafe.Gaming.Evm; -using ChainSafe.Gaming.WalletConnect.Connection; -using ChainSafe.Gaming.WalletConnect.Methods; -using ChainSafe.Gaming.WalletConnect.Models; -using ChainSafe.Gaming.WalletConnect.Storage; -using ChainSafe.Gaming.WalletConnect.Wallets; +using ChainSafe.Gaming.Reown.Connection; +using ChainSafe.Gaming.Reown.Methods; +using ChainSafe.Gaming.Reown.Models; +using ChainSafe.Gaming.Reown.Storage; +using ChainSafe.Gaming.Reown.Wallets; using ChainSafe.Gaming.Web3; using ChainSafe.Gaming.Web3.Analytics; using ChainSafe.Gaming.Web3.Core; +using ChainSafe.Gaming.Web3.Core.Chains; using ChainSafe.Gaming.Web3.Core.Debug; using ChainSafe.Gaming.Web3.Environment; using ChainSafe.Gaming.Web3.Evm.Wallet; -using Nethereum.Hex.HexConvertors.Extensions; using Nethereum.JsonRpc.Client.RpcMessages; using Newtonsoft.Json; -using Org.BouncyCastle.Math; -using WalletConnectSharp.Common.Logging; -using WalletConnectSharp.Common.Model.Errors; -using WalletConnectSharp.Common.Utils; -using WalletConnectSharp.Core; -using WalletConnectSharp.Core.Models; -using WalletConnectSharp.Core.Models.Publisher; -using WalletConnectSharp.Network.Models; -using WalletConnectSharp.Sign; -using WalletConnectSharp.Sign.Models; -using WalletConnectSharp.Sign.Models.Engine; -using BigInteger = System.Numerics.BigInteger; - -namespace ChainSafe.Gaming.WalletConnect +using Reown.Core.Common.Logging; +using Reown.Core.Common.Model.Errors; +using Reown.Core.Common.Utils; +using Reown.Core.Crypto; +using Reown.Core.Models.Publisher; +using Reown.Core.Network.Models; +using Reown.Sign; +using Reown.Sign.Models; +using Reown.Sign.Models.Engine; + +namespace ChainSafe.Gaming.Reown { /// - /// Default implementation of . + /// Reown implementation of . /// - public class WalletConnectProvider : WalletProvider, ILifecycleParticipant, IConnectionHelper + public class ReownProvider : WalletProvider, ILifecycleParticipant, IConnectionHelper { + private const string EvmNamespace = "eip155"; + private readonly ILogWriter logWriter; - private readonly IWalletConnectConfig config; - private readonly DataStorage storage; + private readonly IReownConfig config; private readonly IChainConfig chainConfig; private readonly IOperatingSystemMediator osMediator; private readonly IWalletRegistry walletRegistry; private readonly RedirectionHandler redirection; - private readonly IHttpClient httpClient; + private readonly IHttpClient reownHttpClient; private readonly IAnalyticsClient analyticsClient; + private readonly Web3Environment environment; + private readonly IChainConfigSet chainConfigSet; - private WalletConnectCore core; - private WalletConnectSignClient signClient; - private RequiredNamespaces requiredNamespaces; - private LocalData localData; + private SignClient signClient; private SessionStruct session; private bool connected; private bool initialized; private ConnectionHandlerConfig connectionHandlerConfig; + private Dictionary optionalNamespaces; + private WalletModel sessionWallet; - public WalletConnectProvider( - IWalletConnectConfig config, - DataStorage storage, + public ReownProvider( + IReownConfig config, IChainConfig chainConfig, + IChainConfigSet chainConfigSet, IWalletRegistry walletRegistry, RedirectionHandler redirection, - Web3Environment environment) + Web3Environment environment, + ReownHttpClient reownHttpClient) : base(environment, chainConfig) { + this.chainConfigSet = chainConfigSet; + this.environment = environment; analyticsClient = environment.AnalyticsClient; this.redirection = redirection; this.walletRegistry = walletRegistry; osMediator = environment.OperatingSystem; this.chainConfig = chainConfig; - this.storage = storage; this.config = config; logWriter = environment.LogWriter; - httpClient = environment.HttpClient; + this.reownHttpClient = reownHttpClient; } - public bool StoredSessionAvailable => localData.SessionTopic != null; + public bool StoredSessionAvailable + { + get + { + if (!signClient.AddressProvider.HasDefaultSession) + { + return false; // no session stored + } + + if (string.IsNullOrWhiteSpace(signClient.AddressProvider.DefaultSession.Topic)) + { + return false; // session topic is empty + } + + if (!signClient.Session.Keys.Contains(signClient.AddressProvider.DefaultSession.Topic)) + { + return false; // usually happens when session was closed on the wallet side + } + + return true; + } + } private bool OsManageWalletSelection => osMediator.Platform == Platform.Android; @@ -96,62 +117,58 @@ private async Task Initialize() analyticsClient.CaptureEvent(new AnalyticsEvent() { - EventName = "Wallet Connect Initialized", + EventName = "Reown Initialized", PackageName = "io.chainsafe.web3-unity", }); ValidateConfig(); - WCLogger.Logger = new WCLogWriter(logWriter, config); - - localData = !config.ForceNewSession - ? await storage.LoadLocalData() ?? new LocalData() - : new LocalData(); + ReownLogger.Instance = new ReownLogWriter(logWriter, config); - core = new WalletConnectCore(new CoreOptions + var storage = await ReownStorageFactory.Build(environment); + var signClientOptions = new SignClientOptions { - Name = config.ProjectName, ProjectId = config.ProjectId, - Storage = storage.BuildStorage(sessionStored: !string.IsNullOrEmpty(localData.SessionTopic)), + Name = config.ProjectName, + Metadata = config.Metadata, BaseContext = config.BaseContext, + Storage = storage, + KeyChain = new KeyChain(storage), ConnectionBuilder = config.ConnectionBuilder, - }); - - await core.Start(); + RelayUrlBuilder = config.RelayUrlBuilder, + }; - signClient = await WalletConnectSignClient.Init(new SignClientOptions - { - BaseContext = config.BaseContext, - Core = core, - Metadata = config.Metadata, - Name = config.ProjectName, - ProjectId = config.ProjectId, - Storage = core.Storage, - }); + signClient = await SignClient.Init(signClientOptions); + await signClient.AddressProvider.LoadDefaultsAsync(); - requiredNamespaces = new RequiredNamespaces + var optionalNamespace = new ProposedNamespace // todo using optional namespaces like AppKit does, should they be required? { + Chains = chainConfigSet.Configs + .Select(chainEntry => $"{EvmNamespace}:{chainEntry.ChainId}") + .ToArray(), + Methods = new[] { - ChainModel.EvmNamespace, - new ProposedNamespace - { - Chains = new[] { $"{ChainModel.EvmNamespace}:{chainConfig.ChainId}", }, - Events = new[] { "chainChanged", "accountsChanged" }, - Methods = new[] - { - "eth_sign", - "personal_sign", - "eth_signTypedData", - "eth_signTransaction", - "eth_sendTransaction", - "eth_getTransactionByHash", - "wallet_switchEthereumChain", - "eth_blockNumber", - }, - } + "eth_sign", + "personal_sign", + "eth_signTypedData", + "eth_signTransaction", + "eth_sendTransaction", + "eth_getTransactionByHash", + "wallet_switchEthereumChain", + "eth_blockNumber", + }, + Events = new[] + { + "chainChanged", + "accountsChanged", }, }; + optionalNamespaces = new Dictionary + { + { EvmNamespace, optionalNamespace }, + }; + initialized = true; } @@ -159,19 +176,23 @@ private void ValidateConfig() { if (string.IsNullOrWhiteSpace(config.ProjectId)) { - throw new WalletConnectException("ProjectId was not set."); + throw new ReownIntegrationException("ProjectId was not set."); + } + + if (config.ConnectionHandlerProvider == null) + { + throw new ReownIntegrationException($"No {nameof(IConnectionHandlerProvider)} was provided in the config."); } - if (string.IsNullOrWhiteSpace(config.StoragePath)) + if (string.IsNullOrWhiteSpace(config.Metadata.Url)) { - throw new WalletConnectException("Storage folder path was not set."); + throw new ReownIntegrationException("Your domain URL should be provided in Metadata, otherwise wallets are going to reject the connection."); } } public ValueTask WillStopAsync() { signClient?.Dispose(); - core?.Dispose(); return new ValueTask(Task.CompletedTask); } @@ -180,8 +201,8 @@ public override async Task Connect() { if (connected) { - throw new WalletConnectException( - $"Tried connecting {nameof(WalletConnectProvider)}, but it's already been connected."); + throw new ReownIntegrationException( + $"Tried connecting with {nameof(ReownProvider)}, but was already connected."); } if (!initialized) @@ -191,40 +212,24 @@ public override async Task Connect() try { - var sessionStored = !string.IsNullOrEmpty(localData.SessionTopic); - - session = !sessionStored + session = !config.RememberSession || !StoredSessionAvailable ? await ConnectSession() : await RestoreSession(); - localData.SessionTopic = session.Topic; - - var sessionLocalWallet = GetSessionLocalWallet(); - if (sessionLocalWallet != null) - { - localData.ConnectedLocalWalletName = sessionLocalWallet.Name; - WCLogger.Log($"\"{sessionLocalWallet.Name}\" set as locally connected wallet for the current session."); - } - else - { - localData.ConnectedLocalWalletName = null; - WCLogger.Log("Remote wallet connected."); - } + var address = GetPlayerAddress(); - if (config.RememberSession) - { - await storage.SaveLocalData(localData); - } - else + if (!AddressExtensions.IsPublicAddress(address)) { - storage.ClearLocalData(); + throw new ReownIntegrationException("Public address provided by Reown is not valid."); } - var address = GetPlayerAddress(); + sessionWallet = GetSessionWallet(); - if (!AddressExtensions.IsPublicAddress(address)) + if (sessionWallet is null) { - throw new Web3Exception("Public address provided by WalletConnect is not valid."); + ReownLogger.LogError("Couldn't identify the wallet used to connect the session. " + + "Redirection is disabled. " + + $"URL from wallet metadata is \"{session.Peer.Metadata.Url}\"."); } connected = true; @@ -235,15 +240,15 @@ public override async Task Connect() } catch (Exception e) { - storage.ClearLocalData(); - throw new WalletConnectException("Error occured during WalletConnect connection process.", e); + signClient.AddressProvider.DefaultSession = default; // reset saved session + throw new ReownIntegrationException("Error occured during Reown connection process.", e); } } private async Task CheckAndSwitchNetwork() { var chainId = GetChainId(); - if (chainId != $"{ChainModel.EvmNamespace}:{chainConfig.ChainId}") + if (chainId != $"{EvmNamespace}:{chainConfig.ChainId}") { await SwitchChain(chainConfig.ChainId); UpdateSessionChainId(); @@ -282,34 +287,26 @@ public override async Task Disconnect() return; } - WCLogger.Log("Disconnecting Wallet Connect session..."); + ReownLogger.Log("Disconnecting Reown session..."); try { - storage.ClearLocalData(); - localData = new LocalData(); await signClient.Disconnect(session.Topic, Error.FromErrorType(ErrorType.USER_DISCONNECTED)); - await core.Storage.Clear(); + await signClient.CoreClient.Storage.Clear(); connected = false; } catch (Exception e) { - WCLogger.LogError($"Error occured during disconnect: {e}"); + ReownLogger.LogError($"Error occured during disconnect: {e}"); } } private async Task ConnectSession() { - if (config.ConnectionHandlerProvider == null) - { - throw new WalletConnectException($"Can not connect to a new session. No {nameof(IConnectionHandlerProvider)} was set in config."); - } - - var connectOptions = new ConnectOptions { RequiredNamespaces = requiredNamespaces }; + var connectOptions = new ConnectOptions { OptionalNamespaces = optionalNamespaces }; var connectedData = await signClient.Connect(connectOptions); var connectionHandler = await config.ConnectionHandlerProvider.ProvideHandler(); - Task dialogTask; try { connectionHandlerConfig = new ConnectionHandlerConfig @@ -319,19 +316,25 @@ private async Task ConnectSession() WalletLocationOption = config.WalletLocationOption, LocalWalletOptions = !OsManageWalletSelection - ? walletRegistry.EnumerateSupportedWallets(osMediator.Platform) - .ToList() // todo notify devs that some wallets don't work on Desktop + ? walletRegistry.SupportedWallets.ToList() : null, RedirectToWallet = !OsManageWalletSelection - ? walletName => redirection.RedirectConnection(connectedData.Uri, walletName) + ? OnRedirectToWallet : null, RedirectOsManaged = OsManageWalletSelection ? () => redirection.RedirectConnectionOsManaged(connectedData.Uri) : null, }; - dialogTask = connectionHandler.ConnectUserWallet(connectionHandlerConfig); + + void OnRedirectToWallet(string walletId) + { + signClient.CoreClient.Storage.SetItem("ChainSafe_RecentLocalWalletId", walletId); // saving wallet id to enable future redirection + redirection.RedirectConnection(connectedData.Uri, walletId); + } + + var dialogTask = connectionHandler.ConnectUserWallet(connectionHandlerConfig); // awaiting handler task to catch exceptions, actually awaiting only for approval var combinedTasks = await Task.WhenAny(dialogTask, connectedData.Approval); @@ -355,23 +358,23 @@ private async Task ConnectSession() var newSession = await connectedData.Approval; - WCLogger.Log("Wallet connected using new session."); + ReownLogger.Log("Wallet connected using new session."); return newSession; } private async Task RestoreSession() { - var storedSession = signClient.Find(requiredNamespaces).First(s => s.Topic == localData.SessionTopic); + session = signClient.AddressProvider.DefaultSession; - if (SessionExpired(storedSession)) + if (SessionExpired(session)) { await RenewSession(); } - WCLogger.Log("Wallet connected using stored session."); + ReownLogger.Log("Wallet connected using stored session."); - return storedSession; + return session; } private async Task RenewSession() @@ -384,17 +387,17 @@ private async Task RenewSession() } catch (Exception e) { - throw new WalletConnectException("Auto-renew session failed.", e); + throw new ReownIntegrationException("Session extension failed.", e); } - WCLogger.Log("Renewed session successfully."); + ReownLogger.Log("Renewed session successfully."); } public override async Task Request(string method, params object[] parameters) { if (!connected) { - throw new WalletConnectException("Can't send requests. No session is connected at the moment."); + throw new ReownIntegrationException("Can't send requests. No session is connected at the moment."); } if (SessionExpired(session)) @@ -405,7 +408,7 @@ public override async Task Request(string method, params object[] paramete } else { - throw new WalletConnectException( + throw new ReownIntegrationException( $"Failed to perform {typeof(T)} request - session expired. Please reconnect."); } } @@ -414,12 +417,11 @@ public override async Task Request(string method, params object[] paramete EventUtils.ListenOnce( OnPublishedMessage, - handler => core.Relayer.Publisher.OnPublishedMessage += handler, - handler => core.Relayer.Publisher.OnPublishedMessage -= handler); - - var chainId = GetChainId(); + handler => signClient.CoreClient.Relayer.Publisher.OnPublishedMessage += handler, + handler => signClient.CoreClient.Relayer.Publisher.OnPublishedMessage -= handler); - return await WalletConnectRequest(sessionTopic, method, chainId, parameters); + // var chainId = GetChainId(); + return await ReownRequest(sessionTopic, method, parameters); void OnPublishedMessage(object sender, PublishParams args) { @@ -430,22 +432,19 @@ void OnPublishedMessage(object sender, PublishParams args) return; } - if (localData.ConnectedLocalWalletName != null) - { - redirection.Redirect(localData.ConnectedLocalWalletName); - } + TryRedirectToWallet(); } } - private WalletModel GetSessionLocalWallet() + private WalletModel GetSessionWallet() { var nativeUrl = RemoveSlash(session.Peer.Metadata.Url); - var sessionWallet = walletRegistry - .EnumerateSupportedWallets(osMediator.Platform) + var wallet = walletRegistry + .SupportedWallets .FirstOrDefault(w => RemoveSlash(w.Homepage) == nativeUrl); - return sessionWallet; + return wallet; string RemoveSlash(string s) { @@ -455,15 +454,28 @@ string RemoveSlash(string s) } } - private void TryRedirectToWallet() + private async void TryRedirectToWallet() { - if (localData.ConnectedLocalWalletName == null) + if (sessionWallet is null) + { + return; // session wallet couldn't be determined, ignore redirection + } + + if (!await signClient.CoreClient.Storage.HasItem("ChainSafe_RecentLocalWalletId")) + { + return; // no local wallets connected - ignore redirection + } + + var recentLocalWalletId = await signClient.CoreClient.Storage.GetItem("ChainSafe_RecentLocalWalletId"); + + if (recentLocalWalletId != sessionWallet.Id) { + ReownLogger.Log("Last clicked local wallet was not used to connect the session. " + + "Assuming the wallet was connected remotely. No redirection is going to happen."); return; } - var sessionLocalWallet = GetSessionLocalWallet(); - redirection.Redirect(sessionLocalWallet); + redirection.Redirect(sessionWallet); // safe to redirect } private string GetPlayerAddress() @@ -495,13 +507,20 @@ private string GetFullAddress() return defaultNamespace.Accounts[0]; } - private async Task WalletConnectRequest(string topic, string method, string chainId, params object[] parameters) + private async Task ReownRequest(string topic, string method, params object[] parameters) { - // Helper method to make a request using WalletConnectSignClient. + // Helper method to make a request using ReownSignClient. async Task MakeRequest() { var data = (TRequest)Activator.CreateInstance(typeof(TRequest), parameters); - return await signClient.Request(topic, data, chainId); + try + { + return await signClient.Request(topic, data); + } + catch (KeyNotFoundException e) + { + throw new ReownIntegrationException("Can't execute request. The session was most likely terminated on the wallet side.", e); + } } switch (method) @@ -519,23 +538,21 @@ async Task MakeRequest() default: try { - // Direct RPC request via http, WalletConnect RPC url. - string chain = session.Namespaces.First().Value.Chains[0]; + // Direct RPC request via http, Reown RPC url. + var chain = session.Namespaces.First().Value.Chains[0]; - // Using WalletConnect Blockchain API: https://docs.walletconnect.com/cloud/blockchain-api + // Using Reown Blockchain API: https://docs.reown.com/cloud/blockchain-api var url = $"https://rpc.walletconnect.com/v1?chainId={chain}&projectId={config.ProjectId}"; - string body = JsonConvert.SerializeObject(new RpcRequestMessage(Guid.NewGuid().ToString(), method, parameters)); - - var rawResult = await httpClient.PostRaw(url, body, "application/json"); - - RpcResponseMessage response = JsonConvert.DeserializeObject(rawResult.Response); + var body = JsonConvert.SerializeObject(new RpcRequestMessage(Guid.NewGuid().ToString(), method, parameters)); + var rawResult = await reownHttpClient.PostRaw(url, body, "application/json"); + var response = JsonConvert.DeserializeObject(rawResult.Response); return response.Result.ToObject(); } catch (Exception e) { - throw new WalletConnectException($"{method} RPC method currently not implemented.", e); + throw new ReownIntegrationException($"{method} RPC method currently not implemented.", e); } } } diff --git a/src/ChainSafe.Gaming.WalletConnect/WalletConnectSubCategory.cs b/src/ChainSafe.Gaming.Reown/ReownSubCategory.cs similarity index 54% rename from src/ChainSafe.Gaming.WalletConnect/WalletConnectSubCategory.cs rename to src/ChainSafe.Gaming.Reown/ReownSubCategory.cs index 18a16a607..7afaeb705 100644 --- a/src/ChainSafe.Gaming.WalletConnect/WalletConnectSubCategory.cs +++ b/src/ChainSafe.Gaming.Reown/ReownSubCategory.cs @@ -1,12 +1,12 @@ using ChainSafe.Gaming.Web3.Core; -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown { - public class WalletConnectSubCategory : IWeb3SubCategory + public class ReownSubCategory : IWeb3SubCategory { private readonly Web3.Web3 web3; - public WalletConnectSubCategory(Web3.Web3 web3) + public ReownSubCategory(Web3.Web3 web3) { this.web3 = web3; } diff --git a/src/ChainSafe.Gaming.Reown/Storage/ReownStorageFactory.cs b/src/ChainSafe.Gaming.Reown/Storage/ReownStorageFactory.cs new file mode 100644 index 000000000..5b603d186 --- /dev/null +++ b/src/ChainSafe.Gaming.Reown/Storage/ReownStorageFactory.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using ChainSafe.Gaming.Web3.Environment; +using Newtonsoft.Json; +using Reown.Core.Storage; +using Reown.Core.Storage.Interfaces; + +namespace ChainSafe.Gaming.Reown.Storage +{ + public class ReownStorageFactory + { + private const string RelativeFilePath = "Reown/storage.json"; + + public static async Task Build(Web3Environment environment) + { + switch (environment.OperatingSystem.Platform) + { + case Platform.Editor: + case Platform.Android: + case Platform.IOS: + case Platform.Desktop: + return await BuildFileSystemStorage(environment); + case Platform.WebGL: + return BuildWebGlStorage(); + default: + throw new ReownIntegrationException($"{environment.OperatingSystem.Platform} is not supported."); + } + } + + private static async Task BuildFileSystemStorage(Web3Environment environment) + { + var storageFilePath = Path.Combine(environment.OperatingSystem.AppPersistentDataPath, RelativeFilePath); + var storage = new FileSystemStorage(storageFilePath); + + try + { + await storage.Init(); + } + catch (JsonException) + { + environment.LogWriter.LogError($"Failed to deserialize storage. Deleting it and creating a new one at {storageFilePath}"); + await storage.Clear(); + await storage.Init(); + } + + return storage; + } + + private static IKeyValueStorage BuildWebGlStorage() + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.Reown/Wallets/IWalletRegistry.cs b/src/ChainSafe.Gaming.Reown/Wallets/IWalletRegistry.cs new file mode 100644 index 000000000..de777a499 --- /dev/null +++ b/src/ChainSafe.Gaming.Reown/Wallets/IWalletRegistry.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; +using ChainSafe.Gaming.Reown.Models; + +namespace ChainSafe.Gaming.Reown.Wallets +{ + /// + /// Registry of the wallets supported by Reown. + /// + public interface IWalletRegistry + { + /// + /// Get all wallets supported on the current platform. + /// + /// Sequence of that the platform supports. + IEnumerable SupportedWallets { get; } + + /// + /// Return model for the wallet by it's ID. + /// + /// Wallet ID. + /// Wallet model. + WalletModel GetWallet(string id); + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.Reown/Wallets/ReownWalletRegistry.cs b/src/ChainSafe.Gaming.Reown/Wallets/ReownWalletRegistry.cs new file mode 100644 index 000000000..7ffd11e62 --- /dev/null +++ b/src/ChainSafe.Gaming.Reown/Wallets/ReownWalletRegistry.cs @@ -0,0 +1,106 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using ChainSafe.Gaming.Reown.Models; +using ChainSafe.Gaming.Web3.Core; +using ChainSafe.Gaming.Web3.Environment; +using ChainSafe.Gaming.Web3.Environment.Http; + +namespace ChainSafe.Gaming.Reown.Wallets +{ + /// + /// The registry of the wallets supported by Reown. + /// + public class ReownWalletRegistry : ILifecycleParticipant, IWalletRegistry // todo provide pre-downloaded registry with option to update + { + private const string Host = "https://api.web3modal.com"; + + private readonly IHttpClient reownHttpClient; + private readonly IReownConfig config; + private readonly IOperatingSystemMediator systemMediator; + + private List platformWallets; + + public ReownWalletRegistry(ReownHttpClient reownHttpClient, IReownConfig config, IOperatingSystemMediator systemMediator) + { + this.systemMediator = systemMediator; + this.config = config; + this.reownHttpClient = reownHttpClient; + } + + public static string RegistryUri => $"{Host}/getWallets"; + + public IEnumerable SupportedWallets => platformWallets.AsReadOnly(); + + async ValueTask ILifecycleParticipant.WillStartAsync() + { + var registryUri = !string.IsNullOrWhiteSpace(config.OverrideRegistryUri) + ? config.OverrideRegistryUri + : RegistryUri; + + var parameters = new Dictionary() + { + { "page", 1.ToString() }, + { "entries", 100.ToString() }, // get as many wallets as we can with one api call (when too many wallets returns 400) + { "search", null }, + { "platform", GetPlatformFilter() }, + { "include", BuildWalletIdsFilter(config.IncludeWalletIds) }, + { "exclude", BuildWalletIdsFilter(config.ExcludeWalletIds) }, + }; + + var parametersRaw = HttpUtils.BuildUriParameters(parameters); + + var response = await reownHttpClient.Get(registryUri + parametersRaw); // todo download all the available wallets in a loop + var apiFilteredWallets = platformWallets = response.AssertSuccess().Data; + platformWallets = apiFilteredWallets + .Where(w => + { + switch (systemMediator.Platform) + { + case Platform.Editor: + case Platform.Desktop: + return !string.IsNullOrWhiteSpace(w.DesktopLink); + case Platform.IOS: + case Platform.Android: + return !string.IsNullOrWhiteSpace(w.MobileLink); + case Platform.WebGL: + default: + return true; + } + }) + .ToList(); + + /* todo implement and utilize IsWalletInstalled functionality + * + var walletClosure = wallet; + var isWalletInstalled = WalletUtils.IsWalletInstalled(wallet); + */ + + return; + + string GetPlatformFilter() + { + return systemMediator.Platform switch + { + Platform.Android => "android", + Platform.IOS => "ios", + _ => null + }; + } + + string BuildWalletIdsFilter(IList walletIds) + { + return walletIds is { Count: > 0 } + ? string.Join(",", walletIds) + : null; + } + } + + ValueTask ILifecycleParticipant.WillStopAsync() => new(Task.CompletedTask); + + public WalletModel GetWallet(string id) + { + return platformWallets.Find(w => w.Id == id); + } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/WalletLocationOption.cs b/src/ChainSafe.Gaming.Reown/Wallets/WalletLocationOption.cs similarity index 81% rename from src/ChainSafe.Gaming.WalletConnect/WalletLocationOption.cs rename to src/ChainSafe.Gaming.Reown/Wallets/WalletLocationOption.cs index 1e8c3b7e8..275cf3ac2 100644 --- a/src/ChainSafe.Gaming.WalletConnect/WalletLocationOption.cs +++ b/src/ChainSafe.Gaming.Reown/Wallets/WalletLocationOption.cs @@ -1,4 +1,4 @@ -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown.Wallets { /// /// Wallet location options. diff --git a/src/ChainSafe.Gaming.WalletConnect/WalletLocationOptionsExtensions.cs b/src/ChainSafe.Gaming.Reown/Wallets/WalletLocationOptionsExtensions.cs similarity index 96% rename from src/ChainSafe.Gaming.WalletConnect/WalletLocationOptionsExtensions.cs rename to src/ChainSafe.Gaming.Reown/Wallets/WalletLocationOptionsExtensions.cs index eea8e8d06..d0aef8e44 100644 --- a/src/ChainSafe.Gaming.WalletConnect/WalletLocationOptionsExtensions.cs +++ b/src/ChainSafe.Gaming.Reown/Wallets/WalletLocationOptionsExtensions.cs @@ -1,6 +1,6 @@ using System; -namespace ChainSafe.Gaming.WalletConnect +namespace ChainSafe.Gaming.Reown.Wallets { public static class WalletLocationOptionsExtensions { diff --git a/src/ChainSafe.Gaming.Reown/Wallets/WalletRegistryResponse.cs b/src/ChainSafe.Gaming.Reown/Wallets/WalletRegistryResponse.cs new file mode 100644 index 000000000..390bb44fb --- /dev/null +++ b/src/ChainSafe.Gaming.Reown/Wallets/WalletRegistryResponse.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using ChainSafe.Gaming.Reown.Models; +using Newtonsoft.Json; + +namespace ChainSafe.Gaming.Reown.Wallets +{ + public class WalletRegistryResponse + { + [JsonProperty("count")] + public int Count { get; set; } + + [JsonProperty("data")] + public List Data { get; set; } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.Tests/ChainSafe.Gaming.Tests.csproj b/src/ChainSafe.Gaming.Tests/ChainSafe.Gaming.Tests.csproj index c2006ba78..ae9d69019 100644 --- a/src/ChainSafe.Gaming.Tests/ChainSafe.Gaming.Tests.csproj +++ b/src/ChainSafe.Gaming.Tests/ChainSafe.Gaming.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/src/ChainSafe.Gaming.Tests/Core/StubHttpClient.cs b/src/ChainSafe.Gaming.Tests/Core/StubHttpClient.cs index 288a23761..8ae9a5bd4 100644 --- a/src/ChainSafe.Gaming.Tests/Core/StubHttpClient.cs +++ b/src/ChainSafe.Gaming.Tests/Core/StubHttpClient.cs @@ -1,29 +1,37 @@ using System.Threading.Tasks; using ChainSafe.Gaming.Web3.Environment; +using ChainSafe.Gaming.Web3.Environment.Http; namespace ChainSafe.Gaming.Tests.Core { public sealed class StubHttpClient : IHttpClient { - public ValueTask> GetRaw(string url) + public ValueTask> GetRaw(string url, params HttpHeader[] headers) { // do nothing return new ValueTask>(Task.FromResult(NetworkResponse.Success("Skipped"))); } - public ValueTask> PostRaw(string url, string data, string contentType) + public ValueTask> PostRaw( + string url, + string data, + string contentType, + params HttpHeader[] headers) { // do nothing return new ValueTask>(Task.FromResult(NetworkResponse.Success("Skipped"))); } - public ValueTask> Get(string url) + public ValueTask> Get(string url, params HttpHeader[] headers) { // do nothing return new ValueTask>(Task.FromResult(NetworkResponse.Success(default))); } - public ValueTask> Post(string url, TRequest data) + public ValueTask> Post( + string url, + TRequest data, + params HttpHeader[] headers) { // do nothing return new ValueTask>(Task.FromResult(NetworkResponse.Success(default))); diff --git a/src/ChainSafe.Gaming.Tests/WalletConnectDeepLinksTests.cs b/src/ChainSafe.Gaming.Tests/WalletConnectDeepLinksTests.cs index 23241e678..b5121651d 100644 --- a/src/ChainSafe.Gaming.Tests/WalletConnectDeepLinksTests.cs +++ b/src/ChainSafe.Gaming.Tests/WalletConnectDeepLinksTests.cs @@ -7,9 +7,6 @@ using ChainSafe.Gaming.Evm.Providers; using ChainSafe.Gaming.NetCore; using ChainSafe.Gaming.Tests.Core; -using ChainSafe.Gaming.WalletConnect; -using ChainSafe.Gaming.WalletConnect.Models; -using ChainSafe.Gaming.WalletConnect.Wallets; using ChainSafe.Gaming.Web3.Build; using ChainSafe.Gaming.Web3.Core; using ChainSafe.Gaming.Web3.Environment; @@ -18,7 +15,7 @@ namespace ChainSafe.Gaming.Tests { - // [TestFixture] // todo unstable currently; uncomment after new version of WalletRegistry with pre-downloaded, filtered list of wallets introduced + // [TestFixture] // todo unstable currently; uncomment after new version of WalletRegistry with pre-downloaded filtered list of wallets gets introduced // public class WalletConnectDeepLinksTests // { // private static readonly List KnownBrokenWalletsIos = new() // todo note in the documentation diff --git a/src/ChainSafe.Gaming.Unity/ChainSafe.Gaming.Unity.csproj b/src/ChainSafe.Gaming.Unity/ChainSafe.Gaming.Unity.csproj index 72c0e1294..1304c7f28 100644 --- a/src/ChainSafe.Gaming.Unity/ChainSafe.Gaming.Unity.csproj +++ b/src/ChainSafe.Gaming.Unity/ChainSafe.Gaming.Unity.csproj @@ -20,7 +20,7 @@ - + diff --git a/src/ChainSafe.Gaming.Unity/UnityHttpClient.cs b/src/ChainSafe.Gaming.Unity/UnityHttpClient.cs index 95c7b1f78..85b25265d 100644 --- a/src/ChainSafe.Gaming.Unity/UnityHttpClient.cs +++ b/src/ChainSafe.Gaming.Unity/UnityHttpClient.cs @@ -1,8 +1,7 @@ using System.Text; using System.Threading.Tasks; -using ChainSafe.Gaming.Unity; using ChainSafe.Gaming.Web3.Environment; -using Newtonsoft.Json; +using ChainSafe.Gaming.Web3.Environment.Http; using UnityEngine.Assertions; using UnityEngine.Networking; @@ -25,60 +24,38 @@ public UnityHttpClient(IMainThreadRunner mainThreadRunner) this.mainThreadRunner = mainThreadRunner; } - /// - /// Converts the UnityWebRequest response to a structured NetworkResponse. - /// - /// The Unity web request instance. - /// Converted Network Response. - private static NetworkResponse UnityWebRequestToNetworkResponse(UnityWebRequest request) + public ValueTask> GetRaw(string url, params HttpHeader[] headers) { - // Assert response is successful + return new ValueTask>(mainThreadRunner.EnqueueTask(async () => { - Assert.AreNotEqual(UnityWebRequest.Result.InProgress, request.result); + using var request = UnityWebRequest.Get(url); - if (request.result == UnityWebRequest.Result.ConnectionError) + foreach (var header in headers) { - throw new Web3Exception($"HTTP.{request.method} to '{request.url}' - connection error."); + request.SetRequestHeader(header.Name, header.Value); } - if (request.result != UnityWebRequest.Result.Success) - { - throw new Web3Exception( - $"HTTP.{request.method} to '{request.url}' responded with error: {request.downloadHandler.text}"); - } - } - - return NetworkResponse.Success(request.downloadHandler.text); - } - - /// - /// Sends a GET request to the specified URL and retrieves the raw response. - /// - /// The target URL. - /// A value task that completes with the network response. - public ValueTask> GetRaw(string url) - { - return new ValueTask>(mainThreadRunner.EnqueueTask(async () => - { - using var request = UnityWebRequest.Get(url); request.downloadHandler = new DownloadHandlerBuffer(); await request.SendWebRequest(); return UnityWebRequestToNetworkResponse(request); })); } - /// - /// Sends a POST request to the specified URL with the provided raw data. - /// - /// The target URL. - /// The raw data to be sent as the request body. - /// The MIME type of the request data. - /// A value task that completes with the network response. - public ValueTask> PostRaw(string url, string data, string contentType) + public ValueTask> PostRaw( + string url, + string data, + string contentType, + params HttpHeader[] headers) { return new ValueTask>(mainThreadRunner.EnqueueTask(async () => { using var request = new UnityWebRequest(url, "POST"); + + foreach (var header in headers) + { + request.SetRequestHeader(header.Name, header.Value); + } + request.uploadHandler = new UploadHandlerRaw(new UTF8Encoding().GetBytes(data)); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", contentType); @@ -88,50 +65,29 @@ public ValueTask> PostRaw(string url, string data, strin } /// - /// Sends a GET request to the specified URL and deserializes the response into the desired type. + /// Converts the UnityWebRequest response to a structured NetworkResponse. /// - /// The type to deserialize the response into. - /// The target URL. - /// A value task that completes with the network response. - public async ValueTask> Get(string url) + /// The Unity web request instance. + /// Converted Network Response. + private static NetworkResponse UnityWebRequestToNetworkResponse(UnityWebRequest request) { - var response = await GetRaw(url); - return response.Map(x => + // Assert response is successful { - try - { - return JsonConvert.DeserializeObject(x); - } - catch (JsonReaderException e) - { - throw new Web3Exception($"Tried deserializing response, but failed.\nMessage:{e.Message}\nResponse body:\n{x}"); - } - }); - } + Assert.AreNotEqual(UnityWebRequest.Result.InProgress, request.result); - /// - /// Sends a POST request to the specified URL with the provided data and deserializes the response into the desired type. - /// - /// The type of the request data. - /// The type to deserialize the response into. - /// The target URL. - /// The data to be sent as the request body. - /// A value task that completes with the network response. - public async ValueTask> Post(string url, TRequest data) - { - var requestJson = JsonConvert.SerializeObject(data); - var response = await PostRaw(url, requestJson, "application/json"); - return response.Map(x => - { - try + if (request.result == UnityWebRequest.Result.ConnectionError) { - return JsonConvert.DeserializeObject(x); + throw new Web3Exception($"HTTP.{request.method} to '{request.url}' - connection error."); } - catch (JsonReaderException e) + + if (request.result != UnityWebRequest.Result.Success) { - throw new Web3Exception($"Tried deserializing response, but failed.\nMessage:{e.Message}\nResponse body:\n{x}"); + throw new Web3Exception( + $"HTTP.{request.method} to '{request.url}' responded with error: {request.downloadHandler.text}"); } - }); + } + + return NetworkResponse.Success(request.downloadHandler.text); } } } diff --git a/src/ChainSafe.Gaming.Unity/link.xml b/src/ChainSafe.Gaming.Unity/link.xml index aab5532f7..9b1f50c70 100644 --- a/src/ChainSafe.Gaming.Unity/link.xml +++ b/src/ChainSafe.Gaming.Unity/link.xml @@ -19,7 +19,7 @@ - + diff --git a/src/ChainSafe.Gaming.WalletConnect/Models/ChainModel.cs b/src/ChainSafe.Gaming.WalletConnect/Models/ChainModel.cs deleted file mode 100644 index 1111b1f19..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/Models/ChainModel.cs +++ /dev/null @@ -1,48 +0,0 @@ -namespace ChainSafe.Gaming.WalletConnect.Models -{ - /// - /// Chain model containing fields used for Wallet Connect. - /// - public class ChainModel - { - /// - /// Default namespace for EVM. - /// - public const string EvmNamespace = "eip155"; - - /// - /// Initializes a new instance of the class. - /// - /// Chain Namespace - example "eip155:" for EVMs. - /// Chain Id. - /// Name of the network. - public ChainModel(string chainNamespace, string chainId, string name) - { - ChainNamespace = chainNamespace; - - ChainId = chainId; - - Name = name; - } - - /// - /// Chain Namespace - example "eip155:" for EVMs. - /// - public string ChainNamespace { get; private set; } - - /// - /// Chain Id. - /// - public string ChainId { get; private set; } - - /// - /// Name of the network. - /// - public string Name { get; private set; } - - /// - /// Full chain Id, together with . - /// - public string FullChainId => $"{ChainNamespace}:{ChainId}"; - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/Models/ImageUrlsModel.cs b/src/ChainSafe.Gaming.WalletConnect/Models/ImageUrlsModel.cs deleted file mode 100644 index 36a943e12..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/Models/ImageUrlsModel.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Newtonsoft.Json; - -namespace ChainSafe.Gaming.WalletConnect.Models -{ - /// - /// Wallet Connect Model used in for Wallet's image url if any. - /// - public class ImageUrlsModel - { - /// - /// Small size wallet icon image url. - /// - [JsonProperty("sm")] - public string SmallUrl { get; private set; } - - /// - /// Medium size wallet icon image url. - /// - [JsonProperty("md")] - public string MediumUrl { get; private set; } - - /// - /// Large size wallet icon image url. - /// - [JsonProperty("lg")] - public string LargeUrl { get; private set; } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/Models/WalletLinkModel.cs b/src/ChainSafe.Gaming.WalletConnect/Models/WalletLinkModel.cs deleted file mode 100644 index ba2264433..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/Models/WalletLinkModel.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Newtonsoft.Json; - -namespace ChainSafe.Gaming.WalletConnect.Models -{ - /// - /// Wallet linking model used for opening/redirecting to wallets using a deeplink from either a Native or a Universal/http protocol. - /// - public struct WalletLinkModel - { - /// - /// Native protocol deeplink for redirecting to wallet. - /// If available this redirects without opening a browser. - /// - [JsonProperty("native")] - public string NativeProtocol { get; private set; } - - /// - /// Universal url deeplink for redirecting to wallet. - /// If available this opens a browser that triggers a native deeplink. - /// - [JsonProperty("universal")] - public string UniversalUrl { get; private set; } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/Models/WalletModel.cs b/src/ChainSafe.Gaming.WalletConnect/Models/WalletModel.cs deleted file mode 100644 index 201e113c8..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/Models/WalletModel.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Newtonsoft.Json; - -namespace ChainSafe.Gaming.WalletConnect.Models -{ - /// - /// WalletConnect wallet model used for identifying and redirecting wallets. - /// - public class WalletModel - { - /// - /// Id of the wallet. - /// - [JsonProperty("id")] - public string Id { get; private set; } - - /// - /// Name of the wallet. - /// - [JsonProperty("name")] - public string Name { get; private set; } - - /// - /// Description of the wallet. - /// - [JsonProperty("description")] - public string Description { get; private set; } - - /// - /// Homepage of the wallet. - /// - [JsonProperty("homepage")] - public string Homepage { get; private set; } - - /// - /// for mobile platforms. - /// - [JsonProperty("mobile")] - public WalletLinkModel Mobile { get; private set; } - - /// - /// for desktop platforms. - /// - [JsonProperty("desktop")] - public WalletLinkModel Desktop { get; private set; } - - /// - /// wallet icons urls. - /// - [JsonProperty("image_url")] - public ImageUrlsModel Images { get; private set; } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/RedirectionHandler.cs b/src/ChainSafe.Gaming.WalletConnect/RedirectionHandler.cs deleted file mode 100644 index 33ca9e7eb..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/RedirectionHandler.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System.Web; -using ChainSafe.Gaming.WalletConnect.Models; -using ChainSafe.Gaming.WalletConnect.Wallets; -using ChainSafe.Gaming.Web3.Environment; - -namespace ChainSafe.Gaming.WalletConnect -{ - /// - /// Component responsible for redirection of a user to a wallet app. - /// - public class RedirectionHandler - { - private readonly IWalletRegistry walletRegistry; - private readonly IOperatingSystemMediator osMediator; - private readonly ILogWriter logWriter; - - public RedirectionHandler(IWalletRegistry walletRegistry, IOperatingSystemMediator osMediator, ILogWriter logWriter) - { - this.logWriter = logWriter; - this.osMediator = osMediator; - this.walletRegistry = walletRegistry; - } - - private static bool NativeProtocolAvailable(WalletLinkModel linkData) - { - return !string.IsNullOrWhiteSpace(linkData.NativeProtocol) && linkData.NativeProtocol != ":"; - } - - private static bool UniversalProtocolAvailable(WalletLinkModel linkData) - { - return !string.IsNullOrWhiteSpace(linkData.UniversalUrl); - } - - /// - /// Redirect for connection using the pre-selected wallet. - /// - /// The connection URI provided by WalletConnect. - /// The name of the wallet to redirect user to. - public void RedirectConnection(string connectionUri, string walletName) - { - var walletData = walletRegistry.GetWallet(walletName); - var deeplink = BuildConnectionDeeplink(walletData, connectionUri); - - logWriter.Log($"Generated deep link: {deeplink}"); - - if (osMediator.IsMobilePlatform && osMediator.IsEditor) - { - logWriter.Log("Can't open mobile deeplink in editor. Ignoring.."); - return; - } - - osMediator.OpenUrl(deeplink); - } - - /// - /// Delegate redirection for connection to the OS. - /// - /// The connection URI provided by WalletConnect. - public void RedirectConnectionOsManaged(string connectionUri) - { - logWriter.Log($"Connection URI: {connectionUri}"); - - if (osMediator.IsMobilePlatform && osMediator.IsEditor) - { - logWriter.Log($"Can't open mobile connection URI in editor. Ignoring.."); - return; - } - - osMediator.OpenUrl(connectionUri); - } - - /// - /// Redirect to the pre-selected wallet using the wallet name. - /// - public void Redirect(string walletName) - { - var walletData = walletRegistry.GetWallet(walletName); - Redirect(walletData); - } - - /// - /// Redirect to the pre-selected wallet. - /// - public void Redirect(WalletModel walletData) - { - var deepLink = GetRedirectionDeeplink(walletData); - osMediator.OpenUrl(deepLink); - } - - /// - /// Used to get a redirection deeplink for the . - /// - /// Data of the wallet that we want to redirect to. - /// Deeplink for redirection. - public string GetRedirectionDeeplink(WalletModel walletData) - { - var linkData = GetPlatformLinkData(walletData); - var deeplink = GetPlatformDeeplink(); - return deeplink; - - string GetPlatformDeeplink() - { - if (osMediator.Platform != Platform.IOS) - { - return NativeProtocolAvailable(linkData) ? linkData.NativeProtocol : linkData.UniversalUrl; - } - else - { - return UniversalProtocolAvailable(linkData) ? linkData.UniversalUrl : linkData.NativeProtocol; - } - } - } - - /// - /// Used to get a connection deeplink for the particular wallet. - /// - /// Data of the wallet that we want to connect. - /// The connection URI provided by WalletConnect. - /// Deeplink for connection. - /// Invalid format of deeplink registered for the provided wallet. - public string BuildConnectionDeeplink(WalletModel walletData, string connectionUri) - { - if (string.IsNullOrWhiteSpace(connectionUri)) - { - throw new WalletConnectException("Can not build a connection deep link. The connection URI is empty."); - } - - var linkData = GetPlatformLinkData(walletData); - var platformUrl = BuildPlatformUrl(); - - var finalUrl = $"{platformUrl}wc?uri={HttpUtility.UrlEncode(connectionUri)}"; // use System.Uri.EscapeDataString(uri) if this doesn't work - - return finalUrl; - - string BuildPlatformUrl() - { - if (osMediator.Platform != Platform.IOS) - { - return NativeProtocolAvailable(linkData) ? BuildNativeUrl() : BuildUniversalUrl(); - } - else - { - return UniversalProtocolAvailable(linkData) ? BuildUniversalUrl() : BuildNativeUrl(); - } - } - - string BuildNativeUrl() - { - var nativeUrl = linkData.NativeProtocol; - - if (!nativeUrl.Contains(':')) - { - throw new WalletConnectException( - $"Native protocol deeplink for {walletData.Name} had incorrect format: no \":\" symbol."); - } - - var pureProtocolStringLength = nativeUrl.IndexOf(':') + 1; - var pureProtocol = nativeUrl[..pureProtocolStringLength]; - return $"{pureProtocol}//"; - } - - string BuildUniversalUrl() - { - var universalUrl = linkData.UniversalUrl; - - if (!universalUrl.EndsWith('/')) - { - universalUrl += '/'; - } - - return universalUrl; - } - } - - private WalletLinkModel GetPlatformLinkData(WalletModel walletData) - { - return osMediator.IsMobilePlatform ? walletData.Mobile : walletData.Desktop; - } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/Storage/DataStorage.cs b/src/ChainSafe.Gaming.WalletConnect/Storage/DataStorage.cs deleted file mode 100644 index 04366b4ae..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/Storage/DataStorage.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System; -using System.IO; -using System.Threading.Tasks; -using ChainSafe.Gaming.Web3.Environment; -using Newtonsoft.Json; -using WalletConnectSharp.Common.Logging; -using WalletConnectSharp.Storage; - -namespace ChainSafe.Gaming.WalletConnect.Storage -{ - /// - /// Default implementation of the component responsible for storage of WalletConnect-related data. - /// - public class DataStorage - { - private const string StorageFileName = "walletconnect-storage.json"; - private const string LocalDataFileName = "walletconnect-local.json"; - - private readonly IWalletConnectConfig config; - private readonly IOperatingSystemMediator osMediator; - private readonly ILogWriter logWriter; - - public DataStorage(IWalletConnectConfig config, IOperatingSystemMediator osMediator, ILogWriter logWriter) - { - this.logWriter = logWriter; - this.osMediator = osMediator; - this.config = config; - } - - /// - /// Loads local data for the WalletConnect integration. - /// - /// Local data for the WalletConnect integration. - public async Task LoadLocalData() - { - var path = BuildLocalDataPath(); - if (!File.Exists(path)) - { - return null; - } - - try - { - var json = await File.ReadAllTextAsync(path); - return JsonConvert.DeserializeObject(json); - } - catch - { - logWriter.LogError("WalletConnect local data file is corrupted. Removing.."); - File.Delete(path); - return null; - } - } - - /// - /// Saves local data for the WalletConnect integration. - /// - /// The data. - /// A representing the asynchronous operation. - public async Task SaveLocalData(LocalData localData) - { - var path = BuildLocalDataPath(); - var json = JsonConvert.SerializeObject(localData); - await File.WriteAllTextAsync(path, json); - } - - /// - /// Clears local data for the WalletConnect integration from the disk. - /// - public void ClearLocalData() - { - var path = BuildLocalDataPath(); - if (!File.Exists(path)) - { - return; - } - - File.Delete(path); - } - - /// - /// Builds storage for WalletConnectCSharp. - /// - /// True if the session was already stored. - /// Storage object used by WalletConnectCSharp. - public FileSystemStorage BuildStorage(bool sessionStored) - { - var absStoragePath = BuildStoragePath(osMediator.AppPersistentDataPath, config.StoragePath); - var path = Path.Combine(absStoragePath, StorageFileName); - - // If we're not restoring a session and save WC file exists remove it. - // This is done to mitigate for a WC error that happens intermittently where generated Uri doesn't connect wallet. - if (!sessionStored && File.Exists(path)) - { - File.Delete(path); - } - - GC.Collect(); - GC.WaitForPendingFinalizers(); - WCLogger.Log($"Wallet Connect Storage set to {path}"); - - return new FileSystemStorage(path); - } - - private string BuildLocalDataPath() - { - var absStoragePath = BuildStoragePath(osMediator.AppPersistentDataPath, config.StoragePath); - return Path.Combine(absStoragePath, LocalDataFileName); - } - - public static string BuildStoragePath(string appDataPath, string storageRelativePath) - { - return Path.Combine(appDataPath, storageRelativePath); - } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/Storage/LocalData.cs b/src/ChainSafe.Gaming.WalletConnect/Storage/LocalData.cs deleted file mode 100644 index 0096a274b..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/Storage/LocalData.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace ChainSafe.Gaming.WalletConnect.Storage -{ - /// - /// A class representing a local data used by the WalletConnect integration. - /// - public class LocalData - { - /// - /// Session topic used to restore previously connected session. - /// - public string SessionTopic { get; set; } - - /// - /// The name of the locally connected wallet. - /// - public string ConnectedLocalWalletName { get; set; } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/WalletConnectException.cs b/src/ChainSafe.Gaming.WalletConnect/WalletConnectException.cs deleted file mode 100644 index c3ba6de16..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/WalletConnectException.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using ChainSafe.Gaming.Web3; - -namespace ChainSafe.Gaming.WalletConnect -{ - /// - /// Represents exception related to the WalletConnect integration. - /// - public class WalletConnectException : Web3Exception - { - public WalletConnectException(string message) - : base(message) - { - } - - public WalletConnectException(string message, Exception innerException) - : base(message, innerException) - { - } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/WalletConnectExtensions.cs b/src/ChainSafe.Gaming.WalletConnect/WalletConnectExtensions.cs deleted file mode 100644 index fa1a83d36..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/WalletConnectExtensions.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System.Linq; -using ChainSafe.Gaming.Evm.Providers; -using ChainSafe.Gaming.Evm.Signers; -using ChainSafe.Gaming.WalletConnect.Storage; -using ChainSafe.Gaming.WalletConnect.Wallets; -using ChainSafe.Gaming.Web3.Build; -using ChainSafe.Gaming.Web3.Core; -using ChainSafe.Gaming.Web3.Core.Evm; -using ChainSafe.Gaming.Web3.Core.Logout; -using ChainSafe.Gaming.Web3.Evm.Wallet; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace ChainSafe.Gaming.WalletConnect -{ - public static class WalletConnectExtensions - { - /// - /// Use this to enable WalletConnect functionality for this instance of Web3. - /// - /// The same service collection that was passed in. This enables fluent style. - private static IWeb3ServiceCollection UseWalletConnect(this IWeb3ServiceCollection services) - { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - - return services; - } - - /// - /// Use this to enable WalletConnect functionality for this instance of Web3. - /// - /// The same service collection that was passed in. This enables fluent style. - public static IWeb3ServiceCollection UseWalletConnect(this IWeb3ServiceCollection services, IWalletConnectConfig config) - { - services = UseWalletConnect(services); - - services.Replace(ServiceDescriptor.Singleton(typeof(IWalletConnectConfig), config)); - - return services.UseWalletProvider(config); - } - - /// - /// Access additional services related to WalletConnect. - /// - /// The WalletConnect subcategory of services. - public static WalletConnectSubCategory WalletConnect(this Web3.Web3 web3) - { - return new WalletConnectSubCategory(web3); - } - - /// - /// Access the service. - /// - /// The service. - public static IWalletRegistry WalletRegistry(this WalletConnectSubCategory walletConnect) - { - return ((IWeb3SubCategory)walletConnect).Web3.ServiceProvider.GetRequiredService(); - } - - /// - /// Access the service. - /// - /// The service. - public static RedirectionHandler RedirectionHandler(this WalletConnectSubCategory walletConnect) - { - return ((IWeb3SubCategory)walletConnect).Web3.ServiceProvider.GetRequiredService(); - } - - /// - /// Access the service. - /// - /// The service. - public static IConnectionHelper ConnectionHelper(this WalletConnectSubCategory walletConnect) - { - return ((IWeb3SubCategory)walletConnect).Web3.ServiceProvider.GetRequiredService(); - } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/Wallets/IWalletRegistry.cs b/src/ChainSafe.Gaming.WalletConnect/Wallets/IWalletRegistry.cs deleted file mode 100644 index d2540769a..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/Wallets/IWalletRegistry.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Collections.Generic; -using ChainSafe.Gaming.WalletConnect.Models; -using ChainSafe.Gaming.Web3.Environment; - -namespace ChainSafe.Gaming.WalletConnect.Wallets -{ - /// - /// Registry of the wallets supported by WalletConnect. - /// - public interface IWalletRegistry - { - /// - /// Return model for the wallet by it's name. - /// - /// The name of the wallet. - /// Wallet model. - WalletModel GetWallet(string name); - - /// - /// Enumerates through all wallets supported on the specified platform. - /// - /// The platform. - /// Sequence of that the platform supports. - IEnumerable EnumerateSupportedWallets(Platform platform); - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/Wallets/WalletRegistry.cs b/src/ChainSafe.Gaming.WalletConnect/Wallets/WalletRegistry.cs deleted file mode 100644 index 5d788c698..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/Wallets/WalletRegistry.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using ChainSafe.Gaming.WalletConnect.Models; -using ChainSafe.Gaming.Web3.Core; -using ChainSafe.Gaming.Web3.Environment; -using WalletConnectSharp.Common.Logging; - -namespace ChainSafe.Gaming.WalletConnect.Wallets -{ - /// - /// The registry of the wallets supported by WalletConnect. - /// - public class WalletRegistry : ILifecycleParticipant, IWalletRegistry // todo provide pre-downloaded registry with option to update - { - private readonly IHttpClient httpClient; - private readonly IWalletConnectConfig config; - - private List enabledWallets; - - public WalletRegistry(IHttpClient httpClient, IWalletConnectConfig config) - { - this.config = config; - this.httpClient = httpClient; - } - - public static string BuildRegistryUri(string projectId) => - $"https://explorer-api.walletconnect.com/v3/wallets?projectId={projectId}"; - - async ValueTask ILifecycleParticipant.WillStartAsync() - { - var registryUri = !string.IsNullOrWhiteSpace(config.OverrideRegistryUri) - ? config.OverrideRegistryUri - : BuildRegistryUri(config.ProjectId); - - var response = await httpClient.Get(registryUri); - var allWallets = response.AssertSuccess().Listings; - - if (config.EnabledWallets != null && config.EnabledWallets.Any()) - { - enabledWallets = allWallets.Values - .Where(w => config.EnabledWallets.Contains(w.Name)) - .ToList(); - - return; - } - - if (config.DisabledWallets != null && config.DisabledWallets.Any()) - { - enabledWallets = allWallets.Values - .Where(w => !config.DisabledWallets.Contains(w.Name)) - .ToList(); - - return; - } - - enabledWallets = allWallets.Values.ToList(); - } - - ValueTask ILifecycleParticipant.WillStopAsync() => new(Task.CompletedTask); - - public WalletModel GetWallet(string name) // todo refactor this class to use walletId for identification - { - return enabledWallets.Find(w => w.Name == name); - } - - public IEnumerable EnumerateSupportedWallets(Platform platform) - { - return enabledWallets.Where(w => IsAvailableForPlatform(w, platform)); - } - - /// - /// Is a wallet available for . - /// - /// Platform to wallet app availability. - /// True if wallet is available for . - private bool IsAvailableForPlatform(WalletModel wallet, Platform platform) - { - switch (platform) - { - case Platform.Editor: - case Platform.Desktop: - return CanUseNativeProtocol(false) || !string.IsNullOrEmpty(wallet.Desktop.UniversalUrl); - - case Platform.Android: - case Platform.IOS: - return CanUseNativeProtocol(true) || !string.IsNullOrEmpty(wallet.Mobile.UniversalUrl); - - // currently Wallet Connect doesn't support WebGL. - default: - WCLogger.Log($"Unsupported Platform {platform}"); - return false; - } - - bool CanUseNativeProtocol(bool isMobilePlatform) - { - var nativeUrl = GetLinkData(isMobilePlatform).NativeProtocol; - return !string.IsNullOrWhiteSpace(nativeUrl) && nativeUrl != ":"; - } - - WalletLinkModel GetLinkData(bool isMobilePlatform) - { - return isMobilePlatform ? wallet.Mobile : wallet.Desktop; - } - } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming.WalletConnect/Wallets/WalletRegistryResponse.cs b/src/ChainSafe.Gaming.WalletConnect/Wallets/WalletRegistryResponse.cs deleted file mode 100644 index 3f99d67d3..000000000 --- a/src/ChainSafe.Gaming.WalletConnect/Wallets/WalletRegistryResponse.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Collections.Generic; -using ChainSafe.Gaming.WalletConnect.Models; -using Newtonsoft.Json; - -namespace ChainSafe.Gaming.WalletConnect.Wallets -{ - public class WalletRegistryResponse - { - [JsonProperty("listings")] - public Dictionary Listings { get; set; } - } -} \ No newline at end of file diff --git a/src/ChainSafe.Gaming/Web3/Core/Environment/Http/HttpHeader.cs b/src/ChainSafe.Gaming/Web3/Core/Environment/Http/HttpHeader.cs new file mode 100644 index 000000000..603e625e7 --- /dev/null +++ b/src/ChainSafe.Gaming/Web3/Core/Environment/Http/HttpHeader.cs @@ -0,0 +1,9 @@ +namespace ChainSafe.Gaming.Web3.Environment.Http +{ + public struct HttpHeader + { + public string Name { get; set; } + + public string Value { get; set; } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming/Web3/Core/Environment/Http/HttpUtils.cs b/src/ChainSafe.Gaming/Web3/Core/Environment/Http/HttpUtils.cs new file mode 100644 index 000000000..a6e56cd0e --- /dev/null +++ b/src/ChainSafe.Gaming/Web3/Core/Environment/Http/HttpUtils.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; +using System.Linq; + +namespace ChainSafe.Gaming.Web3.Environment.Http +{ + public static class HttpUtils + { + public static string BuildUriParameters(Dictionary parameters) + { + var parametersRaw = parameters + .Where(p => !string.IsNullOrWhiteSpace(p.Value)) + .Select(pair => $"{pair.Key}={pair.Value}"); + + return $"?{string.Join("&", parametersRaw)}"; + } + } +} \ No newline at end of file diff --git a/src/ChainSafe.Gaming/Web3/Core/Environment/IHttpClient.cs b/src/ChainSafe.Gaming/Web3/Core/Environment/IHttpClient.cs index f596d5fa9..03674e6d1 100644 --- a/src/ChainSafe.Gaming/Web3/Core/Environment/IHttpClient.cs +++ b/src/ChainSafe.Gaming/Web3/Core/Environment/IHttpClient.cs @@ -1,5 +1,7 @@ using System; using System.Threading.Tasks; +using ChainSafe.Gaming.Web3.Environment.Http; +using Newtonsoft.Json; namespace ChainSafe.Gaming.Web3.Environment { @@ -12,8 +14,9 @@ public interface IHttpClient /// Makes a GET request. /// /// URL to send request to. + /// Set of headers to use with the HTTP request. /// Server response. - ValueTask> GetRaw(string url); + ValueTask> GetRaw(string url, params HttpHeader[] headers); /// /// Makes a POST request. @@ -21,26 +24,65 @@ public interface IHttpClient /// URL to send request to. /// Data to send. /// Content type of the data (ex. 'application/json'). + /// Set of headers to use with the HTTP request. /// Server response. - ValueTask> PostRaw(string url, string data, string contentType); + ValueTask> PostRaw( + string url, + string data, + string contentType, + params HttpHeader[] headers); /// /// Makes a GET request. Deserializes response from JSON to the specified type. /// /// URL to send request to. + /// Set of headers to use with the HTTP request. /// Type of the response data. /// Server response. - ValueTask> Get(string url); + async ValueTask> Get(string url, params HttpHeader[] headers) + { + var response = await GetRaw(url, headers); + return response.Map(x => + { + try + { + return JsonConvert.DeserializeObject(x); + } + catch (JsonReaderException e) + { + throw new Web3Exception($"Tried deserializing response, but failed.\nMessage:{e.Message}\nResponse body:\n{x}"); + } + }); + } /// /// Makes a POST request. Handles JSON serialization/deserialization of request and response for the specified types. /// /// URL to send request to. /// Data object to send. + /// Set of headers to use with the HTTP request. /// Type of content used for request. /// Type of content expected as the response. /// Server response. - ValueTask> Post(string url, TRequest data); + async ValueTask> Post( + string url, + TRequest data, + params HttpHeader[] headers) + { + var requestJson = JsonConvert.SerializeObject(data); + var response = await PostRaw(url, requestJson, "application/json", headers); + return response.Map(x => + { + try + { + return JsonConvert.DeserializeObject(x); + } + catch (JsonReaderException e) + { + throw new Web3Exception($"Tried deserializing response, but failed.\nMessage:{e.Message}\nResponse body:\n{x}"); + } + }); + } } /// diff --git a/src/UnitySampleProject/Assets/Resources/ReownConnectionProvider.asset b/src/UnitySampleProject/Assets/Resources/ReownConnectionProvider.asset new file mode 100644 index 000000000..ecc61d490 --- /dev/null +++ b/src/UnitySampleProject/Assets/Resources/ReownConnectionProvider.asset @@ -0,0 +1,35 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 582efc0fde77aab43a77ee4237ba305a, type: 3} + m_Name: ReownConnectionProvider + m_EditorClassIdentifier: + handlerPrefab: {fileID: 5250797134093199901, guid: 0c7c312ad6c521f4b8346ed8e9d7c664, type: 3} + includeWalletIds: [] + excludeWalletIds: [] + k__BackingField: 214bf16d1d17a589e2d54d49fefa2259 + k__BackingField: Web3.Unity + k__BackingField: 1 + k__BackingField: unity-game + k__BackingField: + Description: web3.unity is an open-source gaming SDK. + Icons: [] + Name: Web3.Unity + Redirect: + Native: + Universal: + Url: https://chainsafe.io/ + VerifyUrl: + k__BackingField: + k__BackingField: 1 + k__BackingField: 0 + k__BackingField: {fileID: 21300000, guid: 9af22e71d3035844ca8ae6e9f2a538f5, type: 3} + k__BackingField: Reown diff --git a/src/UnitySampleProject/Assets/Resources/WalletConnectConnectionProvider.asset.meta b/src/UnitySampleProject/Assets/Resources/ReownConnectionProvider.asset.meta similarity index 64% rename from src/UnitySampleProject/Assets/Resources/WalletConnectConnectionProvider.asset.meta rename to src/UnitySampleProject/Assets/Resources/ReownConnectionProvider.asset.meta index 144f2e5ed..86c09a5da 100644 --- a/src/UnitySampleProject/Assets/Resources/WalletConnectConnectionProvider.asset.meta +++ b/src/UnitySampleProject/Assets/Resources/ReownConnectionProvider.asset.meta @@ -1,8 +1,8 @@ fileFormatVersion: 2 -guid: 0d7bd7ae4b3e79d489bbc54514343f5c +guid: cad6fa48701480044a2a6f2d9c9dae1e NativeFormatImporter: externalObjects: {} - mainObjectFileID: 0 + mainObjectFileID: 11400000 userData: assetBundleName: assetBundleVariant: diff --git a/src/UnitySampleProject/Assets/Resources/WalletConnectConnectionProvider.asset b/src/UnitySampleProject/Assets/Resources/WalletConnectConnectionProvider.asset deleted file mode 100644 index 898e6651f..000000000 --- a/src/UnitySampleProject/Assets/Resources/WalletConnectConnectionProvider.asset +++ /dev/null @@ -1,44 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!114 &11400000 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 0} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 582efc0fde77aab43a77ee4237ba305a, type: 3} - m_Name: WalletConnectConnectionProvider - m_EditorClassIdentifier: - k__BackingField: WalletConnect - k__BackingField: {fileID: 8599114313589093787, guid: 4591cfadb2bf9824da90ebf4005728a8, type: 3} - k__BackingField: 1 - k__BackingField: f4bff60eb260841f46b1c77588cd8acb - k__BackingField: Web3.Unity - k__BackingField: 1 - k__BackingField: unity-game - k__BackingField: - Name: Web3.Unity - Description: web3.unity is an open-source gaming SDK written in C# and developed - by ChainSafe Gaming. It connects games built in the Unity game engine to the - blockchain. The library currently supports games built for web browsers (WebGL), - iOS/Android mobile, and desktop. web3.unity is compatible with most EVM-based - chains such as Ethereum, Polygon, Moonbeam, Cronos, Nervos, and Binance Smart - Chain, letting developers easily choose and switch between them to create the - best in-game experience. - Url: https://chainsafe.io/ - Icons: [] - Redirect: - Native: - Universal: - VerifyUrl: - k__BackingField: wallet-connect/ - k__BackingField: - handlerPrefab: {fileID: 5250797134093199901, guid: 0c7c312ad6c521f4b8346ed8e9d7c664, type: 3} - enabledWallets: [] - disabledWallets: [] - k__BackingField: 1 - connectionHandlerProvider: {fileID: 11400000, guid: cdc198015a446e54794e5921e5aa81ef, type: 2} - k__BackingField: 0 diff --git a/src/UnitySampleProject/Assets/link.xml b/src/UnitySampleProject/Assets/link.xml index 269e4a760..e9a2ce145 100644 --- a/src/UnitySampleProject/Assets/link.xml +++ b/src/UnitySampleProject/Assets/link.xml @@ -1,13 +1,13 @@ - + - - + + - - - + + + \ No newline at end of file diff --git a/src/UnitySampleProject/UnitySampleProject.sln.DotSettings b/src/UnitySampleProject/UnitySampleProject.sln.DotSettings index ef25ec43b..3dfca1812 100644 --- a/src/UnitySampleProject/UnitySampleProject.sln.DotSettings +++ b/src/UnitySampleProject/UnitySampleProject.sln.DotSettings @@ -1,2 +1,3 @@  - True \ No newline at end of file + True + True \ No newline at end of file