From 73c72bc4c12a95c4e68a5dba947b729d88185415 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Thu, 17 Apr 2025 08:47:56 +0530 Subject: [PATCH 01/25] feat: auth-service v10 changes --- .../Web3AuthSDK/Samples/LoginVerifier.cs | 6 +- .../Web3AuthSDK/Samples/Web3AuthSample.cs | 61 ++++++++++--------- .../Types/{Provider.cs => AUTH_CONNECTION.cs} | 2 +- .../{TypeOfLogin.cs => AuthConnection.cs} | 2 +- ...nConfigItem.cs => AuthConnectionConfig.cs} | 6 +- .../Web3AuthSDK/Types/LoginConfigItem.cs.meta | 11 ---- .../Plugins/Web3AuthSDK/Types/LoginParams.cs | 2 +- .../Web3AuthSDK/Types/Provider.cs.meta | 11 ---- .../Web3AuthSDK/Types/TypeOfLogin.cs.meta | 11 ---- Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs | 6 +- .../Web3AuthSDK/Types/Web3AuthOptions.cs | 2 +- Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 28 ++++----- 12 files changed, 58 insertions(+), 90 deletions(-) rename Assets/Plugins/Web3AuthSDK/Types/{Provider.cs => AUTH_CONNECTION.cs} (97%) rename Assets/Plugins/Web3AuthSDK/Types/{TypeOfLogin.cs => AuthConnection.cs} (97%) rename Assets/Plugins/Web3AuthSDK/Types/{LoginConfigItem.cs => AuthConnectionConfig.cs} (77%) delete mode 100644 Assets/Plugins/Web3AuthSDK/Types/LoginConfigItem.cs.meta delete mode 100644 Assets/Plugins/Web3AuthSDK/Types/Provider.cs.meta delete mode 100644 Assets/Plugins/Web3AuthSDK/Types/TypeOfLogin.cs.meta diff --git a/Assets/Plugins/Web3AuthSDK/Samples/LoginVerifier.cs b/Assets/Plugins/Web3AuthSDK/Samples/LoginVerifier.cs index d2a7cd8..2c485d8 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/LoginVerifier.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/LoginVerifier.cs @@ -1,10 +1,10 @@ public class LoginVerifier { public string name { get; set; } - public Provider loginProvider { get; set; } + public AUTH_CONNECTION authConnection { get; set; } - public LoginVerifier(string name, Provider loginProvider) + public LoginVerifier(string name, AUTH_CONNECTION authConnection) { this.name = name; - this.loginProvider = loginProvider; + this.authConnection = authConnection; } } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index 91f6c09..171eb38 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -17,20 +17,20 @@ public class Web3AuthSample : MonoBehaviour { List verifierList = new List { - new LoginVerifier("Google", Provider.GOOGLE), - new LoginVerifier("Facebook", Provider.FACEBOOK), + new LoginVerifier("Google", AUTH_CONNECTION.GOOGLE), + new LoginVerifier("Facebook", AUTH_CONNECTION.FACEBOOK), // new LoginVerifier("CUSTOM_VERIFIER", Provider.CUSTOM_VERIFIER), - new LoginVerifier("Twitch", Provider.TWITCH), - new LoginVerifier("Discord", Provider.DISCORD), - new LoginVerifier("Reddit", Provider.REDDIT), - new LoginVerifier("Apple", Provider.APPLE), - new LoginVerifier("Github", Provider.GITHUB), - new LoginVerifier("LinkedIn", Provider.LINKEDIN), - new LoginVerifier("Twitter", Provider.TWITTER), - new LoginVerifier("Line", Provider.LINE), - new LoginVerifier("Email Passwordless", Provider.EMAIL_PASSWORDLESS), - new LoginVerifier("SMS Passwordless", Provider.SMS_PASSWORDLESS), - new LoginVerifier("Farcaster", Provider.FARCASTER), + new LoginVerifier("Twitch", AUTH_CONNECTION.TWITCH), + new LoginVerifier("Discord", AUTH_CONNECTION.DISCORD), + new LoginVerifier("Reddit", AUTH_CONNECTION.REDDIT), + new LoginVerifier("Apple", AUTH_CONNECTION.APPLE), + new LoginVerifier("Github", AUTH_CONNECTION.GITHUB), + new LoginVerifier("LinkedIn", AUTH_CONNECTION.LINKEDIN), + new LoginVerifier("Twitter", AUTH_CONNECTION.TWITTER), + new LoginVerifier("Line", AUTH_CONNECTION.LINE), + new LoginVerifier("Email Passwordless", AUTH_CONNECTION.EMAIL_PASSWORDLESS), + new LoginVerifier("SMS Passwordless", AUTH_CONNECTION.SMS_PASSWORDLESS), + new LoginVerifier("Farcaster", AUTH_CONNECTION.FARCASTER), }; Web3Auth web3Auth; @@ -64,12 +64,13 @@ public class Web3AuthSample : MonoBehaviour void Start() { - var loginConfigItem = new LoginConfigItem() + var authConnectionItem = new AuthConnectionConfig() { - verifier = "your_verifierid_from_web3auth_dashboard", - typeOfLogin = TypeOfLogin.GOOGLE, + authConnectionId = "your_verifierid_from_web3auth_dashboard", // corresponds to `verifier` + authConnection = AuthConnection.GOOGLE, clientId = "your_clientId_from_web3auth_dashboard" }; + var authConnectionConfig = new List { authConnectionItem }; web3Auth = GetComponent(); web3Auth.setOptions(new Web3AuthOptions() @@ -95,7 +96,7 @@ void Start() } */ clientId = "BFuUqebV5I8Pz5F7a5A2ihW7YVmbv_OHXnHYDv6OltAD5NGr6e-ViNvde3U4BHdn6HvwfkgobhVu4VwC-OSJkik", - buildEnv = BuildEnv.PRODUCTION, + buildEnv = BuildEnv.TESTING, redirectUrl = new Uri("torusapp://com.torus.Web3AuthUnity"), network = Web3Auth.Network.SAPPHIRE_DEVNET, sessionTime = 86400 @@ -168,7 +169,7 @@ private void onManageMFA(bool response) { private void onVerifierDropDownChange(int selectedIndex) { - if (verifierList[selectedIndex].loginProvider == Provider.EMAIL_PASSWORDLESS) + if (verifierList[selectedIndex].authConnection == AUTH_CONNECTION.EMAIL_PASSWORDLESS) emailAddressField.gameObject.SetActive(true); else emailAddressField.gameObject.SetActive(false); @@ -176,21 +177,21 @@ private void onVerifierDropDownChange(int selectedIndex) private void login() { - var selectedProvider = verifierList[verifierDropdown.value].loginProvider; + var selectedProvider = verifierList[verifierDropdown.value].authConnection; var options = new LoginParams() { - loginProvider = selectedProvider + authConnection = selectedProvider }; - if (selectedProvider == Provider.EMAIL_PASSWORDLESS) + if (selectedProvider == AUTH_CONNECTION.EMAIL_PASSWORDLESS) { options.extraLoginOptions = new ExtraLoginOptions() { login_hint = emailAddressField.text }; } - if (selectedProvider == Provider.SMS_PASSWORDLESS) + if (selectedProvider == AUTH_CONNECTION.SMS_PASSWORDLESS) { options.extraLoginOptions = new ExtraLoginOptions() { @@ -208,15 +209,15 @@ private void logout() private void enableMFA() { - var selectedProvider = verifierList[verifierDropdown.value].loginProvider; + var selectedProvider = verifierList[verifierDropdown.value].authConnection; var options = new LoginParams() { - loginProvider = selectedProvider, + authConnection = selectedProvider, mfaLevel = MFALevel.MANDATORY }; - if (selectedProvider == Provider.EMAIL_PASSWORDLESS) + if (selectedProvider == AUTH_CONNECTION.EMAIL_PASSWORDLESS) { options.extraLoginOptions = new ExtraLoginOptions() { @@ -228,15 +229,15 @@ private void enableMFA() private void manageMFA() { - var selectedProvider = verifierList[verifierDropdown.value].loginProvider; + var selectedProvider = verifierList[verifierDropdown.value].authConnection; var options = new LoginParams() { - loginProvider = selectedProvider, + authConnection = selectedProvider, mfaLevel = MFALevel.MANDATORY }; - if (selectedProvider == Provider.EMAIL_PASSWORDLESS) + if (selectedProvider == AUTH_CONNECTION.EMAIL_PASSWORDLESS) { options.extraLoginOptions = new ExtraLoginOptions() { @@ -247,7 +248,7 @@ private void manageMFA() } private void launchWalletServices() { - var selectedProvider = verifierList[verifierDropdown.value].loginProvider; + var selectedProvider = verifierList[verifierDropdown.value].authConnection; var chainConfig = new ChainConfig() { @@ -260,7 +261,7 @@ private void launchWalletServices() { } private void request() { - var selectedProvider = verifierList[verifierDropdown.value].loginProvider; + var selectedProvider = verifierList[verifierDropdown.value].authConnection; var chainConfig = new ChainConfig() { diff --git a/Assets/Plugins/Web3AuthSDK/Types/Provider.cs b/Assets/Plugins/Web3AuthSDK/Types/AUTH_CONNECTION.cs similarity index 97% rename from Assets/Plugins/Web3AuthSDK/Types/Provider.cs rename to Assets/Plugins/Web3AuthSDK/Types/AUTH_CONNECTION.cs index 3b926c8..5ec2bfa 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Provider.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/AUTH_CONNECTION.cs @@ -3,7 +3,7 @@ using System.Runtime.Serialization; [JsonConverter(typeof(StringEnumConverter))] -public enum Provider +public enum AUTH_CONNECTION { [EnumMember(Value = "google")] GOOGLE, diff --git a/Assets/Plugins/Web3AuthSDK/Types/TypeOfLogin.cs b/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs similarity index 97% rename from Assets/Plugins/Web3AuthSDK/Types/TypeOfLogin.cs rename to Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs index 4960f4b..7f9a8d4 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/TypeOfLogin.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs @@ -3,7 +3,7 @@ using System.Runtime.Serialization; [JsonConverter(typeof(StringEnumConverter))] -public enum TypeOfLogin +public enum AuthConnection { [EnumMember(Value = "google")] GOOGLE, diff --git a/Assets/Plugins/Web3AuthSDK/Types/LoginConfigItem.cs b/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs similarity index 77% rename from Assets/Plugins/Web3AuthSDK/Types/LoginConfigItem.cs rename to Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs index 0f3ec18..f14aae4 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/LoginConfigItem.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs @@ -1,6 +1,6 @@ -public class LoginConfigItem { - public string verifier { get; set; } - public TypeOfLogin typeOfLogin { get; set; } +public class AuthConnectionConfig { + public string authConnectionId { get; set; } + public AuthConnection authConnection { get; set; } public string name { get; set; } public string description { get; set; } public string clientId { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Types/LoginConfigItem.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/LoginConfigItem.cs.meta deleted file mode 100644 index 2f5e627..0000000 --- a/Assets/Plugins/Web3AuthSDK/Types/LoginConfigItem.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f2084deef0ee33142b69d4593c983a90 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs b/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs index ff3f7f4..b0372d3 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs @@ -2,7 +2,7 @@ public class LoginParams { - public Provider loginProvider { get; set; } + public AUTH_CONNECTION authConnection { get; set; } public string dappShare { get; set; } public ExtraLoginOptions extraLoginOptions { get; set; } public Uri redirectUrl { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Types/Provider.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/Provider.cs.meta deleted file mode 100644 index 82d8ae8..0000000 --- a/Assets/Plugins/Web3AuthSDK/Types/Provider.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d726f63285867184a9016460e6f380f4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/Web3AuthSDK/Types/TypeOfLogin.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/TypeOfLogin.cs.meta deleted file mode 100644 index 5659d28..0000000 --- a/Assets/Plugins/Web3AuthSDK/Types/TypeOfLogin.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1465d9a3f378eb64692b5d08c2dee5a9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs b/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs index 9de1c61..e11cb49 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs @@ -3,9 +3,9 @@ public string email { get; set; } public string name { get; set; } public string profileImage { get; set; } - public string aggregateVerifier { get; set; } - public string verifier { get; set; } - public string verifierId { get; set; } + public string groupedAuthConnectionId { get; set; } + public string authConnectionId { get; set; } + public string userId { get; set; } public string typeOfLogin { get; set; } public string dappShare { get; set; } public string idToken { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index 92543f1..54aadc0 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -32,7 +32,7 @@ public string walletSdkUrl { set { } } public WhiteLabelData? whiteLabel { get; set; } - public Dictionary? loginConfig { get; set; } + public List? authConnectionConfig { get; set; } public bool? useCoreKitKey { get; set; } = false; public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.EIP155; public MfaSettings? mfaSettings { get; set; } = null; diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index 8b29eb4..1f046da 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -125,8 +125,8 @@ public async void setOptions(Web3AuthOptions web3AuthOptions) if (this.web3AuthOptions.whiteLabel != null) this.initParams["whiteLabel"] = JsonConvert.SerializeObject(this.web3AuthOptions.whiteLabel, settings); - if (this.web3AuthOptions.loginConfig != null) - this.initParams["loginConfig"] = JsonConvert.SerializeObject(this.web3AuthOptions.loginConfig, settings); + if (this.web3AuthOptions.authConnectionConfig != null) + this.initParams["authConnectionConfig"] = JsonConvert.SerializeObject(this.web3AuthOptions.authConnectionConfig, settings); if (this.web3AuthOptions.clientId != null) this.initParams["clientId"] = this.web3AuthOptions.clientId; @@ -524,10 +524,10 @@ private string decodeBase64Params(string base64Params) public void login(LoginParams loginParams) { - if (web3AuthOptions.loginConfig != null) + if (web3AuthOptions.authConnectionConfig != null) { - var loginConfigItem = web3AuthOptions.loginConfig?.Values.First(); - var share = KeyStoreManagerUtils.getPreferencesData(loginConfigItem?.verifier); + var authConnectionItem = web3AuthOptions.authConnectionConfig?.FirstOrDefault(); + var share = KeyStoreManagerUtils.getPreferencesData(authConnectionItem?.authConnectionId); if (!string.IsNullOrEmpty(share)) { @@ -564,10 +564,10 @@ public void enableMFA(LoginParams loginParams) string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); if (!string.IsNullOrEmpty(sessionId)) { - if (web3AuthOptions.loginConfig != null) + if (web3AuthOptions.authConnectionConfig != null) { - var loginConfigItem = web3AuthOptions.loginConfig?.Values.First(); - var share = KeyStoreManagerUtils.getPreferencesData(loginConfigItem?.verifier); + var authConnectionItem = web3AuthOptions.authConnectionConfig?.FirstOrDefault(); + var share = KeyStoreManagerUtils.getPreferencesData(authConnectionItem?.authConnectionId); if (!string.IsNullOrEmpty(share)) { loginParams.dappShare = share; @@ -590,10 +590,10 @@ public void manageMFA(LoginParams loginParams) string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); if (!string.IsNullOrEmpty(sessionId)) { - if (web3AuthOptions.loginConfig != null) + if (web3AuthOptions.authConnectionConfig != null) { - var loginConfigItem = web3AuthOptions.loginConfig?.Values.First(); - var share = KeyStoreManagerUtils.getPreferencesData(loginConfigItem?.verifier); + var authConnectionItem = web3AuthOptions.authConnectionConfig?.FirstOrDefault(); + var share = KeyStoreManagerUtils.getPreferencesData(authConnectionItem?.authConnectionId); if (!string.IsNullOrEmpty(share)) { loginParams.dappShare = share; @@ -730,7 +730,7 @@ private void authorizeSession(string newSessionId, string origin) if (!string.IsNullOrEmpty(web3AuthResponse.userInfo?.dappShare)) { KeyStoreManagerUtils.savePreferenceData( - web3AuthResponse.userInfo?.verifier, web3AuthResponse.userInfo?.dappShare + web3AuthResponse.userInfo?.authConnectionId, web3AuthResponse.userInfo?.dappShare ); } @@ -792,8 +792,8 @@ private void sessionTimeOutAPI() try { KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.SESSION_ID); - if (web3AuthOptions.loginConfig != null) - KeyStoreManagerUtils.deletePreferencesData(web3AuthOptions.loginConfig?.Values.First()?.verifier); + if (web3AuthOptions.authConnectionConfig != null) + KeyStoreManagerUtils.deletePreferencesData(web3AuthOptions.authConnectionConfig?.FirstOrDefault()?.authConnectionId); this.Enqueue(() => this.onLogout?.Invoke()); } From d01e48636c1822dfb47639daccca042cfa9a328a Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Thu, 17 Apr 2025 13:54:32 +0530 Subject: [PATCH 02/25] feat: wallet-service and request fucntion changes added. --- .../Plugins/Web3AuthSDK/Types/ChainConfig.cs | 2 +- .../Web3AuthSDK/Types/Web3AuthOptions.cs | 2 +- Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 22 ++++++++++++++----- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs index 27df1de..dc38a9d 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; #nullable enable public class ChainConfig { - public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.EIP155; + public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.eip155; public int decimals { get; set; } = 18; public string blockExplorerUrl { get; set; } = null; public string chainId { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index 54aadc0..7e08364 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -34,7 +34,7 @@ public string walletSdkUrl { public WhiteLabelData? whiteLabel { get; set; } public List? authConnectionConfig { get; set; } public bool? useCoreKitKey { get; set; } = false; - public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.EIP155; + public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.eip155; public MfaSettings? mfaSettings { get; set; } = null; public int sessionTime { get; set; } = 86400; public ChainConfig? chainConfig { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index 1f046da..894e019 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -20,7 +20,7 @@ public enum Network public enum ChainNamespace { - EIP155, SOLANA + eip155, solana } public enum BuildEnv @@ -353,7 +353,7 @@ private async void processRequest(string path, LoginParams loginParams = null) } } - public async void launchWalletServices(ChainConfig chainConfig, string path = "wallet") + public async void launchWalletServices(List chainConfig, string chainId, string path = "wallet") { string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); if (!string.IsNullOrEmpty(sessionId)) @@ -370,7 +370,13 @@ public async void launchWalletServices(ChainConfig chainConfig, string path = "w this.initParams["redirectUrl"] = Utils.GetCurrentURL(); #endif - this.initParams["chainConfig"] = chainConfig; + string chainsJson = JsonConvert.SerializeObject(chainConfig, Formatting.None, new JsonSerializerSettings + { + Converters = new List { new StringEnumConverter() }, + NullValueHandling = NullValueHandling.Ignore + }); + this.initParams["chains"] = chainsJson; + this.initParams["chainId"] = chainId; Dictionary paramMap = new Dictionary(); paramMap["options"] = this.initParams; @@ -607,7 +613,7 @@ public void manageMFA(LoginParams loginParams) } } - public async void request(ChainConfig chainConfig, string method, JArray requestParams, string path = "wallet/request") { + public async void request(List chainConfig, string chainId, string method, JArray requestParams, string path = "wallet/request") { string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); if (!string.IsNullOrEmpty(sessionId)) { @@ -623,7 +629,13 @@ public async void request(ChainConfig chainConfig, string method, JArray request this.initParams["redirectUrl"] = Utils.GetCurrentURL(); #endif - this.initParams["chainConfig"] = chainConfig; + string chainsJson = JsonConvert.SerializeObject(chainConfig, Formatting.None, new JsonSerializerSettings + { + Converters = new List { new StringEnumConverter() }, + NullValueHandling = NullValueHandling.Ignore + }); + this.initParams["chains"] = chainsJson; + this.initParams["chainId"] = chainId; Dictionary paramMap = new Dictionary(); paramMap["options"] = this.initParams; From 34b97429984d8da6b44385dd7cf4b3ba0e3bf2b1 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Thu, 17 Apr 2025 13:54:57 +0530 Subject: [PATCH 03/25] feat: example updated. Signed-off-by: Gaurav Goel --- .../Web3AuthSDK/Samples/Web3AuthSample.cs | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index 171eb38..0f8f00e 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -95,6 +95,15 @@ void Start() {"CUSTOM_VERIFIER", loginConfigItem} } */ + authConnectionConfig = new List() + { + new AuthConnectionConfig() + { + authConnectionId = "web3auth-auth0-email-passwordless-sapphire-devnet", + authConnection = AuthConnection.JWT, + clientId = "d84f6xvbdV75VTGmHiMWfZLeSPk8M07C" + } + }, clientId = "BFuUqebV5I8Pz5F7a5A2ihW7YVmbv_OHXnHYDv6OltAD5NGr6e-ViNvde3U4BHdn6HvwfkgobhVu4VwC-OSJkik", buildEnv = BuildEnv.TESTING, redirectUrl = new Uri("torusapp://com.torus.Web3AuthUnity"), @@ -255,9 +264,14 @@ private void launchWalletServices() { chainId = "0x1", rpcTarget = "https://mainnet.infura.io/v3/daeee53504be4cd3a997d4f2718d33e0", ticker = "ETH", - chainNamespace = Web3Auth.ChainNamespace.EIP155 + chainNamespace = Web3Auth.ChainNamespace.eip155 }; - web3Auth.launchWalletServices(chainConfig); + var chainConfigList = new List { chainConfig }; + foreach (var config in chainConfigList) + { + Debug.Log($"Chain ID: {config.chainId}, RPC Target: {config.rpcTarget}, Ticker: {config.ticker}, Namespace: {config.chainNamespace}"); + } + web3Auth.launchWalletServices(chainConfigList, "0x1"); } private void request() { @@ -267,8 +281,9 @@ private void request() { { chainId = "0x89", rpcTarget = "https://1rpc.io/matic", - chainNamespace = Web3Auth.ChainNamespace.EIP155 + chainNamespace = Web3Auth.ChainNamespace.eip155 }; + var chainConfigList = new List { chainConfig }; JArray paramsArray = new JArray { @@ -277,7 +292,7 @@ private void request() { "Android" }; - web3Auth.request(chainConfig, "personal_sign", paramsArray); + web3Auth.request(chainConfigList, "0x89", "personal_sign", paramsArray); } public string getPublicAddressFromPrivateKey(string privateKeyHex) From 29c158d4c0d2e45ff591ba4e8cb1806e7832bdd3 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Mon, 21 Apr 2025 11:00:53 +0530 Subject: [PATCH 04/25] feat: bump auth-services version Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index 7e08364..e517276 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -54,6 +54,6 @@ public string dashboardUrl set { } } - private const string authDashboardVersion = "v9"; + private const string authDashboardVersion = "v10"; private const string walletAccountConstant = "wallet/account"; } \ No newline at end of file From bfbf5cbffc87a45d77ddd74374ae5300a685b40d Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Mon, 21 Apr 2025 11:02:15 +0530 Subject: [PATCH 05/25] feat: bump auth-services version Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index e517276..9ed2a96 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -11,11 +11,11 @@ public class Web3AuthOptions { public string sdkUrl { get { if (buildEnv == Web3Auth.BuildEnv.STAGING) - return "https://staging-auth.web3auth.io/v9"; + return "https://staging-auth.web3auth.io/v10"; else if (buildEnv == Web3Auth.BuildEnv.TESTING) return "https://develop-auth.web3auth.io"; else - return "https://auth.web3auth.io/v9"; + return "https://auth.web3auth.io/v10"; } set { } } @@ -54,6 +54,6 @@ public string dashboardUrl set { } } - private const string authDashboardVersion = "v10"; + private const string authDashboardVersion = "v9"; private const string walletAccountConstant = "wallet/account"; } \ No newline at end of file From 301fe7198d6de7551e14df87af07838040af21b4 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Wed, 23 Apr 2025 10:18:32 +0530 Subject: [PATCH 06/25] feat: auth-service and wallet-service changes added. Signed-off-by: Gaurav Goel --- .../Web3AuthSDK/Samples/LoginVerifier.cs | 4 +- .../Web3AuthSDK/Samples/Web3AuthSample.cs | 55 +++++++++---------- .../Web3AuthSDK/Types/AUTH_CONNECTION.cs | 46 ---------------- .../Web3AuthSDK/Types/AuthConnection.cs | 8 ++- .../Types/{ChainConfig.cs => ChainsConfig.cs} | 7 ++- .../Plugins/Web3AuthSDK/Types/LoginParams.cs | 2 +- .../Web3AuthSDK/Types/Web3AuthOptions.cs | 14 ++--- Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 25 +++++---- 8 files changed, 64 insertions(+), 97 deletions(-) delete mode 100644 Assets/Plugins/Web3AuthSDK/Types/AUTH_CONNECTION.cs rename Assets/Plugins/Web3AuthSDK/Types/{ChainConfig.cs => ChainsConfig.cs} (79%) diff --git a/Assets/Plugins/Web3AuthSDK/Samples/LoginVerifier.cs b/Assets/Plugins/Web3AuthSDK/Samples/LoginVerifier.cs index 2c485d8..29f9d4f 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/LoginVerifier.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/LoginVerifier.cs @@ -1,8 +1,8 @@ public class LoginVerifier { public string name { get; set; } - public AUTH_CONNECTION authConnection { get; set; } + public AuthConnection authConnection { get; set; } - public LoginVerifier(string name, AUTH_CONNECTION authConnection) + public LoginVerifier(string name, AuthConnection authConnection) { this.name = name; this.authConnection = authConnection; diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index 0f8f00e..f4bee7a 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -17,20 +17,20 @@ public class Web3AuthSample : MonoBehaviour { List verifierList = new List { - new LoginVerifier("Google", AUTH_CONNECTION.GOOGLE), - new LoginVerifier("Facebook", AUTH_CONNECTION.FACEBOOK), - // new LoginVerifier("CUSTOM_VERIFIER", Provider.CUSTOM_VERIFIER), - new LoginVerifier("Twitch", AUTH_CONNECTION.TWITCH), - new LoginVerifier("Discord", AUTH_CONNECTION.DISCORD), - new LoginVerifier("Reddit", AUTH_CONNECTION.REDDIT), - new LoginVerifier("Apple", AUTH_CONNECTION.APPLE), - new LoginVerifier("Github", AUTH_CONNECTION.GITHUB), - new LoginVerifier("LinkedIn", AUTH_CONNECTION.LINKEDIN), - new LoginVerifier("Twitter", AUTH_CONNECTION.TWITTER), - new LoginVerifier("Line", AUTH_CONNECTION.LINE), - new LoginVerifier("Email Passwordless", AUTH_CONNECTION.EMAIL_PASSWORDLESS), - new LoginVerifier("SMS Passwordless", AUTH_CONNECTION.SMS_PASSWORDLESS), - new LoginVerifier("Farcaster", AUTH_CONNECTION.FARCASTER), + new LoginVerifier("Google", AuthConnection.GOOGLE), + new LoginVerifier("Facebook", AuthConnection.FACEBOOK), + // new LoginVerifier("CUSTOM_VERIFIER", AuthConnection.CUSTOM_VERIFIER), + new LoginVerifier("Twitch", AuthConnection.TWITCH), + new LoginVerifier("Discord", AuthConnection.DISCORD), + new LoginVerifier("Reddit", AuthConnection.REDDIT), + new LoginVerifier("Apple", AuthConnection.APPLE), + new LoginVerifier("Github", AuthConnection.GITHUB), + new LoginVerifier("LinkedIn", AuthConnection.LINKEDIN), + new LoginVerifier("Twitter", AuthConnection.TWITTER), + new LoginVerifier("Line", AuthConnection.LINE), + new LoginVerifier("Email Passwordless", AuthConnection.EMAIL_PASSWORDLESS), + new LoginVerifier("SMS Passwordless", AuthConnection.SMS_PASSWORDLESS), + new LoginVerifier("Farcaster", AuthConnection.FARCASTER), }; Web3Auth web3Auth; @@ -105,7 +105,7 @@ void Start() } }, clientId = "BFuUqebV5I8Pz5F7a5A2ihW7YVmbv_OHXnHYDv6OltAD5NGr6e-ViNvde3U4BHdn6HvwfkgobhVu4VwC-OSJkik", - buildEnv = BuildEnv.TESTING, + authBuildEnv = BuildEnv.TESTING, redirectUrl = new Uri("torusapp://com.torus.Web3AuthUnity"), network = Web3Auth.Network.SAPPHIRE_DEVNET, sessionTime = 86400 @@ -126,7 +126,7 @@ void Start() loginButton.onClick.AddListener(login); logoutButton.onClick.AddListener(logout); mfaSetupButton.onClick.AddListener(enableMFA); - launchWalletServicesButton.onClick.AddListener(launchWalletServices); + launchWalletServicesButton.onClick.AddListener(showWalletUI); signMessageButton.onClick.AddListener(request); signResponseButton.onClick.AddListener(manageMFA); @@ -178,7 +178,7 @@ private void onManageMFA(bool response) { private void onVerifierDropDownChange(int selectedIndex) { - if (verifierList[selectedIndex].authConnection == AUTH_CONNECTION.EMAIL_PASSWORDLESS) + if (verifierList[selectedIndex].authConnection == AuthConnection.EMAIL_PASSWORDLESS) emailAddressField.gameObject.SetActive(true); else emailAddressField.gameObject.SetActive(false); @@ -193,14 +193,14 @@ private void login() authConnection = selectedProvider }; - if (selectedProvider == AUTH_CONNECTION.EMAIL_PASSWORDLESS) + if (selectedProvider == AuthConnection.EMAIL_PASSWORDLESS) { options.extraLoginOptions = new ExtraLoginOptions() { login_hint = emailAddressField.text }; } - if (selectedProvider == AUTH_CONNECTION.SMS_PASSWORDLESS) + if (selectedProvider == AuthConnection.SMS_PASSWORDLESS) { options.extraLoginOptions = new ExtraLoginOptions() { @@ -226,7 +226,7 @@ private void enableMFA() mfaLevel = MFALevel.MANDATORY }; - if (selectedProvider == AUTH_CONNECTION.EMAIL_PASSWORDLESS) + if (selectedProvider == AuthConnection.EMAIL_PASSWORDLESS) { options.extraLoginOptions = new ExtraLoginOptions() { @@ -246,7 +246,7 @@ private void manageMFA() mfaLevel = MFALevel.MANDATORY }; - if (selectedProvider == AUTH_CONNECTION.EMAIL_PASSWORDLESS) + if (selectedProvider == AuthConnection.EMAIL_PASSWORDLESS) { options.extraLoginOptions = new ExtraLoginOptions() { @@ -256,34 +256,33 @@ private void manageMFA() web3Auth.manageMFA(options); } - private void launchWalletServices() { + private void showWalletUI() { var selectedProvider = verifierList[verifierDropdown.value].authConnection; - var chainConfig = new ChainConfig() + var chainConfig = new ChainsConfig() { chainId = "0x1", rpcTarget = "https://mainnet.infura.io/v3/daeee53504be4cd3a997d4f2718d33e0", ticker = "ETH", chainNamespace = Web3Auth.ChainNamespace.eip155 }; - var chainConfigList = new List { chainConfig }; + var chainConfigList = new List { chainConfig }; foreach (var config in chainConfigList) { Debug.Log($"Chain ID: {config.chainId}, RPC Target: {config.rpcTarget}, Ticker: {config.ticker}, Namespace: {config.chainNamespace}"); } - web3Auth.launchWalletServices(chainConfigList, "0x1"); + web3Auth.showWalletUI(chainConfigList, "0x1"); } private void request() { var selectedProvider = verifierList[verifierDropdown.value].authConnection; - var chainConfig = new ChainConfig() + var chainConfig = new ChainsConfig() { chainId = "0x89", rpcTarget = "https://1rpc.io/matic", chainNamespace = Web3Auth.ChainNamespace.eip155 }; - var chainConfigList = new List { chainConfig }; JArray paramsArray = new JArray { @@ -292,7 +291,7 @@ private void request() { "Android" }; - web3Auth.request(chainConfigList, "0x89", "personal_sign", paramsArray); + web3Auth.request(chainConfig, "personal_sign", paramsArray); } public string getPublicAddressFromPrivateKey(string privateKeyHex) diff --git a/Assets/Plugins/Web3AuthSDK/Types/AUTH_CONNECTION.cs b/Assets/Plugins/Web3AuthSDK/Types/AUTH_CONNECTION.cs deleted file mode 100644 index 5ec2bfa..0000000 --- a/Assets/Plugins/Web3AuthSDK/Types/AUTH_CONNECTION.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System.Runtime.Serialization; - -[JsonConverter(typeof(StringEnumConverter))] -public enum AUTH_CONNECTION -{ - [EnumMember(Value = "google")] - GOOGLE, - [EnumMember(Value = "facebook")] - FACEBOOK, - [EnumMember(Value = "reddit")] - REDDIT, - [EnumMember(Value = "discord")] - DISCORD, - [EnumMember(Value = "twitch")] - TWITCH, - [EnumMember(Value = "apple")] - APPLE, - [EnumMember(Value = "line")] - LINE, - [EnumMember(Value = "github")] - GITHUB, - [EnumMember(Value = "kakao")] - KAKAO, - [EnumMember(Value = "linkedin")] - LINKEDIN, - [EnumMember(Value = "twitter")] - TWITTER, - [EnumMember(Value = "weibo")] - WEIBO, - [EnumMember(Value = "wechat")] - WECHAT, - [EnumMember(Value = "email_passwordless")] - EMAIL_PASSWORDLESS, - [EnumMember(Value = "email_password")] - EMAIL_PASSWORD, - [EnumMember(Value = "jwt")] - JWT, - [EnumMember(Value = "CUSTOM_VERIFIER")] - CUSTOM_VERIFIER, - [EnumMember(Value = "sms_passwordless")] - SMS_PASSWORDLESS, - [EnumMember(Value = "farcaster")] - FARCASTER -} \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs b/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs index 7f9a8d4..bb32394 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs @@ -36,5 +36,11 @@ public enum AuthConnection [EnumMember(Value = "email_password")] EMAIL_PASSWORD, [EnumMember(Value = "jwt")] - JWT + JWT, + [EnumMember(Value = "CUSTOM_VERIFIER")] + CUSTOM_VERIFIER, + [EnumMember(Value = "sms_passwordless")] + SMS_PASSWORDLESS, + [EnumMember(Value = "farcaster")] + FARCASTER } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/ChainsConfig.cs similarity index 79% rename from Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs rename to Assets/Plugins/Web3AuthSDK/Types/ChainsConfig.cs index dc38a9d..3edc01b 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/ChainsConfig.cs @@ -1,7 +1,12 @@ using System.Collections.Generic; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; #nullable enable -public class ChainConfig { +public class ChainsConfig { + + [JsonConverter(typeof(StringEnumConverter))] public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.eip155; + public int decimals { get; set; } = 18; public string blockExplorerUrl { get; set; } = null; public string chainId { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs b/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs index b0372d3..c6fa0bb 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs @@ -2,7 +2,7 @@ public class LoginParams { - public AUTH_CONNECTION authConnection { get; set; } + public AuthConnection authConnection { get; set; } public string dappShare { get; set; } public ExtraLoginOptions extraLoginOptions { get; set; } public Uri redirectUrl { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index 9ed2a96..a0e12ed 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -6,13 +6,13 @@ public class Web3AuthOptions { public string clientId { get; set; } public Web3Auth.Network network { get; set; } - public Web3Auth.BuildEnv buildEnv { get; set; } = Web3Auth.BuildEnv.PRODUCTION; + public Web3Auth.BuildEnv authBuildEnv { get; set; } = Web3Auth.BuildEnv.PRODUCTION; public Uri redirectUrl { get; set; } public string sdkUrl { get { - if (buildEnv == Web3Auth.BuildEnv.STAGING) + if (authBuildEnv == Web3Auth.BuildEnv.STAGING) return "https://staging-auth.web3auth.io/v10"; - else if (buildEnv == Web3Auth.BuildEnv.TESTING) + else if (authBuildEnv == Web3Auth.BuildEnv.TESTING) return "https://develop-auth.web3auth.io"; else return "https://auth.web3auth.io/v10"; @@ -22,9 +22,9 @@ public string sdkUrl { public string walletSdkUrl { get { - if (buildEnv == Web3Auth.BuildEnv.STAGING) + if (authBuildEnv == Web3Auth.BuildEnv.STAGING) return "https://staging-wallet.web3auth.io/v3"; - else if (buildEnv == Web3Auth.BuildEnv.TESTING) + else if (authBuildEnv == Web3Auth.BuildEnv.TESTING) return "https://develop-wallet.web3auth.io"; else return "https://wallet.web3auth.io/v3"; @@ -37,14 +37,14 @@ public string walletSdkUrl { public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.eip155; public MfaSettings? mfaSettings { get; set; } = null; public int sessionTime { get; set; } = 86400; - public ChainConfig? chainConfig { get; set; } + public ChainsConfig? chainConfig { get; set; } public Dictionary originData { get; set; } = null; public string dashboardUrl { get { - return buildEnv switch + return authBuildEnv switch { Web3Auth.BuildEnv.STAGING => $"https://staging-account.web3auth.io/{authDashboardVersion}/{walletAccountConstant}", Web3Auth.BuildEnv.TESTING => $"https://develop-account.web3auth.io/{walletAccountConstant}", diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index 894e019..119d56c 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -18,6 +18,7 @@ public enum Network MAINNET, TESTNET, CYAN, AQUA, SAPPHIRE_DEVNET, SAPPHIRE_MAINNET } + [JsonConverter(typeof(StringEnumConverter))] public enum ChainNamespace { eip155, solana @@ -131,8 +132,8 @@ public async void setOptions(Web3AuthOptions web3AuthOptions) if (this.web3AuthOptions.clientId != null) this.initParams["clientId"] = this.web3AuthOptions.clientId; - if (this.web3AuthOptions.buildEnv != null) - this.initParams["buildEnv"] = this.web3AuthOptions.buildEnv.ToString().ToLower(); + if (this.web3AuthOptions.authBuildEnv != null) + this.initParams["authBuildEnv"] = this.web3AuthOptions.authBuildEnv.ToString().ToLower(); this.initParams["network"] = this.web3AuthOptions.network.ToString().ToLower(); @@ -353,7 +354,7 @@ private async void processRequest(string path, LoginParams loginParams = null) } } - public async void launchWalletServices(List chainConfig, string chainId, string path = "wallet") + public async void showWalletUI(List chainConfig, string chainId, string path = "wallet") { string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); if (!string.IsNullOrEmpty(sessionId)) @@ -613,7 +614,7 @@ public void manageMFA(LoginParams loginParams) } } - public async void request(List chainConfig, string chainId, string method, JArray requestParams, string path = "wallet/request") { + public async void request(ChainsConfig chainConfig, string method, JArray requestParams, string path = "wallet/request") { string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); if (!string.IsNullOrEmpty(sessionId)) { @@ -629,16 +630,18 @@ public async void request(List chainConfig, string chainId, string this.initParams["redirectUrl"] = Utils.GetCurrentURL(); #endif - string chainsJson = JsonConvert.SerializeObject(chainConfig, Formatting.None, new JsonSerializerSettings - { - Converters = new List { new StringEnumConverter() }, - NullValueHandling = NullValueHandling.Ignore - }); - this.initParams["chains"] = chainsJson; - this.initParams["chainId"] = chainId; + var chainConfigList = new List { chainConfig }; + string chainConfigListJson = JsonConvert.SerializeObject(chainConfigList, Formatting.Indented); + this.initParams["chains"] = chainConfigListJson; + this.initParams["chainId"] = chainConfig.chainId; Dictionary paramMap = new Dictionary(); paramMap["options"] = this.initParams; + foreach (KeyValuePair entry in paramMap) + { + Debug.Log($"Key: {entry.Key}, Value: {JsonUtility.ToJson(entry.Value)}"); + } + var newSessionId = KeyStoreManagerUtils.generateRandomSessionKey(); string loginId = await createSession(JsonConvert.SerializeObject(paramMap, Formatting.None, new JsonSerializerSettings From 279f8c8f9a6794b240e3277abc73fbc93aeceeaf Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Fri, 25 Apr 2025 13:13:40 +0530 Subject: [PATCH 07/25] feat: Rename var names ChainConfig, network to web3AuthNetwork Signed-off-by: Gaurav Goel --- .../Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs | 8 ++++---- .../Types/{ChainsConfig.cs => ChainConfig.cs} | 2 +- Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs | 2 +- .../Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs | 6 ++++-- .../Plugins/Web3AuthSDK/Types/Web3AuthResponse.cs | 7 +++++-- Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 14 +++++++------- 6 files changed, 22 insertions(+), 17 deletions(-) rename Assets/Plugins/Web3AuthSDK/Types/{ChainsConfig.cs => ChainConfig.cs} (95%) diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index f4bee7a..913538b 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -107,7 +107,7 @@ void Start() clientId = "BFuUqebV5I8Pz5F7a5A2ihW7YVmbv_OHXnHYDv6OltAD5NGr6e-ViNvde3U4BHdn6HvwfkgobhVu4VwC-OSJkik", authBuildEnv = BuildEnv.TESTING, redirectUrl = new Uri("torusapp://com.torus.Web3AuthUnity"), - network = Web3Auth.Network.SAPPHIRE_DEVNET, + web3AuthNetwork = Web3Auth.Network.SAPPHIRE_DEVNET, sessionTime = 86400 }); web3Auth.onLogin += onLogin; @@ -259,14 +259,14 @@ private void manageMFA() private void showWalletUI() { var selectedProvider = verifierList[verifierDropdown.value].authConnection; - var chainConfig = new ChainsConfig() + var chainConfig = new ChainConfig() { chainId = "0x1", rpcTarget = "https://mainnet.infura.io/v3/daeee53504be4cd3a997d4f2718d33e0", ticker = "ETH", chainNamespace = Web3Auth.ChainNamespace.eip155 }; - var chainConfigList = new List { chainConfig }; + var chainConfigList = new List { chainConfig }; foreach (var config in chainConfigList) { Debug.Log($"Chain ID: {config.chainId}, RPC Target: {config.rpcTarget}, Ticker: {config.ticker}, Namespace: {config.chainNamespace}"); @@ -277,7 +277,7 @@ private void showWalletUI() { private void request() { var selectedProvider = verifierList[verifierDropdown.value].authConnection; - var chainConfig = new ChainsConfig() + var chainConfig = new ChainConfig() { chainId = "0x89", rpcTarget = "https://1rpc.io/matic", diff --git a/Assets/Plugins/Web3AuthSDK/Types/ChainsConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs similarity index 95% rename from Assets/Plugins/Web3AuthSDK/Types/ChainsConfig.cs rename to Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs index 3edc01b..ba6c54e 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/ChainsConfig.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs @@ -2,7 +2,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; #nullable enable -public class ChainsConfig { +public class ChainConfig { [JsonConverter(typeof(StringEnumConverter))] public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.eip155; diff --git a/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs b/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs index e11cb49..807ee0c 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/UserInfo.cs @@ -6,7 +6,7 @@ public string groupedAuthConnectionId { get; set; } public string authConnectionId { get; set; } public string userId { get; set; } - public string typeOfLogin { get; set; } + public string authConnection { get; set; } public string dappShare { get; set; } public string idToken { get; set; } public string oAuthIdToken { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index a0e12ed..30aca18 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; +using Newtonsoft.Json; #nullable enable public class Web3AuthOptions { public string clientId { get; set; } - public Web3Auth.Network network { get; set; } + [JsonProperty("network")] + public Web3Auth.Network web3AuthNetwork { get; set; } public Web3Auth.BuildEnv authBuildEnv { get; set; } = Web3Auth.BuildEnv.PRODUCTION; public Uri redirectUrl { get; set; } @@ -37,7 +39,7 @@ public string walletSdkUrl { public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.eip155; public MfaSettings? mfaSettings { get; set; } = null; public int sessionTime { get; set; } = 86400; - public ChainsConfig? chainConfig { get; set; } + public ChainConfig? chainConfig { get; set; } public Dictionary originData { get; set; } = null; public string dashboardUrl diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthResponse.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthResponse.cs index 607e47b..531cb29 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthResponse.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthResponse.cs @@ -1,6 +1,9 @@ -public class Web3AuthResponse +using Newtonsoft.Json; +public class Web3AuthResponse { - public string privKey { get; set; } + [JsonProperty("privKey")] + public string privateKey { get; set; } + public string ed25519PrivKey { get; set; } public UserInfo userInfo { get; set; } public string error { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index 119d56c..a30a4bc 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -135,7 +135,7 @@ public async void setOptions(Web3AuthOptions web3AuthOptions) if (this.web3AuthOptions.authBuildEnv != null) this.initParams["authBuildEnv"] = this.web3AuthOptions.authBuildEnv.ToString().ToLower(); - this.initParams["network"] = this.web3AuthOptions.network.ToString().ToLower(); + this.initParams["network"] = this.web3AuthOptions.web3AuthNetwork.ToString().ToLower(); if (this.web3AuthOptions.useCoreKitKey.HasValue) this.initParams["useCoreKitKey"] = this.web3AuthOptions.useCoreKitKey.Value; @@ -354,7 +354,7 @@ private async void processRequest(string path, LoginParams loginParams = null) } } - public async void showWalletUI(List chainConfig, string chainId, string path = "wallet") + public async void showWalletUI(List chainConfig, string chainId, string path = "wallet") { string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); if (!string.IsNullOrEmpty(sessionId)) @@ -614,7 +614,7 @@ public void manageMFA(LoginParams loginParams) } } - public async void request(ChainsConfig chainConfig, string method, JArray requestParams, string path = "wallet/request") { + public async void request(ChainConfig chainConfig, string method, JArray requestParams, string path = "wallet/request") { string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); if (!string.IsNullOrEmpty(sessionId)) { @@ -630,7 +630,7 @@ public async void request(ChainsConfig chainConfig, string method, JArray reques this.initParams["redirectUrl"] = Utils.GetCurrentURL(); #endif - var chainConfigList = new List { chainConfig }; + var chainConfigList = new List { chainConfig }; string chainConfigListJson = JsonConvert.SerializeObject(chainConfigList, Formatting.Indented); this.initParams["chains"] = chainConfigListJson; this.initParams["chainId"] = chainConfig.chainId; @@ -749,7 +749,7 @@ private void authorizeSession(string newSessionId, string origin) ); } - if (string.IsNullOrEmpty(this.web3AuthResponse.privKey) || string.IsNullOrEmpty(this.web3AuthResponse.privKey.Trim('0'))) + if (string.IsNullOrEmpty(this.web3AuthResponse.privateKey) || string.IsNullOrEmpty(this.web3AuthResponse.privateKey.Trim('0'))) this.Enqueue(() => this.onLogout?.Invoke()); else this.Enqueue(() => this.onLogin?.Invoke(this.web3AuthResponse)); @@ -885,7 +885,7 @@ private async Task createSession(string data, long sessionTime, string a private async Task fetchProjectConfig() { TaskCompletionSource fetchProjectConfigResponse = new TaskCompletionSource(); - StartCoroutine(Web3AuthApi.getInstance().fetchProjectConfig(this.web3AuthOptions.clientId, this.web3AuthOptions.network.ToString().ToLower(), (response => + StartCoroutine(Web3AuthApi.getInstance().fetchProjectConfig(this.web3AuthOptions.clientId, this.web3AuthOptions.web3AuthNetwork.ToString().ToLower(), (response => { if (response != null) { @@ -930,7 +930,7 @@ public string getPrivKey() if (web3AuthResponse == null) return ""; - return web3AuthOptions.useCoreKitKey.Value ? web3AuthResponse.coreKitKey : web3AuthResponse.privKey; + return web3AuthOptions.useCoreKitKey.Value ? web3AuthResponse.coreKitKey : web3AuthResponse.privateKey; } public string getEd25519PrivKey() From ae7bccca3112b93d62a474908f5a3ffe77f7ecef Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Mon, 28 Apr 2025 11:37:36 +0530 Subject: [PATCH 08/25] feat: default value added for authConnectionConfig Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index 30aca18..7593519 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -34,7 +34,7 @@ public string walletSdkUrl { set { } } public WhiteLabelData? whiteLabel { get; set; } - public List? authConnectionConfig { get; set; } + public List? authConnectionConfig { get; set; } = new List(); public bool? useCoreKitKey { get; set; } = false; public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.eip155; public MfaSettings? mfaSettings { get; set; } = null; From 2943eb74eb1ae60173cbd9717bb33bb6dbd6ca48 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Tue, 29 Apr 2025 15:09:23 +0530 Subject: [PATCH 09/25] feat: changed authConnection jwt to custom Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs | 2 +- Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index 913538b..1ab6c45 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -100,7 +100,7 @@ void Start() new AuthConnectionConfig() { authConnectionId = "web3auth-auth0-email-passwordless-sapphire-devnet", - authConnection = AuthConnection.JWT, + authConnection = AuthConnection.CUSTOM, clientId = "d84f6xvbdV75VTGmHiMWfZLeSPk8M07C" } }, diff --git a/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs b/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs index bb32394..472aaf3 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs @@ -35,8 +35,8 @@ public enum AuthConnection EMAIL_PASSWORDLESS, [EnumMember(Value = "email_password")] EMAIL_PASSWORD, - [EnumMember(Value = "jwt")] - JWT, + [EnumMember(Value = "custom")] + CUSTOM, [EnumMember(Value = "CUSTOM_VERIFIER")] CUSTOM_VERIFIER, [EnumMember(Value = "sms_passwordless")] From 472f1fbd16e98394ba4b434c91ace1093e3c3681 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Wed, 14 May 2025 10:07:53 +0530 Subject: [PATCH 10/25] feat: renaming variables Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs | 2 +- Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs | 1 + Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index 1ab6c45..636b52a 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -287,7 +287,7 @@ private void request() { JArray paramsArray = new JArray { "Hello, World!", - getPublicAddressFromPrivateKey(web3Auth.getPrivKey()), + getPublicAddressFromPrivateKey(web3Auth.getPrivateKey()), "Android" }; diff --git a/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs index f14aae4..632eeb0 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs @@ -4,6 +4,7 @@ public string name { get; set; } public string description { get; set; } public string clientId { get; set; } + public string groupedAuthConnectionId { get; set; } public string verifierSubIdentifier { get; set; } public string logoHover { get; set; } public string logoLight { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index a30a4bc..adda70c 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -925,7 +925,7 @@ private async Task fetchProjectConfig() return await fetchProjectConfigResponse.Task; } - public string getPrivKey() + public string getPrivateKey() { if (web3AuthResponse == null) return ""; @@ -933,7 +933,7 @@ public string getPrivKey() return web3AuthOptions.useCoreKitKey.Value ? web3AuthResponse.coreKitKey : web3AuthResponse.privateKey; } - public string getEd25519PrivKey() + public string getEd25519PrivateKey() { if (web3AuthResponse == null) return ""; From d97e8d4bb41695e851b8b283e7ed4727f2e7f784 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Wed, 14 May 2025 11:47:05 +0530 Subject: [PATCH 11/25] feat: Update Input config params Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs | 1 - Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs | 2 ++ Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs index 632eeb0..e421217 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs @@ -5,7 +5,6 @@ public string description { get; set; } public string clientId { get; set; } public string groupedAuthConnectionId { get; set; } - public string verifierSubIdentifier { get; set; } public string logoHover { get; set; } public string logoLight { get; set; } public string logoDark { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs b/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs index c6fa0bb..2eaed6e 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs @@ -3,6 +3,8 @@ public class LoginParams { public AuthConnection authConnection { get; set; } + public string authConnectionId { get; set; } + public string groupedAuthConnectionId { get; set; } public string dappShare { get; set; } public ExtraLoginOptions extraLoginOptions { get; set; } public Uri redirectUrl { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index 7593519..54f6e49 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -25,11 +25,11 @@ public string sdkUrl { public string walletSdkUrl { get { if (authBuildEnv == Web3Auth.BuildEnv.STAGING) - return "https://staging-wallet.web3auth.io/v3"; + return "https://staging-wallet.web3auth.io/v4"; else if (authBuildEnv == Web3Auth.BuildEnv.TESTING) return "https://develop-wallet.web3auth.io"; else - return "https://wallet.web3auth.io/v3"; + return "https://wallet.web3auth.io/v4"; } set { } } From 0049a3bfc222c7e9c8a5959a48c243b242ba6bf4 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Wed, 14 May 2025 19:39:30 +0530 Subject: [PATCH 12/25] feat: update wallet-services to v5 version Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index 54f6e49..5723866 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -25,11 +25,11 @@ public string sdkUrl { public string walletSdkUrl { get { if (authBuildEnv == Web3Auth.BuildEnv.STAGING) - return "https://staging-wallet.web3auth.io/v4"; + return "https://staging-wallet.web3auth.io/v5"; else if (authBuildEnv == Web3Auth.BuildEnv.TESTING) return "https://develop-wallet.web3auth.io"; else - return "https://wallet.web3auth.io/v4"; + return "https://wallet.web3auth.io/v5"; } set { } } From cc37dfd24e653f744dfb79b0522b64146e18706a Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Thu, 15 May 2025 08:04:34 +0530 Subject: [PATCH 13/25] feat: update ExtraLoginOptions.cs Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs index 65dfe5d..6f03560 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs @@ -5,13 +5,14 @@ public class ExtraLoginOptions { public string domain { get; set; } public string client_id { get; set; } public string leeway { get; set; } - public string verifierIdField { get; set; } - public bool isVerifierIdCaseSensitive { get; set; } + public string userIdField { get; set; } + public bool isUserIdCaseSensitive { get; set; } public Display display { get; set; } public Prompt prompt { get; set; } public string max_age { get; set; } public string ui_locales { get; set; } public string id_token { get; set; } + public string access_token { get; set; } public string id_token_hint { get; set; } public string login_hint { get; set; } public string acr_values { get; set; } From 2b48b3c59872a2407ed812ed8cac99a6557a1123 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Thu, 15 May 2025 11:11:27 +0530 Subject: [PATCH 14/25] feat: update Web3AuthOptions Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index 5723866..efdf0b9 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -41,6 +41,7 @@ public string walletSdkUrl { public int sessionTime { get; set; } = 86400; public ChainConfig? chainConfig { get; set; } public Dictionary originData { get; set; } = null; + public bool? includeUserDataInToken { get; set; } = false; public string dashboardUrl { From d7dedde4842e88b0e130ac1d25c9d4aa0905bb8b Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Thu, 15 May 2025 11:14:49 +0530 Subject: [PATCH 15/25] feat: update Web3AuthOptions Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index efdf0b9..6300bea 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -41,7 +41,7 @@ public string walletSdkUrl { public int sessionTime { get; set; } = 86400; public ChainConfig? chainConfig { get; set; } public Dictionary originData { get; set; } = null; - public bool? includeUserDataInToken { get; set; } = false; + public bool? includeUserDataInToken { get; set; } = true; public string dashboardUrl { From 2512b386f446e1ce6cb5b1f7f38a96903bcd5e68 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Tue, 20 May 2025 09:01:09 +0530 Subject: [PATCH 16/25] feat: update Web3AuthResponse Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Types/Web3AuthResponse.cs | 3 ++- Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthResponse.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthResponse.cs index 531cb29..8200a96 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthResponse.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthResponse.cs @@ -4,7 +4,8 @@ public class Web3AuthResponse [JsonProperty("privKey")] public string privateKey { get; set; } - public string ed25519PrivKey { get; set; } + [JsonProperty("ed25519PrivKey")] + public string ed25519PrivateKey { get; set; } public UserInfo userInfo { get; set; } public string error { get; set; } public string sessionId { get; set; } diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index adda70c..d23b16a 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -938,7 +938,7 @@ public string getEd25519PrivateKey() if (web3AuthResponse == null) return ""; - return web3AuthOptions.useCoreKitKey.Value ? web3AuthResponse.coreKitEd25519PrivKey : web3AuthResponse.ed25519PrivKey; + return web3AuthOptions.useCoreKitKey.Value ? web3AuthResponse.coreKitEd25519PrivKey : web3AuthResponse.ed25519PrivateKey; } public UserInfo getUserInfo() From 21f379ab381fb6fd21ad0548f0b671804639f127 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Mon, 16 Jun 2025 17:03:35 +0530 Subject: [PATCH 17/25] feat: Update fetchprojectConfig API response, Web3AuthOptions.cs and other input params Signed-off-by: Gaurav Goel --- .../Api/Models/ProjectConfigResponse.cs | 12 +- .../Web3AuthSDK/Samples/Web3AuthSample.cs | 31 ++- .../Web3AuthSDK/Types/AuthConnectionConfig.cs | 1 + .../Web3AuthSDK/Types/BundlerConfig.cs | 7 + .../Web3AuthSDK/Types/BundlerConfig.cs.meta | 3 + .../Types/{ChainConfig.cs => Chains.cs} | 6 +- .../Web3AuthSDK/Types/ExtraLoginOptions.cs | 6 + .../Plugins/Web3AuthSDK/Types/LoginParams.cs | 12 +- .../Web3AuthSDK/Types/PaymasterConfig.cs | 7 + .../Web3AuthSDK/Types/PaymasterConfig.cs.meta | 3 + .../Web3AuthSDK/Types/SmartAccountsConfig.cs | 31 +++ .../Types/SmartAccountsConfig.cs.meta | 3 + .../Web3AuthSDK/Types/WalletServicesConfig.cs | 26 ++ .../Types/WalletServicesConfig.cs.meta | 3 + .../Web3AuthSDK/Types/WalletUiConfig.cs | 51 ++++ .../Web3AuthSDK/Types/WalletUiConfig.cs.meta | 3 + .../Web3AuthSDK/Types/Web3AuthOptions.cs | 77 +++--- Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 226 ++++++++++-------- 18 files changed, 351 insertions(+), 157 deletions(-) create mode 100644 Assets/Plugins/Web3AuthSDK/Types/BundlerConfig.cs create mode 100644 Assets/Plugins/Web3AuthSDK/Types/BundlerConfig.cs.meta rename Assets/Plugins/Web3AuthSDK/Types/{ChainConfig.cs => Chains.cs} (90%) create mode 100644 Assets/Plugins/Web3AuthSDK/Types/PaymasterConfig.cs create mode 100644 Assets/Plugins/Web3AuthSDK/Types/PaymasterConfig.cs.meta create mode 100644 Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs create mode 100644 Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs.meta create mode 100644 Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs create mode 100644 Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs.meta create mode 100644 Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs create mode 100644 Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs.meta diff --git a/Assets/Plugins/Web3AuthSDK/Api/Models/ProjectConfigResponse.cs b/Assets/Plugins/Web3AuthSDK/Api/Models/ProjectConfigResponse.cs index 5627de5..703a70e 100644 --- a/Assets/Plugins/Web3AuthSDK/Api/Models/ProjectConfigResponse.cs +++ b/Assets/Plugins/Web3AuthSDK/Api/Models/ProjectConfigResponse.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Plugins.Web3AuthSDK.Types; public class WhitelistResponse { @@ -8,9 +9,16 @@ public class WhitelistResponse public class ProjectConfigResponse { - public WhiteLabelData whitelabel { get; set; } + public bool? userDataInIdToken { get; set; } = true; + public int? sessionTime { get; set; } = 30 * 86400; + public bool? enableKeyExport { get; set; } = false; + public WhitelistResponse whitelist { get; set; } + public List chains { get; set; } + public SmartAccountsConfig smartAccounts { get; set; } + public WalletUiConfig walletUiConfig { get; set; } + public List embeddedWalletAuth { get; set; } public bool sms_otp_enabled { get; set; } public bool wallet_connect_enabled { get; set; } public string wallet_connect_project_id { get; set; } - public WhitelistResponse whitelist { get; set; } + public WhiteLabelData whitelabel { get; set; } } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index 636b52a..015ab50 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -1,18 +1,16 @@ using System; -using System.Linq; using System.Collections.Generic; -using UnityEngine; -using UnityEngine.UI; +using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using static Web3Auth; using Org.BouncyCastle.Asn1.Sec; -using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; -using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; -using Org.BouncyCastle.Crypto.Digests; +using UnityEngine; +using UnityEngine.UI; +using static Web3Auth; public class Web3AuthSample : MonoBehaviour { @@ -104,10 +102,11 @@ void Start() clientId = "d84f6xvbdV75VTGmHiMWfZLeSPk8M07C" } }, - clientId = "BFuUqebV5I8Pz5F7a5A2ihW7YVmbv_OHXnHYDv6OltAD5NGr6e-ViNvde3U4BHdn6HvwfkgobhVu4VwC-OSJkik", + clientId = "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ", authBuildEnv = BuildEnv.TESTING, redirectUrl = new Uri("torusapp://com.torus.Web3AuthUnity"), - web3AuthNetwork = Web3Auth.Network.SAPPHIRE_DEVNET, + web3AuthNetwork = Web3Auth.Network.SAPPHIRE_MAINNET, + defaultChainId = "0x1", sessionTime = 86400 }); web3Auth.onLogin += onLogin; @@ -259,29 +258,29 @@ private void manageMFA() private void showWalletUI() { var selectedProvider = verifierList[verifierDropdown.value].authConnection; - var chainConfig = new ChainConfig() + var chainConfig = new Chains() { chainId = "0x1", rpcTarget = "https://mainnet.infura.io/v3/daeee53504be4cd3a997d4f2718d33e0", ticker = "ETH", - chainNamespace = Web3Auth.ChainNamespace.eip155 + chainNamespace = ChainNamespace.eip155 }; - var chainConfigList = new List { chainConfig }; + var chainConfigList = new List { chainConfig }; foreach (var config in chainConfigList) { Debug.Log($"Chain ID: {config.chainId}, RPC Target: {config.rpcTarget}, Ticker: {config.ticker}, Namespace: {config.chainNamespace}"); } - web3Auth.showWalletUI(chainConfigList, "0x1"); + web3Auth.showWalletUI("0x1"); } private void request() { var selectedProvider = verifierList[verifierDropdown.value].authConnection; - var chainConfig = new ChainConfig() + var chainConfig = new Chains() { chainId = "0x89", rpcTarget = "https://1rpc.io/matic", - chainNamespace = Web3Auth.ChainNamespace.eip155 + chainNamespace = ChainNamespace.eip155 }; JArray paramsArray = new JArray @@ -291,7 +290,7 @@ private void request() { "Android" }; - web3Auth.request(chainConfig, "personal_sign", paramsArray); + web3Auth.request("personal_sign", paramsArray); } public string getPublicAddressFromPrivateKey(string privateKeyHex) diff --git a/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs index e421217..c3393b5 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs @@ -12,4 +12,5 @@ public bool showOnModal { get; set; } = true; public bool showOnDesktop { get; set; } = true; public bool showOnMobile { get; set; } = true; + public ExtraLoginOptions extraLoginOptions { get; set; } } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/BundlerConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/BundlerConfig.cs new file mode 100644 index 0000000..f93bf51 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/BundlerConfig.cs @@ -0,0 +1,7 @@ +namespace Plugins.Web3AuthSDK.Types +{ + public class BundlerConfig + { + public string url { get; set; } + } +} \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/BundlerConfig.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/BundlerConfig.cs.meta new file mode 100644 index 0000000..db199d7 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/BundlerConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f7937f8f3db14dfea557ef526d300942 +timeCreated: 1750061363 \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/Chains.cs similarity index 90% rename from Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs rename to Assets/Plugins/Web3AuthSDK/Types/Chains.cs index ba6c54e..85e2787 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/ChainConfig.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Chains.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; +#nullable enable using Newtonsoft.Json; using Newtonsoft.Json.Converters; -#nullable enable -public class ChainConfig { + +public class Chains { [JsonConverter(typeof(StringEnumConverter))] public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.eip155; diff --git a/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs index 6f03560..b0d1c9a 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs @@ -13,6 +13,7 @@ public class ExtraLoginOptions { public string ui_locales { get; set; } public string id_token { get; set; } public string access_token { get; set; } + private EmailFlowType flow_type { get; set; } = EmailFlowType.link; public string id_token_hint { get; set; } public string login_hint { get; set; } public string acr_values { get; set; } @@ -23,4 +24,9 @@ public class ExtraLoginOptions { public string response_type { get; set; } public string nonce { get; set; } public string redirect_uri { get; set; } +} + +public enum EmailFlowType +{ + link, code } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs b/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs index 2eaed6e..f1c96a1 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/LoginParams.cs @@ -1,16 +1,14 @@ -using System; - -public class LoginParams +public class LoginParams { public AuthConnection authConnection { get; set; } public string authConnectionId { get; set; } public string groupedAuthConnectionId { get; set; } - public string dappShare { get; set; } - public ExtraLoginOptions extraLoginOptions { get; set; } - public Uri redirectUrl { get; set; } public string appState { get; set; } public MFALevel mfaLevel { get; set; } - + public ExtraLoginOptions extraLoginOptions { get; set; } + public string dappShare { get; set; } public Curve curve { get; set; } = Curve.SECP256K1; public string dappUrl { get; set; } + public string? loginHint { get; set; } + } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/PaymasterConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/PaymasterConfig.cs new file mode 100644 index 0000000..84e9b81 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/PaymasterConfig.cs @@ -0,0 +1,7 @@ +namespace Plugins.Web3AuthSDK.Types +{ + public class PaymasterConfig + { + public string url { get; set; } + } +} \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/PaymasterConfig.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/PaymasterConfig.cs.meta new file mode 100644 index 0000000..6402c23 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/PaymasterConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 526533185c3841fc8a5d6f901c5f73ec +timeCreated: 1750061393 \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs new file mode 100644 index 0000000..fb675f0 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; + +namespace Plugins.Web3AuthSDK.Types +{ + public class SmartAccountsConfig + { + public SmartAccountType SmartAccountType { get; set; } + + public SmartAccountWalletScope walletScope { get; set; } + + public List chains { get; set; } + } + + public class ChainConfig + { + public string chainId { get; set; } + public BundlerConfig bundlerConfig { get; set; } + public PaymasterConfig paymasterConfig { get; set; } + } +} + +public enum SmartAccountWalletScope +{ + embedded, + all +} + +public enum SmartAccountType +{ + biconomy, kernel, safe, trust, light, simple, nexus +} \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs.meta new file mode 100644 index 0000000..48728ce --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e5f50c644c2544d8894b5b60b03f365d +timeCreated: 1750060901 \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs new file mode 100644 index 0000000..3d6f44f --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs @@ -0,0 +1,26 @@ +using Newtonsoft.Json; + +namespace Plugins.Web3AuthSDK.Types +{ + public class WalletServicesConfig + { + public ConfirmationStrategy? confirmationStrategy { get; set; } = ConfirmationStrategy.DEFAULT; + + public WhiteLabelData? whiteLabel { get; set; } + } +} + +public enum ConfirmationStrategy +{ + [JsonProperty("popup")] + POPUP, + + [JsonProperty("modal")] + MODAL, + + [JsonProperty("auto-approve")] + AUTO_APPROVE, + + [JsonProperty("default")] + DEFAULT +} \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs.meta new file mode 100644 index 0000000..479be9e --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1194c63acb8a40528f551ca2f9d7b5f3 +timeCreated: 1750059054 \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs new file mode 100644 index 0000000..cbb3059 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs @@ -0,0 +1,51 @@ +using Newtonsoft.Json; + +namespace Plugins.Web3AuthSDK.Types +{ + public class WalletUiConfig + { + public bool? enablePortfolioWidget { get; set; } + + public bool? enableConfirmationModal { get; set; } + + public bool? enableWalletConnect { get; set; } + + public bool? enableTokenDisplay { get; set; } + + public bool? enableNftDisplay { get; set; } + + public bool? enableShowAllTokensButton { get; set; } + + public bool? enableBuyButton { get; set; } + + public bool? enableSendButton { get; set; } + + public bool? enableSwapButton { get; set; } + + public bool? enableReceiveButton { get; set; } + + public ButtonPositionType? portfolioWidgetPosition { get; set; } + + public DefaultPortfolioType? defaultPortfolio { get; set; } + } +} + +public enum ButtonPositionType +{ + [JsonProperty("bottom-left")] + BOTTOM_LEFT, + + [JsonProperty("top-left")] + TOP_LEFT, + + [JsonProperty("bottom-right")] + BOTTOM_RIGHT, + + [JsonProperty("top-right")] + TOP_RIGHT +} + +public enum DefaultPortfolioType +{ + token , nft +} \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs.meta new file mode 100644 index 0000000..0bd31e3 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 845b4eaa6fcf4ba09c241466a1c8efc9 +timeCreated: 1750062059 \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index 6300bea..283825c 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -1,48 +1,32 @@ -using System; +#nullable enable + +using System; using System.Collections.Generic; using Newtonsoft.Json; -#nullable enable +using Plugins.Web3AuthSDK.Types; public class Web3AuthOptions { public string clientId { get; set; } - [JsonProperty("network")] - public Web3Auth.Network web3AuthNetwork { get; set; } - - public Web3Auth.BuildEnv authBuildEnv { get; set; } = Web3Auth.BuildEnv.PRODUCTION; public Uri redirectUrl { get; set; } + public Dictionary originData { get; set; } = null; + + [JsonProperty("buildEnv")] + public Web3Auth.BuildEnv authBuildEnv { get; set; } = Web3Auth.BuildEnv.PRODUCTION; public string sdkUrl { - get { - if (authBuildEnv == Web3Auth.BuildEnv.STAGING) - return "https://staging-auth.web3auth.io/v10"; - else if (authBuildEnv == Web3Auth.BuildEnv.TESTING) - return "https://develop-auth.web3auth.io"; - else - return "https://auth.web3auth.io/v10"; + get + { + return authBuildEnv switch + { + Web3Auth.BuildEnv.STAGING => "https://staging-auth.web3auth.io/v10", + Web3Auth.BuildEnv.TESTING => "https://develop-auth.web3auth.io", + _ => "https://auth.web3auth.io/v10" + }; } set { } } - - public string walletSdkUrl { - get { - if (authBuildEnv == Web3Auth.BuildEnv.STAGING) - return "https://staging-wallet.web3auth.io/v5"; - else if (authBuildEnv == Web3Auth.BuildEnv.TESTING) - return "https://develop-wallet.web3auth.io"; - else - return "https://wallet.web3auth.io/v5"; - } - set { } - } - public WhiteLabelData? whiteLabel { get; set; } + public List? authConnectionConfig { get; set; } = new List(); - public bool? useCoreKitKey { get; set; } = false; - public Web3Auth.ChainNamespace? chainNamespace { get; set; } = Web3Auth.ChainNamespace.eip155; - public MfaSettings? mfaSettings { get; set; } = null; - public int sessionTime { get; set; } = 86400; - public ChainConfig? chainConfig { get; set; } - public Dictionary originData { get; set; } = null; - public bool? includeUserDataInToken { get; set; } = true; - + public WhiteLabelData? whiteLabel { get; set; } public string dashboardUrl { get @@ -56,6 +40,31 @@ public string dashboardUrl } set { } } + public string? accountAbstractionConfig { get; set; } + public string walletSdkUrl { + get + { + return authBuildEnv switch + { + Web3Auth.BuildEnv.STAGING => "https://staging-wallet.web3auth.io/v5", + Web3Auth.BuildEnv.TESTING => "https://develop-wallet.web3auth.io", + _ => "https://wallet.web3auth.io/v5" + }; + } + set { } + } + public bool? includeUserDataInToken { get; set; } = true; + public Chains? chains { get; set; } + public String? defaultChainId { get; set; } = "0x1"; + public bool? enableLogging { get; set; } = false; + public int sessionTime { get; set; } = 86400; + + [JsonProperty("network")] + public Web3Auth.Network web3AuthNetwork { get; set; } + + public bool? useSFAKey { get; set; } = false; + public WalletServicesConfig? walletServicesConfig { get; set; } + public MfaSettings? mfaSettings { get; set; } = null; private const string authDashboardVersion = "v9"; private const string walletAccountConstant = "wallet/account"; diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index d23b16a..fab6b82 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -1,15 +1,17 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using System; +using System; +using System.Collections; using System.Collections.Generic; -using System.Text; +using System.IO; using System.Linq; -using UnityEngine; using System.Net; -using System.Collections; -using Org.BouncyCastle.Math; -using Newtonsoft.Json.Linq; +using System.Text; using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using Org.BouncyCastle.Math; +using UnityEngine; +using Web3AuthSDK.Editor; public class Web3Auth : MonoBehaviour { @@ -21,7 +23,7 @@ public enum Network [JsonConverter(typeof(StringEnumConverter))] public enum ChainNamespace { - eip155, solana + eip155, solana, other } public enum BuildEnv @@ -43,6 +45,7 @@ public enum Language private Dictionary initParams; private Web3AuthResponse web3AuthResponse; + private ProjectConfigResponse projectConfigResponse; private bool isRequestResponse = false; public event Action onLogin; @@ -65,7 +68,7 @@ public static void setSignResponse(SignResponse _response) private string redirectUri; [SerializeField] - private Web3Auth.Network network; + private Network network; private string redirectUrl; private static readonly Queue _executionQueue = new Queue(); @@ -85,7 +88,7 @@ public void Awake() onDeepLinkActivated(Application.absoluteURL); #if UNITY_EDITOR - Web3AuthSDK.Editor.Web3AuthDebug.onURLRecieved += (Uri url) => + Web3AuthDebug.onURLRecieved += (Uri url) => { this.setResultUrl(url); }; @@ -137,11 +140,8 @@ public async void setOptions(Web3AuthOptions web3AuthOptions) this.initParams["network"] = this.web3AuthOptions.web3AuthNetwork.ToString().ToLower(); - if (this.web3AuthOptions.useCoreKitKey.HasValue) - this.initParams["useCoreKitKey"] = this.web3AuthOptions.useCoreKitKey.Value; - - if (this.web3AuthOptions.chainNamespace != null) - this.initParams["chainNamespace"] = this.web3AuthOptions.chainNamespace; + if (this.web3AuthOptions.useSFAKey.HasValue) + this.initParams["useCoreKitKey"] = this.web3AuthOptions.useSFAKey.Value; if (this.web3AuthOptions.mfaSettings != null) this.initParams["mfaSettings"] = JsonConvert.SerializeObject(this.web3AuthOptions.mfaSettings, settings); @@ -151,7 +151,6 @@ public async void setOptions(Web3AuthOptions web3AuthOptions) if (this.web3AuthOptions.dashboardUrl != null) this.initParams["dashboardUrl"] = this.web3AuthOptions.dashboardUrl; - } } @@ -239,10 +238,10 @@ private void IncomingHttpRequest(IAsyncResult result) "; - byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); + byte[] buffer = Encoding.UTF8.GetBytes(responseString); httpResponse.ContentLength64 = buffer.Length; - System.IO.Stream output = httpResponse.OutputStream; + Stream output = httpResponse.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); @@ -252,10 +251,10 @@ private void IncomingHttpRequest(IAsyncResult result) { var responseString = @"ok"; - byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); + byte[] buffer = Encoding.UTF8.GetBytes(responseString); httpResponse.ContentLength64 = buffer.Length; - System.IO.Stream output = httpResponse.OutputStream; + Stream output = httpResponse.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); string code = httpRequest.QueryString.Get("code"); @@ -284,12 +283,12 @@ private async void processRequest(string path, LoginParams loginParams = null) this.initParams["redirectUrl"] = Utils.GetCurrentURL(); #endif - loginParams.redirectUrl = loginParams.redirectUrl ?? new Uri(this.initParams["redirectUrl"].ToString()); + //loginParams.redirectUrl = loginParams.redirectUrl ?? new Uri(this.initParams["redirectUrl"].ToString()); //Debug.Log("loginParams.redirectUrl: =>" + loginParams.redirectUrl); var sessionId = KeyStoreManagerUtils.generateRandomSessionKey(); if(path == "manage_mfa") { loginParams.dappUrl = this.initParams["redirectUrl"].ToString(); - loginParams.redirectUrl = new Uri(this.initParams["dashboardUrl"].ToString()); + //loginParams.redirectUrl = new Uri(this.initParams["dashboardUrl"].ToString()); this.initParams["redirectUrl"] = new Uri(this.initParams["dashboardUrl"].ToString()); var loginIdObject = new Dictionary { @@ -315,7 +314,7 @@ private async void processRequest(string path, LoginParams loginParams = null) paramMap["sessionId"] = savedSessionId; } - //Debug.Log("paramMap: =>" + JsonConvert.SerializeObject(paramMap)); + Debug.Log("paramMap: =>" + JsonConvert.SerializeObject(paramMap)); string loginId = await createSession(JsonConvert.SerializeObject(paramMap, Formatting.None, new JsonSerializerSettings { @@ -354,77 +353,91 @@ private async void processRequest(string path, LoginParams loginParams = null) } } - public async void showWalletUI(List chainConfig, string chainId, string path = "wallet") + public async void showWalletUI(string path = "wallet") { string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); if (!string.IsNullOrEmpty(sessionId)) { - redirectUrl = this.initParams["redirectUrl"].ToString(); - if (redirectUrl.EndsWith("/")) - { - redirectUrl = redirectUrl.TrimEnd('/'); - } - #if UNITY_STANDALONE || UNITY_EDITOR - this.initParams["redirectUrl"] = StartLocalWebserver(); - redirectUrl = this.initParams["redirectUrl"].ToString().Replace("/complete/", ""); - #elif UNITY_WEBGL + redirectUrl = this.initParams["redirectUrl"].ToString(); + if (redirectUrl.EndsWith("/")) + { + redirectUrl = redirectUrl.TrimEnd('/'); + } +#if UNITY_STANDALONE || UNITY_EDITOR + this.initParams["redirectUrl"] = StartLocalWebserver(); + redirectUrl = this.initParams["redirectUrl"].ToString().Replace("/complete/", ""); +#elif UNITY_WEBGL this.initParams["redirectUrl"] = Utils.GetCurrentURL(); - #endif +#endif - string chainsJson = JsonConvert.SerializeObject(chainConfig, Formatting.None, new JsonSerializerSettings - { - Converters = new List { new StringEnumConverter() }, - NullValueHandling = NullValueHandling.Ignore - }); - this.initParams["chains"] = chainsJson; - this.initParams["chainId"] = chainId; - Dictionary paramMap = new Dictionary(); - paramMap["options"] = this.initParams; - - //Debug.Log("paramMap: =>" + JsonConvert.SerializeObject(paramMap)); - var newSessionId = KeyStoreManagerUtils.generateRandomSessionKey(); - string loginId = await createSession(JsonConvert.SerializeObject(paramMap, Formatting.None, - new JsonSerializerSettings + if (projectConfigResponse?.chains != null) { - NullValueHandling = NullValueHandling.Ignore - }), 600, "*", newSessionId); - - if (!string.IsNullOrEmpty(loginId)) - { - var loginIdObject = new Dictionary - { - { "loginId", loginId }, - { "sessionId", sessionId }, - { "platform", "unity" } - }; - string hash = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(loginIdObject, Formatting.None, + string chainsJson = JsonConvert.SerializeObject(projectConfigResponse.chains, Formatting.None, new JsonSerializerSettings + { + Converters = new List { new StringEnumConverter() }, + NullValueHandling = NullValueHandling.Ignore + }); + this.initParams["chains"] = chainsJson; + } + + this.initParams["chainId"] = web3AuthOptions.defaultChainId ?? "0x1"; + + if (projectConfigResponse?.embeddedWalletAuth != null) + { + this.initParams["embeddedWalletAuth"] = projectConfigResponse.embeddedWalletAuth; + } + + if (projectConfigResponse?.smartAccounts != null) + { + this.initParams["smartAccounts"] = projectConfigResponse.smartAccounts; + } + Dictionary paramMap = new Dictionary(); + paramMap["options"] = this.initParams; + + //Debug.Log("paramMap: =>" + JsonConvert.SerializeObject(paramMap)); + var newSessionId = KeyStoreManagerUtils.generateRandomSessionKey(); + string loginId = await createSession(JsonConvert.SerializeObject(paramMap, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore - }))); + }), 600, "*", newSessionId); - UriBuilder uriBuilder = new UriBuilder(this.web3AuthOptions.walletSdkUrl); - if(this.web3AuthOptions.sdkUrl.Contains("develop")) + if (!string.IsNullOrEmpty(loginId)) { - uriBuilder.Path = "/" + path; + var loginIdObject = new Dictionary + { + { "loginId", loginId }, + { "sessionId", sessionId }, + { "platform", "unity" } + }; + string hash = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(loginIdObject, Formatting.None, + new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }))); + + UriBuilder uriBuilder = new UriBuilder(this.web3AuthOptions.walletSdkUrl); + if(this.web3AuthOptions.sdkUrl.Contains("develop")) + { + uriBuilder.Path = "/" + path; + } + else + { + uriBuilder.Path += "/" + path; + } + uriBuilder.Fragment = "b64Params=" + hash; + //Debug.Log("finalUriBuilderToOpen: =>" + uriBuilder.ToString()); + isRequestResponse = false; + Utils.LaunchUrl(uriBuilder.ToString(), this.initParams["redirectUrl"].ToString(), gameObject.name); } else { - uriBuilder.Path += "/" + path; + throw new Exception("Some went wrong. Please try again later."); } - uriBuilder.Fragment = "b64Params=" + hash; - //Debug.Log("finalUriBuilderToOpen: =>" + uriBuilder.ToString()); - isRequestResponse = false; - Utils.LaunchUrl(uriBuilder.ToString(), this.initParams["redirectUrl"].ToString(), gameObject.name); - } - else + } else { - throw new Exception("Some went wrong. Please try again later."); + throw new Exception("SessionId not found. Please login first."); } - } else - { - throw new Exception("SessionId not found. Please login first."); - } } public void setResultUrl(Uri uri) @@ -525,7 +538,7 @@ private string decodeBase64Params(string base64Params) base64Params += d % 2 > 0 ? "=" : "=="; } byte[] bytes = Convert.FromBase64String(base64Params); - var decodedString = System.Text.Encoding.UTF8.GetString(bytes); + var decodedString = Encoding.UTF8.GetString(bytes); return decodedString; } @@ -614,7 +627,7 @@ public void manageMFA(LoginParams loginParams) } } - public async void request(ChainConfig chainConfig, string method, JArray requestParams, string path = "wallet/request") { + public async void request(string method, JArray requestParams, string path = "wallet/request") { string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); if (!string.IsNullOrEmpty(sessionId)) { @@ -622,18 +635,33 @@ public async void request(ChainConfig chainConfig, string method, JArray request if (redirectUrl.EndsWith("/")) { redirectUrl = redirectUrl.TrimEnd('/'); - } - #if UNITY_STANDALONE || UNITY_EDITOR + } +#if UNITY_STANDALONE || UNITY_EDITOR this.initParams["redirectUrl"] = StartLocalWebserver(); redirectUrl = this.initParams["redirectUrl"].ToString().Replace("/complete/", ""); - #elif UNITY_WEBGL +#elif UNITY_WEBGL this.initParams["redirectUrl"] = Utils.GetCurrentURL(); - #endif +#endif - var chainConfigList = new List { chainConfig }; - string chainConfigListJson = JsonConvert.SerializeObject(chainConfigList, Formatting.Indented); - this.initParams["chains"] = chainConfigListJson; - this.initParams["chainId"] = chainConfig.chainId; + if (projectConfigResponse?.chains != null) + { + string chainsJson = JsonConvert.SerializeObject(projectConfigResponse.chains, Formatting.None, new JsonSerializerSettings + { + Converters = new List { new StringEnumConverter() }, + NullValueHandling = NullValueHandling.Ignore + }); + this.initParams["chains"] = chainsJson; + } + this.initParams["chainId"] = web3AuthOptions.defaultChainId ?? "0x1"; + if (projectConfigResponse?.embeddedWalletAuth != null) + { + this.initParams["embeddedWalletAuth"] = projectConfigResponse.embeddedWalletAuth; + } + + if (projectConfigResponse?.smartAccounts != null) + { + this.initParams["smartAccounts"] = projectConfigResponse.smartAccounts; + } Dictionary paramMap = new Dictionary(); paramMap["options"] = this.initParams; @@ -716,7 +744,7 @@ private void authorizeSession(string newSessionId, string origin) { if (response != null) { - var shareMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject(response.message); + var shareMetadata = JsonConvert.DeserializeObject(response.message); var aes256cbc = new AES256CBC( sessionId, @@ -726,7 +754,7 @@ private void authorizeSession(string newSessionId, string origin) var encryptedShareBytes = AES256CBC.toByteArray(new BigInteger(shareMetadata.ciphertext, 16)); var share = aes256cbc.decrypt(encryptedShareBytes, shareMetadata.mac); - var tempJson = JsonConvert.DeserializeObject(System.Text.Encoding.UTF8.GetString(share)); + var tempJson = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(share)); this.web3AuthResponse = JsonConvert.DeserializeObject(tempJson.ToString()); if (this.web3AuthResponse != null) @@ -772,7 +800,7 @@ private void sessionTimeOutAPI() { if (response != null) { - var shareMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject(response.message); + var shareMetadata = JsonConvert.DeserializeObject(response.message); var aes256cbc = new AES256CBC( sessionId, @@ -780,7 +808,7 @@ private void sessionTimeOutAPI() shareMetadata.iv ); - var encryptedData = aes256cbc.encrypt(System.Text.Encoding.UTF8.GetBytes("")); + var encryptedData = aes256cbc.encrypt(Encoding.UTF8.GetBytes("")); var encryptedMetadata = new ShareMetadata() { iv = shareMetadata.iv, @@ -837,7 +865,7 @@ private async Task createSession(string data, long sessionTime, string a ephemKey, KeyStoreManagerUtils.convertByteToHexadecimal(ivKey) ); - var encryptedData = aes256cbc.encrypt(System.Text.Encoding.UTF8.GetBytes(data)); + var encryptedData = aes256cbc.encrypt(Encoding.UTF8.GetBytes(data)); var mac = aes256cbc.getMac(encryptedData); var encryptedMetadata = new ShareMetadata() { @@ -887,6 +915,7 @@ private async Task fetchProjectConfig() TaskCompletionSource fetchProjectConfigResponse = new TaskCompletionSource(); StartCoroutine(Web3AuthApi.getInstance().fetchProjectConfig(this.web3AuthOptions.clientId, this.web3AuthOptions.web3AuthNetwork.ToString().ToLower(), (response => { + projectConfigResponse = response; if (response != null) { this.web3AuthOptions.originData = this.web3AuthOptions.originData.mergeMaps(response.whitelist?.signed_urls); @@ -901,6 +930,13 @@ private async Task fetchProjectConfig() this.web3AuthOptions.whiteLabel = this.web3AuthOptions.whiteLabel?.merge(response.whitelabel); } } + + if (response?.whitelabel != null) + { + this.web3AuthOptions.whiteLabel = this.web3AuthOptions.whiteLabel == null ? response.whitelabel : this.web3AuthOptions.whiteLabel?.merge(response.whitelabel); + this.web3AuthOptions.walletServicesConfig.whiteLabel = this.web3AuthOptions.walletServicesConfig.whiteLabel == null ? response.whitelabel : this.web3AuthOptions.walletServicesConfig.whiteLabel?.merge(response.whitelabel); + } + //Debug.Log("this.web3AuthOptions: =>" + JsonConvert.SerializeObject(this.web3AuthOptions)); JsonSerializerSettings settings = new JsonSerializerSettings @@ -914,7 +950,7 @@ private async Task fetchProjectConfig() if(this.web3AuthOptions.originData != null) this.initParams["originData"] = JsonConvert.SerializeObject(this.web3AuthOptions.originData, settings); - fetchProjectConfigResponse.SetResult(true); + fetchProjectConfigResponse.SetResult(true); } else { @@ -930,7 +966,7 @@ public string getPrivateKey() if (web3AuthResponse == null) return ""; - return web3AuthOptions.useCoreKitKey.Value ? web3AuthResponse.coreKitKey : web3AuthResponse.privateKey; + return web3AuthOptions.useSFAKey.Value ? web3AuthResponse.coreKitKey : web3AuthResponse.privateKey; } public string getEd25519PrivateKey() @@ -938,7 +974,7 @@ public string getEd25519PrivateKey() if (web3AuthResponse == null) return ""; - return web3AuthOptions.useCoreKitKey.Value ? web3AuthResponse.coreKitEd25519PrivKey : web3AuthResponse.ed25519PrivateKey; + return web3AuthOptions.useSFAKey.Value ? web3AuthResponse.coreKitEd25519PrivKey : web3AuthResponse.ed25519PrivateKey; } public UserInfo getUserInfo() From ed79bc415b6255aa79457743e4cdc632915b1389 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Mon, 28 Jul 2025 14:36:37 +0400 Subject: [PATCH 18/25] feat: modify project config response Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Api/Models/ProjectConfigResponse.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Assets/Plugins/Web3AuthSDK/Api/Models/ProjectConfigResponse.cs b/Assets/Plugins/Web3AuthSDK/Api/Models/ProjectConfigResponse.cs index 703a70e..e2e8695 100644 --- a/Assets/Plugins/Web3AuthSDK/Api/Models/ProjectConfigResponse.cs +++ b/Assets/Plugins/Web3AuthSDK/Api/Models/ProjectConfigResponse.cs @@ -19,6 +19,6 @@ public class ProjectConfigResponse public List embeddedWalletAuth { get; set; } public bool sms_otp_enabled { get; set; } public bool wallet_connect_enabled { get; set; } - public string wallet_connect_project_id { get; set; } + public string walletConnectProjectId { get; set; } public WhiteLabelData whitelabel { get; set; } } \ No newline at end of file From 9af6d7b97d210a58978622c02b48d597c7c25d36 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Mon, 28 Jul 2025 14:37:25 +0400 Subject: [PATCH 19/25] Update project config url and Web3Auth.cs Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs | 5 +- Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 104 +++++++++++------- 2 files changed, 65 insertions(+), 44 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs b/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs index 3f9001a..3fb045f 100644 --- a/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs +++ b/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs @@ -99,11 +99,11 @@ public IEnumerator createSession(LogoutApiRequest logoutApiRequest, Action callback) + public IEnumerator fetchProjectConfig(string project_id, string network, string build_env, Action callback) { //Debug.Log("network =>" + network); string baseUrl = SIGNER_MAP[network]; - var requestURL = $"{baseUrl}/api/configuration?project_id={project_id}&network={network}&whitelist=true"; + var requestURL = $"{baseUrl}/api/v2/configuration?project_id={project_id}&network={network}&build_env={build_env}"; var request = UnityWebRequest.Get(requestURL); yield return request.SendWebRequest(); @@ -111,6 +111,7 @@ public IEnumerator fetchProjectConfig(string project_id, string network, Action< if (request.result == UnityWebRequest.Result.Success) { string result = request.downloadHandler.text; + //Debug.Log("fetch config raw API result: " + result); callback(Newtonsoft.Json.JsonConvert.DeserializeObject(result)); } else diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index fab6b82..a522090 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -11,7 +11,6 @@ using Newtonsoft.Json.Linq; using Org.BouncyCastle.Math; using UnityEngine; -using Web3AuthSDK.Editor; public class Web3Auth : MonoBehaviour { @@ -88,7 +87,7 @@ public void Awake() onDeepLinkActivated(Application.absoluteURL); #if UNITY_EDITOR - Web3AuthDebug.onURLRecieved += (Uri url) => + Web3AuthSDK.Editor.Web3AuthDebug.onURLRecieved += (Uri url) => { this.setResultUrl(url); }; @@ -370,17 +369,28 @@ public async void showWalletUI(string path = "wallet") this.initParams["redirectUrl"] = Utils.GetCurrentURL(); #endif - if (projectConfigResponse?.chains != null) - { - string chainsJson = JsonConvert.SerializeObject(projectConfigResponse.chains, Formatting.None, new JsonSerializerSettings - { - Converters = new List { new StringEnumConverter() }, - NullValueHandling = NullValueHandling.Ignore - }); - this.initParams["chains"] = chainsJson; - } - - this.initParams["chainId"] = web3AuthOptions.defaultChainId ?? "0x1"; + if (projectConfigResponse?.chains != null && projectConfigResponse.chains.Count > 0) + { + string chainsJson = JsonConvert.SerializeObject(projectConfigResponse.chains, Formatting.None, new JsonSerializerSettings + { + Converters = new List { new StringEnumConverter() }, + NullValueHandling = NullValueHandling.Ignore + }); + + this.initParams["chains"] = chainsJson; + + // Set defaultChainId and chainId based on the first chain + var firstChainId = projectConfigResponse.chains[0]?.chainId ?? web3AuthOptions.defaultChainId ?? "0x1"; + this.initParams["defaultChainId"] = firstChainId; + this.initParams["chainId"] = firstChainId; + } + else + { + // Fallback to web3AuthOptions.defaultChainId or "0x1" + string fallbackChainId = web3AuthOptions.defaultChainId ?? "0x1"; + this.initParams["defaultChainId"] = fallbackChainId; + this.initParams["chainId"] = fallbackChainId; + } if (projectConfigResponse?.embeddedWalletAuth != null) { @@ -643,16 +653,29 @@ public async void request(string method, JArray requestParams, string path = "wa this.initParams["redirectUrl"] = Utils.GetCurrentURL(); #endif - if (projectConfigResponse?.chains != null) - { - string chainsJson = JsonConvert.SerializeObject(projectConfigResponse.chains, Formatting.None, new JsonSerializerSettings - { - Converters = new List { new StringEnumConverter() }, - NullValueHandling = NullValueHandling.Ignore - }); - this.initParams["chains"] = chainsJson; - } - this.initParams["chainId"] = web3AuthOptions.defaultChainId ?? "0x1"; + if (projectConfigResponse?.chains != null && projectConfigResponse.chains.Count > 0) + { + string chainsJson = JsonConvert.SerializeObject(projectConfigResponse.chains, Formatting.None, new JsonSerializerSettings + { + Converters = new List { new StringEnumConverter() }, + NullValueHandling = NullValueHandling.Ignore + }); + Debug.Log("Chain JSON:\n" + chainsJson); + this.initParams["chains"] = chainsJson; + + // Set defaultChainId and chainId based on the first chain + var firstChainId = projectConfigResponse.chains[0]?.chainId ?? web3AuthOptions.defaultChainId ?? "0x1"; + this.initParams["defaultChainId"] = firstChainId; + this.initParams["chainId"] = firstChainId; + } + else + { + // Fallback to web3AuthOptions.defaultChainId or "0x1" + string fallbackChainId = web3AuthOptions.defaultChainId ?? "0x1"; + this.initParams["defaultChainId"] = fallbackChainId; + this.initParams["chainId"] = fallbackChainId; + } + if (projectConfigResponse?.embeddedWalletAuth != null) { this.initParams["embeddedWalletAuth"] = projectConfigResponse.embeddedWalletAuth; @@ -671,6 +694,7 @@ public async void request(string method, JArray requestParams, string path = "wa } var newSessionId = KeyStoreManagerUtils.generateRandomSessionKey(); + //Debug.Log("paramMap durinr request func: =>" + JsonConvert.SerializeObject(paramMap)); string loginId = await createSession(JsonConvert.SerializeObject(paramMap, Formatting.None, new JsonSerializerSettings { @@ -729,7 +753,7 @@ private void authorizeSession(string newSessionId, string origin) if (string.IsNullOrEmpty(newSessionId)) { sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); - Debug.Log("sessionId during authorizeSession in if part =>" + sessionId); + //Debug.Log("sessionId during authorizeSession in if part =>" + sessionId); } else { @@ -742,7 +766,7 @@ private void authorizeSession(string newSessionId, string origin) //Debug.Log("origin: =>" + origin); StartCoroutine(Web3AuthApi.getInstance().authorizeSession(pubKey, origin, (response => { - if (response != null) + if (response != null && !string.IsNullOrEmpty(response.message)) { var shareMetadata = JsonConvert.DeserializeObject(response.message); @@ -913,29 +937,25 @@ private async Task createSession(string data, long sessionTime, string a private async Task fetchProjectConfig() { TaskCompletionSource fetchProjectConfigResponse = new TaskCompletionSource(); - StartCoroutine(Web3AuthApi.getInstance().fetchProjectConfig(this.web3AuthOptions.clientId, this.web3AuthOptions.web3AuthNetwork.ToString().ToLower(), (response => + StartCoroutine(Web3AuthApi.getInstance().fetchProjectConfig(this.web3AuthOptions.clientId, this.web3AuthOptions.web3AuthNetwork.ToString().ToLower(), + this.web3AuthOptions.authBuildEnv.ToString().ToLower(), (response => { projectConfigResponse = response; if (response != null) { this.web3AuthOptions.originData = this.web3AuthOptions.originData.mergeMaps(response.whitelist?.signed_urls); if (response?.whitelabel != null) - { - if (this.web3AuthOptions.whiteLabel == null) - { - this.web3AuthOptions.whiteLabel = response.whitelabel; - } - else - { - this.web3AuthOptions.whiteLabel = this.web3AuthOptions.whiteLabel?.merge(response.whitelabel); - } - } - - if (response?.whitelabel != null) - { - this.web3AuthOptions.whiteLabel = this.web3AuthOptions.whiteLabel == null ? response.whitelabel : this.web3AuthOptions.whiteLabel?.merge(response.whitelabel); - this.web3AuthOptions.walletServicesConfig.whiteLabel = this.web3AuthOptions.walletServicesConfig.whiteLabel == null ? response.whitelabel : this.web3AuthOptions.walletServicesConfig.whiteLabel?.merge(response.whitelabel); - } + { + var whitelabel = response.whitelabel; + + this.web3AuthOptions.whiteLabel = this.web3AuthOptions.whiteLabel?.merge(whitelabel) ?? whitelabel; + + if (this.web3AuthOptions.walletServicesConfig != null) + { + this.web3AuthOptions.walletServicesConfig.whiteLabel = + this.web3AuthOptions.walletServicesConfig.whiteLabel?.merge(whitelabel) ?? whitelabel; + } + } //Debug.Log("this.web3AuthOptions: =>" + JsonConvert.SerializeObject(this.web3AuthOptions)); From 70cae01e302a87abe2be84a3e2ea31541ac9cc26 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Mon, 28 Jul 2025 14:37:37 +0400 Subject: [PATCH 20/25] Update example Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index 015ab50..260104c 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -102,10 +102,10 @@ void Start() clientId = "d84f6xvbdV75VTGmHiMWfZLeSPk8M07C" } }, - clientId = "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ", + clientId = "BHgArYmWwSeq21czpcarYh0EVq2WWOzflX-NTK-tY1-1pauPzHKRRLgpABkmYiIV_og9jAvoIxQ8L3Smrwe04Lw", authBuildEnv = BuildEnv.TESTING, redirectUrl = new Uri("torusapp://com.torus.Web3AuthUnity"), - web3AuthNetwork = Web3Auth.Network.SAPPHIRE_MAINNET, + web3AuthNetwork = Web3Auth.Network.SAPPHIRE_DEVNET, defaultChainId = "0x1", sessionTime = 86400 }); From 5819fd640f0d47ce109400424aef58b6c58f8a87 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Wed, 30 Jul 2025 11:06:10 +0400 Subject: [PATCH 21/25] feat: update example Signed-off-by: Gaurav Goel --- Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index 015ab50..260104c 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -102,10 +102,10 @@ void Start() clientId = "d84f6xvbdV75VTGmHiMWfZLeSPk8M07C" } }, - clientId = "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ", + clientId = "BHgArYmWwSeq21czpcarYh0EVq2WWOzflX-NTK-tY1-1pauPzHKRRLgpABkmYiIV_og9jAvoIxQ8L3Smrwe04Lw", authBuildEnv = BuildEnv.TESTING, redirectUrl = new Uri("torusapp://com.torus.Web3AuthUnity"), - web3AuthNetwork = Web3Auth.Network.SAPPHIRE_MAINNET, + web3AuthNetwork = Web3Auth.Network.SAPPHIRE_DEVNET, defaultChainId = "0x1", sessionTime = 86400 }); From b63cb27110316bf500230a712948bfa0f87d3570 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Thu, 13 Aug 2026 13:59:31 +0700 Subject: [PATCH 22/25] reuse local redirect listener and normalize sessionIds --- Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs | 13 +- .../Keystore/KeyStoreManagerUtils.cs | 37 +++++ .../Web3AuthSDK/Samples/Web3AuthSample.cs | 7 +- .../Web3AuthSDK/Samples/Web3AuthSample.unity | 4 +- .../Web3AuthSDK/Types/AuthConnection.cs.meta | 11 ++ .../Types/AuthConnectionConfig.cs.meta | 11 ++ .../Plugins/Web3AuthSDK/Types/Chains.cs.meta | 11 ++ .../Web3AuthSDK/Types/SessionResponse.cs | 5 +- .../Web3AuthSDK/Types/SessionResponse.cs.meta | 11 ++ .../Web3AuthSDK/Types/SmartAccountsConfig.cs | 19 ++- .../Web3AuthSDK/Types/Web3AuthOptions.cs | 3 +- Assets/Plugins/Web3AuthSDK/Utils.cs | 7 + Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 146 ++++++++++++++---- 13 files changed, 242 insertions(+), 43 deletions(-) create mode 100644 Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs.meta create mode 100644 Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs.meta create mode 100644 Assets/Plugins/Web3AuthSDK/Types/Chains.cs.meta create mode 100644 Assets/Plugins/Web3AuthSDK/Types/SessionResponse.cs.meta diff --git a/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs b/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs index d059072..443dbac 100644 --- a/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs +++ b/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs @@ -117,10 +117,21 @@ public IEnumerator fetchProjectConfig(string project_id, string network, string if (request.result == UnityWebRequest.Result.Success) { string result = request.downloadHandler.text; - callback(JsonConvert.DeserializeObject(result)); + try + { + callback(JsonConvert.DeserializeObject(result)); + } + catch (Exception ex) + { + Debug.LogError($"Failed to deserialize project config: {ex.Message}\nRaw: {result}"); + callback(null); + } } else + { + Debug.LogError($"Failed to fetch project config ({request.responseCode}): {request.downloadHandler?.text ?? request.error}\nURL: {requestURL}"); callback(null); + } } public static Dictionary SIGNER_MAP = new Dictionary() diff --git a/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs b/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs index aa8a0b0..77f623b 100644 --- a/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs +++ b/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs @@ -30,10 +30,47 @@ public class KeyStoreManagerUtils public static string MAC = "mac"; public static string REDIRECT_URL = "redirectUrl"; + public static string normalizeSessionId(string sessionId) + { + if (string.IsNullOrWhiteSpace(sessionId)) + return string.Empty; + + sessionId = sessionId.Trim(); + if (sessionId.StartsWith("0x", System.StringComparison.OrdinalIgnoreCase)) + sessionId = sessionId.Substring(2); + + return sessionId; + } + + public static bool isValidSessionId(string sessionId) + { + if (string.IsNullOrEmpty(sessionId)) + return false; + + for (int i = 0; i < sessionId.Length; i++) + { + char c = sessionId[i]; + bool isHex = (c >= '0' && c <= '9') || + (c >= 'a' && c <= 'f') || + (c >= 'A' && c <= 'F'); + if (!isHex) + return false; + } + + return true; + } + public static string getPubKey(string sessionId) { try { + sessionId = normalizeSessionId(sessionId); + if (!isValidSessionId(sessionId)) + { + UnityEngine.Debug.LogError($"getPubKey: sessionId is not valid hex (length={sessionId?.Length ?? 0})."); + return ""; + } + var domain = SecNamedCurves.GetByName("secp256k1"); var parameters = new ECDomainParameters(domain.Curve, domain.G, domain.N); diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index 250a2ea..740c93c 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -102,10 +102,11 @@ void Start() clientId = "d84f6xvbdV75VTGmHiMWfZLeSPk8M07C" } }, - clientId = "BHgArYmWwSeq21czpcarYh0EVq2WWOzflX-NTK-tY1-1pauPzHKRRLgpABkmYiIV_og9jAvoIxQ8L3Smrwe04Lw", - authBuildEnv = BuildEnv.TESTING, + clientId = "BPrPLO2tetqnI5UsOuuGK9SSmMGrRHi-y6LEtKp6PW5P1btBYqNkLFFtExK53PqOt-H9JszGhfQOq2FOGGNf-TE", + authBuildEnv = BuildEnv.PRODUCTION, redirectUrl = new Uri("torusapp://com.torus.Web3AuthUnity"), - web3AuthNetwork = Web3Auth.Network.SAPPHIRE_DEVNET, + localRedirectHost = "web3auth.localtest.me", + web3AuthNetwork = Web3Auth.Network.SAPPHIRE_MAINNET, defaultChainId = "0x1", sessionTime = 86400 }); diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.unity b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.unity index 4fa2deb..f889936 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.unity +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.unity @@ -1016,9 +1016,9 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: 3eab2a0bf902d6e4b9c2e968ad89f528, type: 3} m_Name: m_EditorClassIdentifier: - clientId: BHgArYmWwSeq21czpcarYh0EVq2WWOzflX-NTK-tY1-1pauPzHKRRLgpABkmYiIV_og9jAvoIxQ8L3Smrwe04Lw + clientId: BPrPLO2tetqnI5UsOuuGK9SSmMGrRHi-y6LEtKp6PW5P1btBYqNkLFFtExK53PqOt-H9JszGhfQOq2FOGGNf-TE redirectUri: torusapp://com.torus.Web3AuthUnity/auth - network: 4 + network: 5 --- !u!1 &505954357 GameObject: m_ObjectHideFlags: 0 diff --git a/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs.meta new file mode 100644 index 0000000..4a8a291 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/AuthConnection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3cac2e9bc4f5b4409a259f14150516fb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs.meta new file mode 100644 index 0000000..5bee978 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/AuthConnectionConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b9bcd576ed9fb46b180962fc2f2fe66b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/Web3AuthSDK/Types/Chains.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/Chains.cs.meta new file mode 100644 index 0000000..c74669d --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/Chains.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 58c3bd9c2267c46489245c7dc2453bb1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/Web3AuthSDK/Types/SessionResponse.cs b/Assets/Plugins/Web3AuthSDK/Types/SessionResponse.cs index ae516fe..803355d 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/SessionResponse.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/SessionResponse.cs @@ -1,4 +1,7 @@ +using Newtonsoft.Json; + public class SessionResponse { - public string sessionId; + [JsonProperty("sessionId")] + public string sessionId { get; set; } } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/SessionResponse.cs.meta b/Assets/Plugins/Web3AuthSDK/Types/SessionResponse.cs.meta new file mode 100644 index 0000000..81276be --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Types/SessionResponse.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c8852eee12be949c28c26e5bce6eb19b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs index fb675f0..f8ede03 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/SmartAccountsConfig.cs @@ -1,13 +1,15 @@ using System.Collections.Generic; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; namespace Plugins.Web3AuthSDK.Types { public class SmartAccountsConfig { - public SmartAccountType SmartAccountType { get; set; } - + public SmartAccountType smartAccountType { get; set; } + public SmartAccountWalletScope walletScope { get; set; } - + public List chains { get; set; } } @@ -19,13 +21,22 @@ public class ChainConfig } } +[JsonConverter(typeof(StringEnumConverter))] public enum SmartAccountWalletScope { embedded, all } +[JsonConverter(typeof(StringEnumConverter))] public enum SmartAccountType { - biconomy, kernel, safe, trust, light, simple, nexus + metamask, + biconomy, + kernel, + safe, + trust, + light, + simple, + nexus } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index 283825c..bdcfa87 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -9,6 +9,7 @@ public class Web3AuthOptions { public string clientId { get; set; } public Uri redirectUrl { get; set; } public Dictionary originData { get; set; } = null; + public string localRedirectHost { get; set; } = Utils.LOCAL_REDIRECT_HOST; [JsonProperty("buildEnv")] public Web3Auth.BuildEnv authBuildEnv { get; set; } = Web3Auth.BuildEnv.PRODUCTION; @@ -66,6 +67,6 @@ public string walletSdkUrl { public WalletServicesConfig? walletServicesConfig { get; set; } public MfaSettings? mfaSettings { get; set; } = null; - private const string authDashboardVersion = "v9"; + private const string authDashboardVersion = "v10"; private const string walletAccountConstant = "wallet/account"; } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Utils.cs b/Assets/Plugins/Web3AuthSDK/Utils.cs index 94039ba..e240695 100644 --- a/Assets/Plugins/Web3AuthSDK/Utils.cs +++ b/Assets/Plugins/Web3AuthSDK/Utils.cs @@ -92,4 +92,11 @@ public static int GetRandomUnusedPort() } + public const string LOCAL_REDIRECT_HOST = "localhost"; + + public static string GetLocalRedirectBaseUrl(string host = null) + { + var redirectHost = string.IsNullOrWhiteSpace(host) ? LOCAL_REDIRECT_HOST : host.Trim(); + return $"http://{redirectHost}:{LOCAL_REDIRECT_PORT}"; + } } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index 4b8f4ae..090140c 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -70,6 +70,10 @@ public static void setSignResponse(SignResponse _response) private Network network; private string redirectUrl; +#if UNITY_STANDALONE || UNITY_EDITOR + private HttpListener localHttpListener; +#endif + private static readonly Queue _executionQueue = new Queue(); public void Awake() @@ -173,42 +177,81 @@ private void onDeepLinkActivated(string url) } #if UNITY_STANDALONE || UNITY_EDITOR + private void StopLocalWebserver() + { + if (localHttpListener == null) + return; + + try + { + if (localHttpListener.IsListening) + localHttpListener.Stop(); + localHttpListener.Close(); + } + catch (Exception ex) + { + Debug.LogWarning("Failed to stop local redirect server: " + ex.Message); + } + finally + { + localHttpListener = null; + } + } + private string StartLocalWebserver() { - HttpListener httpListener = new HttpListener(); + // Always free the previous listener so a second wallet/MFA/sign flow can bind the same port. + StopLocalWebserver(); - var redirectUrl = $"http://localhost:{Utils.GetRandomUnusedPort()}"; + localHttpListener = new HttpListener(); - httpListener.Prefixes.Add($"{redirectUrl}/complete/"); - httpListener.Prefixes.Add($"{redirectUrl}/auth/"); - httpListener.Start(); - httpListener.BeginGetContext(new AsyncCallback(IncomingHttpRequest), httpListener); + var redirectUrl = Utils.GetLocalRedirectBaseUrl(this.web3AuthOptions?.localRedirectHost); + + localHttpListener.Prefixes.Add($"{redirectUrl}/complete/"); + localHttpListener.Prefixes.Add($"{redirectUrl}/auth/"); + try + { + localHttpListener.Start(); + } + catch (HttpListenerException ex) + { + localHttpListener = null; + throw new Exception( + $"Failed to start local redirect server at {redirectUrl}. " + + $"Make sure the host resolves to this machine and the port is free. ({ex.Message})"); + } + localHttpListener.BeginGetContext(new AsyncCallback(IncomingHttpRequest), localHttpListener); return redirectUrl + "/complete/"; } private void IncomingHttpRequest(IAsyncResult result) { - - // get back the reference to our http listener HttpListener httpListener = (HttpListener)result.AsyncState; - // fetch the context object - HttpListenerContext httpContext = httpListener.EndGetContext(result); + // Listener may have been stopped/replaced by a newer StartLocalWebserver call. + if (httpListener == null || !httpListener.IsListening) + return; - // if we'd like the HTTP listener to accept more incoming requests, we'd just restart the "get context" here: - // httpListener.BeginGetContext(new AsyncCallback(IncomingHttpRequest),httpListener); - // however, since we only want/expect the one, single auth redirect, we don't need/want this, now. - // but this is what you would do if you'd want to implement more (simple) "webserver" functionality - // in your project. + HttpListenerContext httpContext; + try + { + httpContext = httpListener.EndGetContext(result); + } + catch (ObjectDisposedException) + { + return; + } + catch (HttpListenerException) + { + return; + } - // the context object has the request object for us, that holds details about the incoming request HttpListenerRequest httpRequest = httpContext.Request; HttpListenerResponse httpResponse = httpContext.Response; if (httpRequest.Url.LocalPath == "/complete/") { - httpListener.BeginGetContext(new AsyncCallback(IncomingHttpRequest), httpListener); var responseString = @" @@ -237,7 +280,7 @@ private void IncomingHttpRequest(IAsyncResult result) if (window.location.hash.trim() == """") { document.querySelector(""#error"").style.display=""flex""; } else { - fetch(`http://${window.location.host}/auth/?code=${window.location.hash.slice(1,window.location.hash.length)}`).then(function(response) { + fetch(`http://${window.location.host}/auth/?code=${encodeURIComponent(window.location.hash.slice(1))}`).then(function(response) { console.log(response); document.querySelector(""#success"").style.display=""flex""; }).catch(function(error) { @@ -276,7 +319,12 @@ private void IncomingHttpRequest(IAsyncResult result) this.setResultUrl(new Uri($"http://localhost#{code}")); } - httpListener.Close(); + if (ReferenceEquals(localHttpListener, httpListener)) + StopLocalWebserver(); + else + { + try { httpListener.Close(); } catch { /* ignored */ } + } } } #endif @@ -506,7 +554,7 @@ public void setResultUrl(Uri uri) SessionResponse sessionResponse = null; try { - sessionResponse = JsonUtility.FromJson(decodedString); + sessionResponse = JsonConvert.DeserializeObject(decodedString); } catch (Exception e) { @@ -514,10 +562,17 @@ public void setResultUrl(Uri uri) } if (sessionResponse == null || string.IsNullOrEmpty(sessionResponse.sessionId)) { - Debug.LogError("Invalid or missing session response (sessionId is null or empty)."); + Debug.LogError("Invalid or missing session response (sessionId is null or empty). Decoded: " + decodedString); + return; + } + string sessionId = KeyStoreManagerUtils.normalizeSessionId(sessionResponse.sessionId); + if (!KeyStoreManagerUtils.isValidSessionId(sessionId)) + { + Debug.LogError( + "Invalid sessionId format from redirect (expected hex private key). " + + $"length={sessionResponse.sessionId?.Length}, decoded={decodedString}"); return; } - string sessionId = sessionResponse.sessionId; this.Enqueue(() => KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.SESSION_ID, sessionId)); this.Enqueue(() => KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.REDIRECT_URL, redirectUrl)); @@ -540,12 +595,16 @@ private string getQueryParamValue(Uri uri, string key) string[] queryParameters = uri.Query.Substring(1).Split('&'); foreach (string queryParameter in queryParameters) { - string[] keyValue = queryParameter.Split('='); - if (keyValue[0] == key) - { - value = keyValue[1]; - break; - } + int separator = queryParameter.IndexOf('='); + if (separator <= 0) + continue; + + string paramKey = Uri.UnescapeDataString(queryParameter.Substring(0, separator)); + if (paramKey != key) + continue; + + value = Uri.UnescapeDataString(queryParameter.Substring(separator + 1)); + break; } } return value; @@ -555,8 +614,8 @@ private string decodeBase64Params(string base64Params) { if(string.IsNullOrEmpty(base64Params)) return string.Empty; - // Replace URL-safe characters - base64Params = base64Params.Replace('-', '+').Replace('_', '/'); + // Replace URL-safe characters and spaces introduced by poorly encoded query strings + base64Params = base64Params.Replace('-', '+').Replace('_', '/').Replace(' ', '+'); var d = base64Params.Length % 4; if (d != 0) { @@ -813,7 +872,20 @@ private void authorizeSession(string newSessionId, string origin) if (!string.IsNullOrEmpty(sessionId)) { + sessionId = KeyStoreManagerUtils.normalizeSessionId(sessionId); + if (!KeyStoreManagerUtils.isValidSessionId(sessionId)) + { + Debug.LogError($"authorizeSession: stored sessionId is not valid hex (length={sessionId.Length}). Clearing it."); + KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.SESSION_ID); + return; + } + var pubKey = KeyStoreManagerUtils.getPubKey(sessionId); + if (string.IsNullOrEmpty(pubKey)) + { + Debug.LogError("authorizeSession: failed to derive public key from sessionId."); + return; + } StartCoroutine(Web3AuthApi.getInstance().authorizeSession(pubKey, origin, (response => { if (response != null && !string.IsNullOrEmpty(response.message)) @@ -852,7 +924,11 @@ private void authorizeSession(string newSessionId, string origin) if (!string.IsNullOrEmpty(this.web3AuthResponse.sessionId)) { - KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.SESSION_ID, this.web3AuthResponse.sessionId); + var responseSessionId = KeyStoreManagerUtils.normalizeSessionId(this.web3AuthResponse.sessionId); + if (KeyStoreManagerUtils.isValidSessionId(responseSessionId)) + { + KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.SESSION_ID, responseSessionId); + } } if (web3AuthResponse.userInfo != null && !string.IsNullOrEmpty(web3AuthResponse.userInfo.dappShare) && @@ -1071,6 +1147,14 @@ public UserInfo getUserInfo() return web3AuthResponse.userInfo; } + private void OnDestroy() + { +#if UNITY_STANDALONE || UNITY_EDITOR + StopLocalWebserver(); +#endif + Application.deepLinkActivated -= onDeepLinkActivated; + } + public void Update() { lock (_executionQueue) From c29f5352d75e0af629fb59083c1f2d2b90e9e3e1 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Thu, 13 Aug 2026 14:31:51 +0700 Subject: [PATCH 23/25] address cursor comments --- .../Web3AuthSDK/Samples/Web3AuthSample.cs | 2 +- .../Web3AuthSDK/Types/ExtraLoginOptions.cs | 11 +++++- .../Web3AuthSDK/Types/WalletServicesConfig.cs | 15 ++++--- .../Web3AuthSDK/Types/WalletUiConfig.cs | 39 +++++++++++-------- .../Web3AuthSDK/Types/Web3AuthOptions.cs | 2 +- Assets/Plugins/Web3AuthSDK/Utils.cs | 4 +- Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 30 +++++++++++++- 7 files changed, 73 insertions(+), 30 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index 740c93c..fd5bd87 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -271,7 +271,7 @@ private void showWalletUI() { { Debug.Log($"Chain ID: {config.chainId}, RPC Target: {config.rpcTarget}, Ticker: {config.ticker}, Namespace: {config.chainNamespace}"); } - web3Auth.showWalletUI("0x1"); + web3Auth.showWalletUI(); } private void request() { diff --git a/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs index b0d1c9a..4202e9d 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/ExtraLoginOptions.cs @@ -1,4 +1,7 @@ using System.Collections.Generic; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; public class ExtraLoginOptions { public Dictionary additionalParams { get; set; } @@ -13,7 +16,7 @@ public class ExtraLoginOptions { public string ui_locales { get; set; } public string id_token { get; set; } public string access_token { get; set; } - private EmailFlowType flow_type { get; set; } = EmailFlowType.link; + public EmailFlowType flow_type { get; set; } = EmailFlowType.link; public string id_token_hint { get; set; } public string login_hint { get; set; } public string acr_values { get; set; } @@ -26,7 +29,11 @@ public class ExtraLoginOptions { public string redirect_uri { get; set; } } +[JsonConverter(typeof(StringEnumConverter))] public enum EmailFlowType { - link, code + [EnumMember(Value = "link")] + link, + [EnumMember(Value = "code")] + code } \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs index 3d6f44f..c0ce0a3 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/WalletServicesConfig.cs @@ -1,26 +1,29 @@ +using System.Runtime.Serialization; using Newtonsoft.Json; +using Newtonsoft.Json.Converters; namespace Plugins.Web3AuthSDK.Types { public class WalletServicesConfig { public ConfirmationStrategy? confirmationStrategy { get; set; } = ConfirmationStrategy.DEFAULT; - + public WhiteLabelData? whiteLabel { get; set; } } } +[JsonConverter(typeof(StringEnumConverter))] public enum ConfirmationStrategy { - [JsonProperty("popup")] + [EnumMember(Value = "popup")] POPUP, - [JsonProperty("modal")] + [EnumMember(Value = "modal")] MODAL, - [JsonProperty("auto-approve")] + [EnumMember(Value = "auto-approve")] AUTO_APPROVE, - [JsonProperty("default")] + [EnumMember(Value = "default")] DEFAULT -} \ No newline at end of file +} diff --git a/Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs b/Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs index cbb3059..77e3ed2 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/WalletUiConfig.cs @@ -1,4 +1,6 @@ +using System.Runtime.Serialization; using Newtonsoft.Json; +using Newtonsoft.Json.Converters; namespace Plugins.Web3AuthSDK.Types { @@ -7,45 +9,50 @@ public class WalletUiConfig public bool? enablePortfolioWidget { get; set; } public bool? enableConfirmationModal { get; set; } - + public bool? enableWalletConnect { get; set; } - + public bool? enableTokenDisplay { get; set; } - + public bool? enableNftDisplay { get; set; } - + public bool? enableShowAllTokensButton { get; set; } - + public bool? enableBuyButton { get; set; } - + public bool? enableSendButton { get; set; } - + public bool? enableSwapButton { get; set; } - + public bool? enableReceiveButton { get; set; } - + public ButtonPositionType? portfolioWidgetPosition { get; set; } - + public DefaultPortfolioType? defaultPortfolio { get; set; } } } +[JsonConverter(typeof(StringEnumConverter))] public enum ButtonPositionType { - [JsonProperty("bottom-left")] + [EnumMember(Value = "bottom-left")] BOTTOM_LEFT, - [JsonProperty("top-left")] + [EnumMember(Value = "top-left")] TOP_LEFT, - [JsonProperty("bottom-right")] + [EnumMember(Value = "bottom-right")] BOTTOM_RIGHT, - [JsonProperty("top-right")] + [EnumMember(Value = "top-right")] TOP_RIGHT } +[JsonConverter(typeof(StringEnumConverter))] public enum DefaultPortfolioType { - token , nft -} \ No newline at end of file + [EnumMember(Value = "token")] + token, + [EnumMember(Value = "nft")] + nft +} diff --git a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs index bdcfa87..8ef54e9 100644 --- a/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs +++ b/Assets/Plugins/Web3AuthSDK/Types/Web3AuthOptions.cs @@ -26,7 +26,7 @@ public string sdkUrl { set { } } - public List? authConnectionConfig { get; set; } = new List(); + public List? authConnectionConfig { get; set; } = null; public WhiteLabelData? whiteLabel { get; set; } public string dashboardUrl { diff --git a/Assets/Plugins/Web3AuthSDK/Utils.cs b/Assets/Plugins/Web3AuthSDK/Utils.cs index e240695..7cab77d 100644 --- a/Assets/Plugins/Web3AuthSDK/Utils.cs +++ b/Assets/Plugins/Web3AuthSDK/Utils.cs @@ -91,7 +91,7 @@ public static int GetRandomUnusedPort() return port; } - + public const int LOCAL_REDIRECT_PORT = 3000; public const string LOCAL_REDIRECT_HOST = "localhost"; public static string GetLocalRedirectBaseUrl(string host = null) @@ -99,4 +99,4 @@ public static string GetLocalRedirectBaseUrl(string host = null) var redirectHost = string.IsNullOrWhiteSpace(host) ? LOCAL_REDIRECT_HOST : host.Trim(); return $"http://{redirectHost}:{LOCAL_REDIRECT_PORT}"; } -} \ No newline at end of file +} diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index 090140c..3d73115 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -91,6 +91,8 @@ public void Awake() onDeepLinkActivated(Application.absoluteURL); #if UNITY_EDITOR + UnityEditor.AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload; + Web3AuthSDK.Editor.Web3AuthDebug.onURLRecieved += (Uri url) => { this.setResultUrl(url); @@ -107,6 +109,14 @@ public void Awake() #endif } +#if UNITY_EDITOR + private void OnBeforeAssemblyReload() + { + // Close HttpListener before domain reload to avoid "invalid GC handle" warnings. + StopLocalWebserver(); + } +#endif + private string getResolvedClientId() { if (!string.IsNullOrEmpty(this.web3AuthOptions?.clientId)) @@ -149,9 +159,12 @@ public async void setOptions(Web3AuthOptions web3AuthOptions) if (this.web3AuthOptions.whiteLabel != null) this.initParams["whiteLabel"] = JsonConvert.SerializeObject(this.web3AuthOptions.whiteLabel, settings); - if (this.web3AuthOptions.authConnectionConfig != null) + if (this.web3AuthOptions.authConnectionConfig != null && this.web3AuthOptions.authConnectionConfig.Count > 0) this.initParams["authConnectionConfig"] = JsonConvert.SerializeObject(this.web3AuthOptions.authConnectionConfig, settings); + if (this.web3AuthOptions.walletServicesConfig != null) + this.initParams["walletServicesConfig"] = JsonConvert.SerializeObject(this.web3AuthOptions.walletServicesConfig, settings); + if (this.web3AuthOptions.authBuildEnv != null) this.initParams["authBuildEnv"] = this.web3AuthOptions.authBuildEnv.ToString().ToLower(); @@ -1097,7 +1110,7 @@ private async Task fetchProjectConfig() if (this.web3AuthOptions.walletServicesConfig != null) { - this.web3AuthOptions.walletServicesConfig.whiteLabel = + this.web3AuthOptions.walletServicesConfig.whiteLabel = this.web3AuthOptions.walletServicesConfig.whiteLabel?.merge(whitelabel) ?? whitelabel; } } @@ -1113,6 +1126,9 @@ private async Task fetchProjectConfig() if(this.web3AuthOptions.originData != null) this.initParams["originData"] = JsonConvert.SerializeObject(this.web3AuthOptions.originData, settings); + if (this.web3AuthOptions.walletServicesConfig != null) + this.initParams["walletServicesConfig"] = JsonConvert.SerializeObject(this.web3AuthOptions.walletServicesConfig, settings); + fetchProjectConfigResponse.SetResult(true); } else @@ -1147,8 +1163,18 @@ public UserInfo getUserInfo() return web3AuthResponse.userInfo; } + private void OnDisable() + { +#if UNITY_STANDALONE || UNITY_EDITOR + StopLocalWebserver(); +#endif + } + private void OnDestroy() { +#if UNITY_EDITOR + UnityEditor.AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload; +#endif #if UNITY_STANDALONE || UNITY_EDITOR StopLocalWebserver(); #endif From 9dba82ce942c28f431f2f6a2d6a5638dc7338cd1 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Thu, 13 Aug 2026 14:46:49 +0700 Subject: [PATCH 24/25] fix: pass authConnectionConfig as array in session options --- Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index 3d73115..1619e5c 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -160,10 +160,10 @@ public async void setOptions(Web3AuthOptions web3AuthOptions) this.initParams["whiteLabel"] = JsonConvert.SerializeObject(this.web3AuthOptions.whiteLabel, settings); if (this.web3AuthOptions.authConnectionConfig != null && this.web3AuthOptions.authConnectionConfig.Count > 0) - this.initParams["authConnectionConfig"] = JsonConvert.SerializeObject(this.web3AuthOptions.authConnectionConfig, settings); + this.initParams["authConnectionConfig"] = this.web3AuthOptions.authConnectionConfig; if (this.web3AuthOptions.walletServicesConfig != null) - this.initParams["walletServicesConfig"] = JsonConvert.SerializeObject(this.web3AuthOptions.walletServicesConfig, settings); + this.initParams["walletServicesConfig"] = this.web3AuthOptions.walletServicesConfig; if (this.web3AuthOptions.authBuildEnv != null) this.initParams["authBuildEnv"] = this.web3AuthOptions.authBuildEnv.ToString().ToLower(); @@ -1127,7 +1127,7 @@ private async Task fetchProjectConfig() this.initParams["originData"] = JsonConvert.SerializeObject(this.web3AuthOptions.originData, settings); if (this.web3AuthOptions.walletServicesConfig != null) - this.initParams["walletServicesConfig"] = JsonConvert.SerializeObject(this.web3AuthOptions.walletServicesConfig, settings); + this.initParams["walletServicesConfig"] = this.web3AuthOptions.walletServicesConfig; fetchProjectConfigResponse.SetResult(true); } From bb63900e73302765575ee7f649186eb0974f0421 Mon Sep 17 00:00:00 2001 From: Gaurav Goel Date: Thu, 13 Aug 2026 17:08:35 +0700 Subject: [PATCH 25/25] fix: Android deep-link login and session origin handling --- .gitignore | 5 +- Assets/Plugins/Android/AndroidManifest.xml | 14 +- .../Web3AuthSDK/Android/Web3AuthActivity.java | 59 +++ .../Android/Web3AuthActivity.java.meta | 32 ++ .../Api/Models/LogoutApiRequest.cs | 1 + Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs | 217 +++++++-- .../Keystore/KeyStoreManagerUtils.cs | 3 +- .../Web3AuthSDK/Samples/Web3AuthSample.cs | 12 +- Assets/Plugins/Web3AuthSDK/Utils.cs | 13 +- Assets/Plugins/Web3AuthSDK/Web3Auth.cs | 423 ++++++++++++++---- 10 files changed, 633 insertions(+), 146 deletions(-) create mode 100644 Assets/Plugins/Web3AuthSDK/Android/Web3AuthActivity.java create mode 100644 Assets/Plugins/Web3AuthSDK/Android/Web3AuthActivity.java.meta diff --git a/.gitignore b/.gitignore index 4c36115..a80f880 100644 --- a/.gitignore +++ b/.gitignore @@ -75,4 +75,7 @@ crashlytics-build.properties ios-build/* web3auth-android-build_*/ TestBuild_BackUpThisFolder_ButDontShipItWithYourGame/* -.DS_Store \ No newline at end of file +.DS_Store +# TMP Essential Resources (imported locally; package is in Packages/manifest.json) +/[Aa]ssets/[Tt]ext[Mm]esh [Pp]ro/ +/[Aa]ssets/[Tt]ext[Mm]esh [Pp]ro.meta diff --git a/Assets/Plugins/Android/AndroidManifest.xml b/Assets/Plugins/Android/AndroidManifest.xml index 1fd0007..5c578ab 100644 --- a/Assets/Plugins/Android/AndroidManifest.xml +++ b/Assets/Plugins/Android/AndroidManifest.xml @@ -9,8 +9,12 @@ - + @@ -19,11 +23,9 @@ - + - \ No newline at end of file + diff --git a/Assets/Plugins/Web3AuthSDK/Android/Web3AuthActivity.java b/Assets/Plugins/Web3AuthSDK/Android/Web3AuthActivity.java new file mode 100644 index 0000000..7017765 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Android/Web3AuthActivity.java @@ -0,0 +1,59 @@ +package com.web3auth.unity.android; + +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.util.Log; + +import com.unity3d.player.UnityPlayerActivity; + +/** + * Captures torusapp:// Custom Tab redirects. setIntent is required for singleTask + Unity deep links. + */ +public class Web3AuthActivity extends UnityPlayerActivity { + private static final String TAG = "Web3AuthActivity"; + private static String pendingDeepLinkUrl; + + public static synchronized String consumePendingDeepLinkUrl() { + String url = pendingDeepLinkUrl; + pendingDeepLinkUrl = null; + return url; + } + + public static synchronized void setPendingDeepLinkUrl(String url) { + pendingDeepLinkUrl = url; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + captureDeepLink(getIntent()); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + setIntent(intent); + captureDeepLink(intent); + } + + private void captureDeepLink(Intent intent) { + if (intent == null) { + return; + } + Uri data = intent.getData(); + if (data == null) { + return; + } + String url = data.toString(); + if (url == null || url.length() == 0) { + return; + } + if (!url.startsWith("torusapp://")) { + return; + } + Log.d(TAG, "Captured deep link: " + url); + setPendingDeepLinkUrl(url); + intent.setData(null); + } +} diff --git a/Assets/Plugins/Web3AuthSDK/Android/Web3AuthActivity.java.meta b/Assets/Plugins/Web3AuthSDK/Android/Web3AuthActivity.java.meta new file mode 100644 index 0000000..89b585a --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/Android/Web3AuthActivity.java.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: a7c4e2f91b0d4e8a9f3c6d5e4b2a1908 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Android: Android + second: + enabled: 1 + settings: {} + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/Web3AuthSDK/Api/Models/LogoutApiRequest.cs b/Assets/Plugins/Web3AuthSDK/Api/Models/LogoutApiRequest.cs index fe92b8c..7271fda 100644 --- a/Assets/Plugins/Web3AuthSDK/Api/Models/LogoutApiRequest.cs +++ b/Assets/Plugins/Web3AuthSDK/Api/Models/LogoutApiRequest.cs @@ -9,4 +9,5 @@ public class LogoutApiRequest public string signature { get; set; } public long timeout { get; set; } public string allowedOrigin { get; set; } = "*"; + public string sessionNamespace { get; set; } = ""; } diff --git a/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs b/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs index 443dbac..ec7ecdd 100644 --- a/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs +++ b/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs @@ -1,5 +1,6 @@ using System.Collections; using System; +using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine.Networking; @@ -9,7 +10,12 @@ public class Web3AuthApi { static Web3AuthApi instance; - static string baseAddress = "https://session.web3auth.io/v2"; + static readonly string[] sessionHosts = new[] + { + "https://session.web3auth.io/v2", + "https://session-us.web3auth.io/v2", + "https://session-sg.web3auth.io/v2", + }; public static Web3AuthApi getInstance() { @@ -18,62 +24,164 @@ public static Web3AuthApi getInstance() return instance; } + // Auth stores allowedOrigin as scheme://host (no path). Avoid System.Uri for custom schemes (lowercases host). static string getOriginFromRedirectUrl(string redirectUrl) { if (string.IsNullOrEmpty(redirectUrl)) return redirectUrl; - if (!Uri.TryCreate(redirectUrl, UriKind.Absolute, out var uri)) - return redirectUrl; - return uri.GetLeftPart(UriPartial.Authority); + + var cleaned = redirectUrl.Split('#')[0].Split('?')[0].TrimEnd('/'); + + if (cleaned.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + cleaned.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + if (Uri.TryCreate(cleaned, UriKind.Absolute, out var uri)) + return uri.GetLeftPart(UriPartial.Authority); + return cleaned; + } + + var schemeSep = cleaned.IndexOf("://", StringComparison.Ordinal); + if (schemeSep <= 0) + return cleaned; + + var scheme = cleaned.Substring(0, schemeSep); + var rest = cleaned.Substring(schemeSep + 3); + var pathSep = rest.IndexOf('/'); + var authority = pathSep >= 0 ? rest.Substring(0, pathSep) : rest; + if (string.IsNullOrEmpty(authority)) + return cleaned; + + return scheme + "://" + authority; } - public IEnumerator authorizeSession(string key, string redirectUrl, Action callback) + static List buildOriginsToTry(string redirectUrl) { - var requestURL = $"{baseAddress}/store/get"; + var origins = new List(); + void add(string value) + { + if (string.IsNullOrEmpty(value) || origins.Contains(value)) + return; + origins.Add(value); + } - WWWForm data = new WWWForm(); - data.AddField("key", key); + add(getOriginFromRedirectUrl(redirectUrl)); - var request = UnityWebRequest.Post(requestURL, data); - request.SetRequestHeader("origin", getOriginFromRedirectUrl(redirectUrl)); + var primary = getOriginFromRedirectUrl(redirectUrl); + if (!string.IsNullOrEmpty(primary)) + add(primary.ToLowerInvariant()); - yield return request.SendWebRequest(); + if (!string.IsNullOrEmpty(redirectUrl)) + { + var full = redirectUrl.Split('#')[0].Split('?')[0].TrimEnd('/'); + add(full); + add(full.ToLowerInvariant()); + } - if (request.result == UnityWebRequest.Result.Success) + add("*"); + return origins; + } + + static UnityWebRequest PostJson(string url, object body, string originHeader = null) + { + var json = JsonConvert.SerializeObject(body); + var request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST); + request.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(json)); + request.downloadHandler = new DownloadHandlerBuffer(); + request.SetRequestHeader("Content-Type", "application/json"); + if (!string.IsNullOrEmpty(originHeader)) + request.SetRequestHeader("origin", originHeader); + return request; + } + + public IEnumerator authorizeSession(string key, string redirectUrl, Action callback, bool quiet = false) + { + var originsToTry = buildOriginsToTry(redirectUrl); + var keyNormalized = (key ?? "").ToLowerInvariant(); + StoreApiResponse finalResponse = null; + int maxAttempts = quiet ? 1 : 3; + + if (!quiet) + Debug.Log($"Web3Auth authorizeSession origins=[{string.Join(", ", originsToTry)}] keyLength={keyNormalized.Length}"); + + for (int attempt = 0; attempt < maxAttempts && finalResponse == null; attempt++) { - string result = request.downloadHandler?.text; - if (!string.IsNullOrEmpty(result)) + if (attempt > 0) + yield return new WaitForSecondsRealtime(Mathf.Min(1f * attempt, 3f)); + + foreach (var host in sessionHosts) { - StoreApiResponse response = null; - try - { - response = JsonConvert.DeserializeObject(result); - } - catch + if (finalResponse != null) + break; + + foreach (var origin in originsToTry) { - response = null; - } + var requestURL = $"{host}/store/get"; + var request = PostJson(requestURL, new JObject + { + ["key"] = keyNormalized, + ["namespace"] = "" + }, origin); - callback(response); - } - else - { - callback(null); + if (!quiet) + Debug.Log($"Web3Auth authorizeSession POST {requestURL} origin={origin} attempt={attempt}"); + + yield return request.SendWebRequest(); + + if (request.result != UnityWebRequest.Result.Success) + { + if (!quiet) + { + Debug.LogError( + $"Web3Auth authorizeSession failed ({request.responseCode}): " + + $"{request.downloadHandler?.text ?? request.error}"); + } + continue; + } + + string result = request.downloadHandler?.text; + if (!quiet) + Debug.Log("Web3Auth authorizeSession response: " + result); + if (string.IsNullOrEmpty(result)) + continue; + + StoreApiResponse response = null; + try + { + response = JsonConvert.DeserializeObject(result); + } + catch (Exception ex) + { + if (!quiet) + Debug.LogError("Web3Auth authorizeSession deserialize failed: " + ex.Message + " raw=" + result); + continue; + } + + if (response != null && !string.IsNullOrEmpty(response.message)) + { + finalResponse = response; + break; + } + } } } - else - callback(null); + + if (finalResponse == null && !quiet) + Debug.LogError("Web3Auth authorizeSession: empty/null store response for all origin/host retries"); + + callback(finalResponse); } public IEnumerator logout(LogoutApiRequest logoutApiRequest, Action callback) { - WWWForm data = new WWWForm(); - data.AddField("key", logoutApiRequest.key); - data.AddField("data", logoutApiRequest.data); - data.AddField("signature", logoutApiRequest.signature); - data.AddField("timeout", logoutApiRequest.timeout.ToString()); + var request = PostJson($"{sessionHosts[0]}/store/set", new JObject + { + ["key"] = (logoutApiRequest.key ?? "").ToLowerInvariant(), + ["data"] = logoutApiRequest.data, + ["signature"] = logoutApiRequest.signature, + ["timeout"] = logoutApiRequest.timeout, + ["namespace"] = logoutApiRequest.sessionNamespace ?? "" + }); - var request = UnityWebRequest.Post($"{baseAddress}/store/set", data); yield return request.SendWebRequest(); if (request.result == UnityWebRequest.Result.Success) @@ -85,15 +193,35 @@ public IEnumerator logout(LogoutApiRequest logoutApiRequest, Action cal callback(null); } + private static string DescribeWebRequestFailure(UnityWebRequest request) + { + if (request == null) + return "unknown request failure"; + + if (request.responseCode == 0) + { + return "network/DNS error (responseCode=0). Check emulator/device internet connectivity. " + + $"result={request.result}, error={request.error}"; + } + + return $"({request.responseCode}): {request.downloadHandler?.text ?? request.error}"; + } + public IEnumerator createSession(LogoutApiRequest logoutApiRequest, Action callback) { - WWWForm data = new WWWForm(); - data.AddField("key", logoutApiRequest.key); - data.AddField("data", logoutApiRequest.data); - data.AddField("signature", logoutApiRequest.signature); - data.AddField("timeout", logoutApiRequest.timeout.ToString()); - // Debug.Log("key during create session =>" + logoutApiRequest.key); - var request = UnityWebRequest.Post($"{baseAddress}/store/set", data); + var body = new JObject + { + ["key"] = (logoutApiRequest.key ?? "").ToLowerInvariant(), + ["data"] = logoutApiRequest.data, + ["signature"] = logoutApiRequest.signature, + ["timeout"] = logoutApiRequest.timeout, + ["allowedOrigin"] = logoutApiRequest.allowedOrigin ?? "*", + ["namespace"] = logoutApiRequest.sessionNamespace ?? "" + }; + + var request = PostJson($"{sessionHosts[0]}/store/set", body, logoutApiRequest.allowedOrigin); + Debug.Log($"Web3Auth createSession store/set origin={logoutApiRequest.allowedOrigin} namespace={logoutApiRequest.sessionNamespace ?? ""}"); + yield return request.SendWebRequest(); if (request.result == UnityWebRequest.Result.Success) @@ -102,7 +230,10 @@ public IEnumerator createSession(LogoutApiRequest logoutApiRequest, Action(result)); } else + { + Debug.LogError("Web3Auth createSession failed " + DescribeWebRequestFailure(request)); callback(null); + } } public IEnumerator fetchProjectConfig(string project_id, string network, string build_env, Action callback) @@ -129,7 +260,7 @@ public IEnumerator fetchProjectConfig(string project_id, string network, string } else { - Debug.LogError($"Failed to fetch project config ({request.responseCode}): {request.downloadHandler?.text ?? request.error}\nURL: {requestURL}"); + Debug.LogError($"Failed to fetch project config {DescribeWebRequestFailure(request)}\nURL: {requestURL}"); callback(null); } } diff --git a/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs b/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs index 77f623b..03c36cc 100644 --- a/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs +++ b/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs @@ -77,7 +77,8 @@ public static string getPubKey(string sessionId) var key = new ECPrivateKeyParameters(new BigInteger(sessionId, 16), parameters); var q = new ECPublicKeyParameters("EC", domain.G.Multiply(key.D), parameters).Q; - return Hex.ToHexString(domain.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()).GetEncoded(false)); + // Uncompressed secp256k1 pubkey (04 || X || Y) + return Hex.ToHexString(domain.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()).GetEncoded(false)).ToLowerInvariant(); } catch (System.Exception ex) { UnityEngine.Debug.Log(ex); diff --git a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs index fd5bd87..4167487 100644 --- a/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs +++ b/Assets/Plugins/Web3AuthSDK/Samples/Web3AuthSample.cs @@ -93,18 +93,10 @@ void Start() {"CUSTOM_VERIFIER", loginConfigItem} } */ - authConnectionConfig = new List() - { - new AuthConnectionConfig() - { - authConnectionId = "web3auth-auth0-email-passwordless-sapphire-devnet", - authConnection = AuthConnection.CUSTOM, - clientId = "d84f6xvbdV75VTGmHiMWfZLeSPk8M07C" - } - }, + authConnectionConfig = null, clientId = "BPrPLO2tetqnI5UsOuuGK9SSmMGrRHi-y6LEtKp6PW5P1btBYqNkLFFtExK53PqOt-H9JszGhfQOq2FOGGNf-TE", authBuildEnv = BuildEnv.PRODUCTION, - redirectUrl = new Uri("torusapp://com.torus.Web3AuthUnity"), + redirectUrl = new Uri("torusapp://com.torus.Web3AuthUnity/auth"), localRedirectHost = "web3auth.localtest.me", web3AuthNetwork = Web3Auth.Network.SAPPHIRE_MAINNET, defaultChainId = "0x1", diff --git a/Assets/Plugins/Web3AuthSDK/Utils.cs b/Assets/Plugins/Web3AuthSDK/Utils.cs index 7cab77d..22e16b3 100644 --- a/Assets/Plugins/Web3AuthSDK/Utils.cs +++ b/Assets/Plugins/Web3AuthSDK/Utils.cs @@ -71,12 +71,15 @@ public static Dictionary ParseQuery(string text) Dictionary result = new Dictionary(); - if (parts.Count > 0) + foreach (var part in parts) { - result = parts.ToDictionary( - c => c.Split('=')[0], - c => Uri.UnescapeDataString(c.Split('=')[1]) - ); + int separator = part.IndexOf('='); + if (separator <= 0) + continue; + + string key = Uri.UnescapeDataString(part.Substring(0, separator)); + string value = Uri.UnescapeDataString(part.Substring(separator + 1)); + result[key] = value; } return result; diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index 1619e5c..87c7bd1 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -142,10 +142,20 @@ public async void setOptions(Web3AuthOptions web3AuthOptions) if (!isfetchConfigSuccess) { - throw new Exception("Failed to fetch project config. Please try again later."); + throw new Exception( + "Failed to fetch project config. If responseCode was 0, the emulator/device has no working internet/DNS. " + + "Check Wi‑Fi, cold-boot the AVD, or try a physical device."); } else { + // Restore existing session if present. Empty store is normal when logged out / expired. var redirectUrl = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.REDIRECT_URL); - authorizeSession("", redirectUrl); + if (string.IsNullOrEmpty(redirectUrl) && this.web3AuthOptions.redirectUrl != null) + redirectUrl = GetRedirectUrlString(this.web3AuthOptions.redirectUrl); +#if UNITY_EDITOR || UNITY_STANDALONE + var localHost = this.web3AuthOptions.localRedirectHost ?? Utils.LOCAL_REDIRECT_HOST; + if (!string.IsNullOrEmpty(localHost)) + redirectUrl = $"http://{localHost}:{Utils.LOCAL_REDIRECT_PORT}"; +#endif + authorizeSession("", redirectUrl, quietIfEmpty: true); JsonSerializerSettings settings = new JsonSerializerSettings { @@ -153,17 +163,17 @@ public async void setOptions(Web3AuthOptions web3AuthOptions) Formatting = Formatting.Indented }; + // Prefer OriginalString — System.Uri lowercases custom-scheme hosts. if (this.web3AuthOptions.redirectUrl != null) - this.initParams["redirectUrl"] = this.web3AuthOptions.redirectUrl; + this.initParams["redirectUrl"] = GetRedirectUrlString(this.web3AuthOptions.redirectUrl); if (this.web3AuthOptions.whiteLabel != null) this.initParams["whiteLabel"] = JsonConvert.SerializeObject(this.web3AuthOptions.whiteLabel, settings); - if (this.web3AuthOptions.authConnectionConfig != null && this.web3AuthOptions.authConnectionConfig.Count > 0) - this.initParams["authConnectionConfig"] = this.web3AuthOptions.authConnectionConfig; + SetAuthConnectionConfigInitParam(settings); if (this.web3AuthOptions.walletServicesConfig != null) - this.initParams["walletServicesConfig"] = this.web3AuthOptions.walletServicesConfig; + this.initParams["walletServicesConfig"] = JObject.FromObject(this.web3AuthOptions.walletServicesConfig, JsonSerializer.Create(settings)); if (this.web3AuthOptions.authBuildEnv != null) this.initParams["authBuildEnv"] = this.web3AuthOptions.authBuildEnv.ToString().ToLower(); @@ -186,9 +196,87 @@ public async void setOptions(Web3AuthOptions web3AuthOptions) private void onDeepLinkActivated(string url) { +#if UNITY_ANDROID && !UNITY_EDITOR + if (!string.IsNullOrEmpty(url) && url == lastProcessedAndroidDeepLink) + return; + if (!string.IsNullOrEmpty(url)) + lastProcessedAndroidDeepLink = url; +#endif this.setResultUrl(new Uri(url)); } + private static string GetRedirectUrlString(Uri redirectUri) + { + if (redirectUri == null) + return null; + if (!string.IsNullOrEmpty(redirectUri.OriginalString)) + return redirectUri.OriginalString.Split('#')[0].Split('?')[0].TrimEnd('/'); + return redirectUri.AbsoluteUri.Split('#')[0].Split('?')[0].TrimEnd('/'); + } + +#if UNITY_ANDROID && !UNITY_EDITOR + private string lastProcessedAndroidDeepLink; + + private void OnApplicationFocus(bool hasFocus) + { + if (hasFocus) + TryConsumeAndroidDeepLink(); + } + + private void OnApplicationPause(bool pauseStatus) + { + if (!pauseStatus) + TryConsumeAndroidDeepLink(); + } + + private void TryConsumeAndroidDeepLink() + { + try + { + string url = null; + using (var activityClass = new AndroidJavaClass("com.web3auth.unity.android.Web3AuthActivity")) + { + url = activityClass.CallStatic("consumePendingDeepLinkUrl"); + } + + if (string.IsNullOrEmpty(url)) + { + using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) + using (var activity = unityPlayer.GetStatic("currentActivity")) + using (var intent = activity.Call("getIntent")) + { + if (intent == null) + return; + + using (var data = intent.Call("getData")) + { + if (data == null) + return; + url = data.Call("toString"); + if (string.IsNullOrEmpty(url) || !url.StartsWith("torusapp://", StringComparison.OrdinalIgnoreCase)) + return; + intent.Call("setData", null as AndroidJavaObject); + } + } + } + + if (string.IsNullOrEmpty(url)) + return; + + if (url == lastProcessedAndroidDeepLink) + return; + + lastProcessedAndroidDeepLink = url; + Debug.Log("Web3Auth Android deep link: " + url); + onDeepLinkActivated(url); + } + catch (Exception ex) + { + Debug.LogWarning("TryConsumeAndroidDeepLink failed: " + ex.Message); + } + } +#endif + #if UNITY_STANDALONE || UNITY_EDITOR private void StopLocalWebserver() { @@ -349,6 +437,9 @@ private async void processRequest(string path, LoginParams loginParams = null) { redirectUrl = redirectUrl.TrimEnd('/'); } + // Prefer casing from Web3AuthOptions when available. + if (web3AuthOptions?.redirectUrl != null) + redirectUrl = GetRedirectUrlString(web3AuthOptions.redirectUrl) ?? redirectUrl; #if UNITY_STANDALONE || UNITY_EDITOR this.initParams["redirectUrl"] = StartLocalWebserver(); @@ -357,12 +448,9 @@ private async void processRequest(string path, LoginParams loginParams = null) this.initParams["redirectUrl"] = Utils.GetCurrentURL(); #endif - //loginParams.redirectUrl = loginParams.redirectUrl ?? new Uri(this.initParams["redirectUrl"].ToString()); - //Debug.Log("loginParams.redirectUrl: =>" + loginParams.redirectUrl); var sessionId = KeyStoreManagerUtils.generateRandomSessionKey(); if(path == "manage_mfa") { loginParams.dappUrl = this.initParams["redirectUrl"].ToString(); - //loginParams.redirectUrl = new Uri(this.initParams["dashboardUrl"].ToString()); this.initParams["redirectUrl"] = new Uri(this.initParams["dashboardUrl"].ToString()); var loginIdObject = new Dictionary { @@ -525,24 +613,55 @@ public async void showWalletUI(string path = "wallet") public void setResultUrl(Uri uri) { + if (uri == null) + { + Debug.LogWarning("Web3Auth setResultUrl: uri is null"); + return; + } + + Debug.Log("Web3Auth setResultUrl: " + uri); + string hash = uri.Fragment; #if !UNITY_EDITOR && UNITY_WEBGL if (hash == null || hash.Length == 0) return; #else - if (hash == null) - throw new UserCancelledException(); + // Custom Tabs may put session data in query instead of fragment. + if (string.IsNullOrEmpty(hash) || hash == "#") + { + if (!string.IsNullOrEmpty(uri.Query) && uri.Query.Length > 1) + { + hash = uri.Query; + } + else + { + Debug.LogError("Web3Auth setResultUrl: missing fragment/query in redirect URL: " + uri); + return; + } + } #endif - hash = hash.Remove(0, 1); + if (hash.StartsWith("#") || hash.StartsWith("?")) + hash = hash.Substring(1); Dictionary queryParameters = Utils.ParseQuery(uri.Query); if (queryParameters.Keys.Contains("error")) throw new UnKnownException(queryParameters["error"]); - string newUriString = "http://" + uri.Host + "?" + hash; - Uri newUri = new Uri(newUriString); - string b64Params = getQueryParamValue(newUri, "b64Params"); + Dictionary hashParameters = Utils.ParseQuery("?" + hash); + string b64Params = null; + if (hashParameters != null && hashParameters.ContainsKey("b64Params")) + b64Params = hashParameters["b64Params"]; + if (string.IsNullOrEmpty(b64Params)) + b64Params = getQueryParamValue(uri, "b64Params"); + string decodedString = decodeBase64Params(b64Params); + if (string.IsNullOrEmpty(decodedString)) + { + Debug.LogError("Web3Auth setResultUrl: failed to decode b64Params from: " + uri); + return; + } + Debug.Log("Web3Auth setResultUrl decoded: " + decodedString); + if (decodedString.Contains("actionType")) { RedirectResponse response = JsonUtility.FromJson(decodedString); @@ -571,7 +690,7 @@ public void setResultUrl(Uri uri) } catch (Exception e) { - Debug.Log("Failed to decode JSON: " + e.Message); + Debug.LogError("Failed to decode session JSON: " + e.Message + " raw=" + decodedString); } if (sessionResponse == null || string.IsNullOrEmpty(sessionResponse.sessionId)) { @@ -586,11 +705,49 @@ public void setResultUrl(Uri uri) $"length={sessionResponse.sessionId?.Length}, decoded={decodedString}"); return; } - this.Enqueue(() => KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.SESSION_ID, sessionId)); - this.Enqueue(() => KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.REDIRECT_URL, redirectUrl)); - //call authorize session API - this.Enqueue(() => authorizeSession(sessionId, redirectUrl)); + string resolvedRedirectUrl = redirectUrl; + if (string.IsNullOrEmpty(resolvedRedirectUrl) && initParams != null && initParams.ContainsKey("redirectUrl") && initParams["redirectUrl"] != null) + resolvedRedirectUrl = initParams["redirectUrl"].ToString(); + if (string.IsNullOrEmpty(resolvedRedirectUrl) && web3AuthOptions?.redirectUrl != null) + resolvedRedirectUrl = GetRedirectUrlString(web3AuthOptions.redirectUrl); + +#if UNITY_EDITOR || UNITY_STANDALONE + // Editor uses local redirect; auth stores that origin. + if (!string.IsNullOrEmpty(this.redirectUrl) && + (this.redirectUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + this.redirectUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) + { + resolvedRedirectUrl = this.redirectUrl.Replace("/complete/", "").TrimEnd('/'); + } + else if (initParams != null && initParams.ContainsKey("redirectUrl") && initParams["redirectUrl"] != null) + { + var initRedirect = initParams["redirectUrl"].ToString(); + if (!string.IsNullOrEmpty(initRedirect) && + (initRedirect.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + initRedirect.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) + { + resolvedRedirectUrl = initRedirect.Replace("/complete/", "").TrimEnd('/'); + } + } +#else + if (!string.IsNullOrEmpty(resolvedRedirectUrl) && web3AuthOptions?.redirectUrl != null) + { + var preferred = GetRedirectUrlString(web3AuthOptions.redirectUrl); + if (!string.IsNullOrEmpty(preferred)) + resolvedRedirectUrl = preferred; + } +#endif + + Debug.Log("Web3Auth setResultUrl authorizing sessionId length=" + sessionId.Length + " redirect=" + resolvedRedirectUrl); + + + this.Enqueue(() => + { + KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.SESSION_ID, sessionId); + KeyStoreManagerUtils.savePreferenceData(KeyStoreManagerUtils.REDIRECT_URL, resolvedRedirectUrl); + authorizeSession(sessionId, resolvedRedirectUrl); + }); #if !UNITY_EDITOR && UNITY_WEBGL if (this.web3AuthResponse != null) @@ -871,7 +1028,7 @@ static ShareMetadata parseShareMetadataFromStoreMessage(string message) return null; } - private void authorizeSession(string newSessionId, string origin) + private void authorizeSession(string newSessionId, string origin, bool quietIfEmpty = false) { string sessionId = ""; if (string.IsNullOrEmpty(newSessionId)) @@ -901,6 +1058,8 @@ private void authorizeSession(string newSessionId, string origin) } StartCoroutine(Web3AuthApi.getInstance().authorizeSession(pubKey, origin, (response => { + try + { if (response != null && !string.IsNullOrEmpty(response.message)) { var shareMetadata = parseShareMetadataFromStoreMessage(response.message); @@ -952,87 +1111,169 @@ private void authorizeSession(string newSessionId, string origin) ); } - if (string.IsNullOrEmpty(this.web3AuthResponse.privateKey) || string.IsNullOrEmpty(this.web3AuthResponse.privateKey.Trim('0'))) + bool hasKey = + !string.IsNullOrEmpty(this.web3AuthResponse.privateKey) && + !string.IsNullOrEmpty(this.web3AuthResponse.privateKey.Trim('0')); + bool hasCoreKitKey = + !string.IsNullOrEmpty(this.web3AuthResponse.coreKitKey) && + !string.IsNullOrEmpty(this.web3AuthResponse.coreKitKey.Trim('0')); + bool hasUser = + this.web3AuthResponse.userInfo != null && + (!string.IsNullOrEmpty(this.web3AuthResponse.userInfo.email) || + !string.IsNullOrEmpty(this.web3AuthResponse.userInfo.name) || + !string.IsNullOrEmpty(this.web3AuthResponse.userInfo.userId)); + + if (!hasKey && !hasCoreKitKey && !hasUser) + { + Debug.LogError("Web3Auth authorizeSession: response had no private key/userInfo. Invoking onLogout. raw=" + tempJson); this.Enqueue(() => this.onLogout?.Invoke()); + } else { + Debug.Log("Web3Auth authorizeSession success, invoking onLogin"); this.Enqueue(() => this.onLogin?.Invoke(this.web3AuthResponse)); this.Enqueue(() => this.onMFASetup?.Invoke(true)); } } + else + { + Debug.LogError("Web3Auth authorizeSession: web3AuthResponse was null after decrypt"); + } } + else + { + if (quietIfEmpty) + { + Debug.Log("Web3Auth authorizeSession: no active session to restore"); + KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.SESSION_ID); + } + else + { + Debug.LogError("Web3Auth authorizeSession: empty/null store response for session authorize"); + } + } + } + catch (Exception ex) + { + Debug.LogError("Web3Auth authorizeSession callback failed: " + ex); + } + + }), quiet: quietIfEmpty)); + } + } + + private string resolveSessionRedirectUrl() + { + var redirectUrl = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.REDIRECT_URL); + if (string.IsNullOrEmpty(redirectUrl) && web3AuthOptions?.redirectUrl != null) + redirectUrl = GetRedirectUrlString(web3AuthOptions.redirectUrl); +#if UNITY_EDITOR || UNITY_STANDALONE + if (!string.IsNullOrEmpty(this.redirectUrl) && + (this.redirectUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + this.redirectUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) + { + redirectUrl = this.redirectUrl.Replace("/complete/", "").TrimEnd('/'); + } + else if (!string.IsNullOrEmpty(redirectUrl) && redirectUrl.StartsWith("torusapp://", StringComparison.OrdinalIgnoreCase)) + { + var localHost = web3AuthOptions?.localRedirectHost ?? Utils.LOCAL_REDIRECT_HOST; + redirectUrl = $"http://{localHost}:{Utils.LOCAL_REDIRECT_PORT}"; + } +#endif + return redirectUrl; + } - }))); + private void clearLocalSessionAndNotifyLogout() + { + try + { + KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.SESSION_ID); + KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.REDIRECT_URL); + if (web3AuthOptions?.authConnectionConfig != null) + KeyStoreManagerUtils.deletePreferencesData(web3AuthOptions.authConnectionConfig?.FirstOrDefault()?.authConnectionId); + web3AuthResponse = null; } + catch (Exception ex) + { + Debug.LogError("Failed to delete session data: " + ex.Message); + } + this.Enqueue(() => this.onLogout?.Invoke()); } private void sessionTimeOutAPI() { string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); - string redirectUrl = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.REDIRECT_URL); - if (!string.IsNullOrEmpty(sessionId)) + string redirectUrl = resolveSessionRedirectUrl(); + + if (string.IsNullOrEmpty(sessionId)) { - var pubKey = KeyStoreManagerUtils.getPubKey(sessionId); - StartCoroutine(Web3AuthApi.getInstance().authorizeSession(pubKey, redirectUrl, (response => - { - if (response != null && !string.IsNullOrEmpty(response.message)) - { - var shareMetadata = parseShareMetadataFromStoreMessage(response.message); - if (shareMetadata == null || string.IsNullOrEmpty(shareMetadata.ephemPublicKey) || - string.IsNullOrEmpty(shareMetadata.iv) || string.IsNullOrEmpty(shareMetadata.ciphertext) || - string.IsNullOrEmpty(shareMetadata.mac)) - { - return; - } + clearLocalSessionAndNotifyLogout(); + return; + } - var aes256cbc = new AES256CBC( - sessionId, - shareMetadata.ephemPublicKey, - shareMetadata.iv - ); + sessionId = KeyStoreManagerUtils.normalizeSessionId(sessionId); + var pubKey = KeyStoreManagerUtils.getPubKey(sessionId); + if (string.IsNullOrEmpty(pubKey)) + { + clearLocalSessionAndNotifyLogout(); + return; + } - var encryptedData = aes256cbc.encrypt(Encoding.UTF8.GetBytes("")); - var encryptedMetadata = new ShareMetadata() + StartCoroutine(Web3AuthApi.getInstance().authorizeSession(pubKey, redirectUrl, (response => + { + if (response != null && !string.IsNullOrEmpty(response.message)) + { + var shareMetadata = parseShareMetadataFromStoreMessage(response.message); + if (shareMetadata != null && + !string.IsNullOrEmpty(shareMetadata.ephemPublicKey) && + !string.IsNullOrEmpty(shareMetadata.iv) && + !string.IsNullOrEmpty(shareMetadata.ciphertext) && + !string.IsNullOrEmpty(shareMetadata.mac)) + { + try { - iv = shareMetadata.iv, - ephemPublicKey = shareMetadata.ephemPublicKey, - ciphertext = KeyStoreManagerUtils.convertByteToHexadecimal(encryptedData), - mac = shareMetadata.mac - }; - var jsonData = JsonConvert.SerializeObject(encryptedMetadata); - - StartCoroutine(Web3AuthApi.getInstance().logout( - new LogoutApiRequest() - { - key = KeyStoreManagerUtils.getPubKey(sessionId), - data = jsonData, - signature = KeyStoreManagerUtils.getECDSASignature( - sessionId, - jsonData - ), - timeout = 1 - }, result => + var aes256cbc = new AES256CBC( + sessionId, + shareMetadata.ephemPublicKey, + shareMetadata.iv + ); + + var encryptedData = aes256cbc.encrypt(Encoding.UTF8.GetBytes("")); + var encryptedMetadata = new ShareMetadata() { - if (result != null) + iv = shareMetadata.iv, + ephemPublicKey = shareMetadata.ephemPublicKey, + ciphertext = KeyStoreManagerUtils.convertByteToHexadecimal(encryptedData), + mac = shareMetadata.mac + }; + var jsonData = JsonConvert.SerializeObject(encryptedMetadata); + + StartCoroutine(Web3AuthApi.getInstance().logout( + new LogoutApiRequest() { - try - { - KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.SESSION_ID); - if (web3AuthOptions.authConnectionConfig != null) - KeyStoreManagerUtils.deletePreferencesData(web3AuthOptions.authConnectionConfig?.FirstOrDefault()?.authConnectionId); - - this.Enqueue(() => this.onLogout?.Invoke()); - } - catch (Exception ex) - { - Debug.LogError("Failed to delete session data: " + ex.Message); - } + key = KeyStoreManagerUtils.getPubKey(sessionId), + data = jsonData, + signature = KeyStoreManagerUtils.getECDSASignature( + sessionId, + jsonData + ), + timeout = 1 + }, result => + { + clearLocalSessionAndNotifyLogout(); } - } - )); + )); + return; + } + catch (Exception ex) + { + Debug.LogWarning("Web3Auth logout remote invalidate failed: " + ex.Message); + } } - }))); - } + } + + clearLocalSessionAndNotifyLogout(); + }), quiet: true)); } private async Task createSession(string data, long sessionTime, string allowedOrigin, string sessionId) @@ -1090,6 +1331,21 @@ private async Task createSession(string data, long sessionTime, string a return await createSessionResponse.Task; } + private void SetAuthConnectionConfigInitParam(JsonSerializerSettings settings = null) + { + settings ??= new JsonSerializerSettings + { + Converters = new List { new StringEnumConverter() }, + NullValueHandling = NullValueHandling.Ignore + }; + + var config = this.web3AuthOptions?.authConnectionConfig; + if (config != null && config.Count > 0) + this.initParams["authConnectionConfig"] = JArray.FromObject(config, JsonSerializer.Create(settings)); + else + this.initParams["authConnectionConfig"] = new JArray(); + } + private async Task fetchProjectConfig() { TaskCompletionSource fetchProjectConfigResponse = new TaskCompletionSource(); @@ -1127,7 +1383,14 @@ private async Task fetchProjectConfig() this.initParams["originData"] = JsonConvert.SerializeObject(this.web3AuthOptions.originData, settings); if (this.web3AuthOptions.walletServicesConfig != null) - this.initParams["walletServicesConfig"] = this.web3AuthOptions.walletServicesConfig; + this.initParams["walletServicesConfig"] = JObject.FromObject(this.web3AuthOptions.walletServicesConfig, JsonSerializer.Create(settings)); + + if ((this.web3AuthOptions.authConnectionConfig == null || this.web3AuthOptions.authConnectionConfig.Count == 0) + && response.embeddedWalletAuth != null && response.embeddedWalletAuth.Count > 0) + { + this.web3AuthOptions.authConnectionConfig = response.embeddedWalletAuth; + } + SetAuthConnectionConfigInitParam(settings); fetchProjectConfigResponse.SetResult(true); }