diff --git a/src/Packages/Passport/Editor/FileHelpers.cs b/src/Packages/Passport/Editor/FileHelpers.cs index 7065ab96..e58c9c37 100644 --- a/src/Packages/Passport/Editor/FileHelpers.cs +++ b/src/Packages/Passport/Editor/FileHelpers.cs @@ -5,55 +5,43 @@ namespace Immutable.Passport.Editor public static class FileHelpers { /// - /// Copies everything except .meta files in the source directory to the destination directory - /// + /// Copies everything except .meta files in the source directory to the destination directory + /// public static void CopyDirectory(string sourcePath, string destinationPath) { // Checks if the destination directory exists - DirectoryInfo destinationDir = new DirectoryInfo(destinationPath); + var destinationDir = new DirectoryInfo(destinationPath); if (!destinationDir.Exists) - { Directory.CreateDirectory(destinationPath); - } else - { // If the directory exists, clear it ClearDirectory(destinationPath); - } var dir = new DirectoryInfo(sourcePath); - DirectoryInfo[] dirs = dir.GetDirectories(); - foreach (FileInfo file in dir.GetFiles()) - { + var dirs = dir.GetDirectories(); + foreach (var file in dir.GetFiles()) if (!file.Name.EndsWith(".meta")) { - string targetFilePath = Path.Combine(destinationPath, file.Name); + var targetFilePath = Path.Combine(destinationPath, file.Name); file.CopyTo(targetFilePath, true); } - } - foreach (DirectoryInfo subDir in dirs) + foreach (var subDir in dirs) { - string newdestinationPath = Path.Combine(destinationPath, subDir.Name); + var newdestinationPath = Path.Combine(destinationPath, subDir.Name); CopyDirectory(subDir.FullName, newdestinationPath); } } /// - /// Deletes everything in the given directory - /// + /// Deletes everything in the given directory + /// public static void ClearDirectory(string directoryPath) { - DirectoryInfo directory = new DirectoryInfo(directoryPath); - foreach (FileInfo fileInfo in directory.EnumerateFiles()) - { - fileInfo.Delete(); - } + var directory = new DirectoryInfo(directoryPath); + foreach (var fileInfo in directory.EnumerateFiles()) fileInfo.Delete(); - foreach (DirectoryInfo directoryInfo in directory.EnumerateDirectories()) - { - directoryInfo.Delete(true); - } + foreach (var directoryInfo in directory.EnumerateDirectories()) directoryInfo.Delete(true); } } } \ No newline at end of file diff --git a/src/Packages/Passport/Editor/PassportAndroidProcessor.cs b/src/Packages/Passport/Editor/PassportAndroidProcessor.cs index c27195d6..ce110bb1 100644 --- a/src/Packages/Passport/Editor/PassportAndroidProcessor.cs +++ b/src/Packages/Passport/Editor/PassportAndroidProcessor.cs @@ -2,21 +2,21 @@ using System; using System.IO; -using UnityEditor; using UnityEditor.Android; using UnityEngine; namespace Immutable.Passport.Editor { - class PassportAndroidProcessor : IPostGenerateGradleAndroidProject + internal class PassportAndroidProcessor : IPostGenerateGradleAndroidProject { - public int callbackOrder { get { return 0; } } + public int callbackOrder => 0; + public void OnPostGenerateGradleAndroidProject(string path) { Debug.Log("MyCustomBuildProcessor.OnPostGenerateGradleAndroidProject at path " + path); // Find the location of the files - string passportWebFilesDir = Path.GetFullPath("Packages/com.immutable.passport/Runtime/Resources"); + var passportWebFilesDir = Path.GetFullPath("Packages/com.immutable.passport/Runtime/Resources"); if (!Directory.Exists(passportWebFilesDir)) { Debug.LogError("The Passport files directory doesn't exist!"); @@ -24,7 +24,7 @@ public void OnPostGenerateGradleAndroidProject(string path) } FileHelpers.CopyDirectory(passportWebFilesDir, $"{path}/src/main/assets/ImmutableSDK/Runtime/Passport"); - Debug.Log($"Sucessfully copied Passport files"); + Debug.Log("Sucessfully copied Passport files"); AddUseAndroidX(path); } diff --git a/src/Packages/Passport/Editor/PassportEditor.asmdef b/src/Packages/Passport/Editor/PassportEditor.asmdef index 4d5cf619..076348e7 100644 --- a/src/Packages/Passport/Editor/PassportEditor.asmdef +++ b/src/Packages/Passport/Editor/PassportEditor.asmdef @@ -1,18 +1,18 @@ { - "name": "Immutable.Passport.Editor", - "rootNamespace": "Immutable.Passport.Editor", - "references": [], - "includePlatforms": [ - "Editor", - "macOSStandalone", - "WindowsStandalone64" - ], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "Immutable.Passport.Editor", + "rootNamespace": "Immutable.Passport.Editor", + "references": [], + "includePlatforms": [ + "Editor", + "macOSStandalone", + "WindowsStandalone64" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/src/Packages/Passport/Editor/PassportPostprocess.cs b/src/Packages/Passport/Editor/PassportPostprocess.cs index 44df2365..42b985aa 100644 --- a/src/Packages/Passport/Editor/PassportPostprocess.cs +++ b/src/Packages/Passport/Editor/PassportPostprocess.cs @@ -1,11 +1,7 @@ #if UNITY_EDITOR -using System.IO; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Text; -using System.Xml; using System; +using System.IO; using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; @@ -19,19 +15,19 @@ internal class PassportPostprocess : IPostprocessBuildWithReport public void OnPostprocessBuild(BuildReport report) { - Debug.Log($"Passport post-processing..."); + Debug.Log("Passport post-processing..."); if (report.summary.result is BuildResult.Failed || report.summary.result is BuildResult.Cancelled) return; - BuildTarget buildTarget = report.summary.platform; + var buildTarget = report.summary.platform; - string buildFullOutputPath = report.summary.outputPath; - string buildAppName = Path.GetFileNameWithoutExtension(buildFullOutputPath); - string buildOutputPath = Path.GetDirectoryName(buildFullOutputPath); + var buildFullOutputPath = report.summary.outputPath; + var buildAppName = Path.GetFileNameWithoutExtension(buildFullOutputPath); + var buildOutputPath = Path.GetDirectoryName(buildFullOutputPath); // Get the build's data folder - string buildDataPath = Path.GetFullPath($"{buildOutputPath}/{buildAppName}_Data/"); + var buildDataPath = Path.GetFullPath($"{buildOutputPath}/{buildAppName}_Data/"); if (buildTarget == BuildTarget.StandaloneOSX) { buildDataPath = @@ -41,7 +37,8 @@ public void OnPostprocessBuild(BuildReport report) // but there is no way to check that so try another path if (!Directory.Exists(buildDataPath)) { - buildDataPath = Path.GetFullPath($"{buildFullOutputPath}/{Application.productName}/Resources/Data/"); + buildDataPath = + Path.GetFullPath($"{buildFullOutputPath}/{Application.productName}/Resources/Data/"); Debug.Log($"StandaloneOSX buildDataPath 2: {buildDataPath}"); } } @@ -58,15 +55,16 @@ public void OnPostprocessBuild(BuildReport report) // Copy passport files to data directory for these target // For other platforms, check the pre process file - if (buildTarget == BuildTarget.StandaloneWindows64 || buildTarget == BuildTarget.StandaloneOSX || buildTarget == BuildTarget.iOS) + if (buildTarget == BuildTarget.StandaloneWindows64 || buildTarget == BuildTarget.StandaloneOSX || + buildTarget == BuildTarget.iOS) { CopyIntoDataDir(buildDataPath); - Debug.Log($"Successfully copied Passport files"); + Debug.Log("Successfully copied Passport files"); } if (buildTarget == BuildTarget.iOS) { - string projPath = $"{buildOutputPath}/{buildAppName}" + "/Unity-iPhone.xcodeproj/project.pbxproj"; + var projPath = $"{buildOutputPath}/{buildAppName}" + "/Unity-iPhone.xcodeproj/project.pbxproj"; var type = Type.GetType("UnityEditor.iOS.Xcode.PBXProject, UnityEditor.iOS.Extensions.Xcode"); if (type == null) @@ -104,16 +102,14 @@ public void OnPostprocessBuild(BuildReport report) } var cflags = ""; - if (EditorUserBuildSettings.development) - { - cflags += " -DUNITYWEBVIEW_DEVELOPMENT"; - } + if (EditorUserBuildSettings.development) cflags += " -DUNITYWEBVIEW_DEVELOPMENT"; cflags = cflags.Trim(); if (!string.IsNullOrEmpty(cflags)) { - var method = type.GetMethod("AddBuildProperty", new Type[] { typeof(string), typeof(string), typeof(string) }); + var method = type.GetMethod("AddBuildProperty", + new[] { typeof(string), typeof(string), typeof(string) }); method.Invoke(proj, new object[] { target, "OTHER_CFLAGS", cflags }); } @@ -132,25 +128,22 @@ private void CopyIntoDataDir(string buildDataPath) // Check that the data folder exists if (!Directory.Exists(buildDataPath)) { - string errorMessage = "Failed to get the build's data folder. Make sure your build is the same name as your product name (In your project settings)."; + var errorMessage = + "Failed to get the build's data folder. Make sure your build is the same name as your product name (In your project settings)."; Debug.LogError(errorMessage); throw new Exception(errorMessage); } // Passport folder in the data folder - string buildPassportPath = $"{buildDataPath}/ImmutableSDK/Runtime/Passport/"; + var buildPassportPath = $"{buildDataPath}/ImmutableSDK/Runtime/Passport/"; // Make sure it exists - DirectoryInfo buildPassportInfo = new DirectoryInfo(buildPassportPath); + var buildPassportInfo = new DirectoryInfo(buildPassportPath); if (!buildPassportInfo.Exists) - { Directory.CreateDirectory(buildPassportPath); - } else - { // If the directory exists, clear it FileHelpers.ClearDirectory(buildPassportPath); - } buildPassportPath = Path.GetFullPath(buildPassportPath); @@ -162,28 +155,24 @@ private void CopyFilesTo(string destinationPath) Debug.Log("Copying Passport files..."); // Find the location of the files - string passportWebFilesDir = Path.GetFullPath("Packages/com.immutable.passport/Runtime/Resources"); + var passportWebFilesDir = Path.GetFullPath("Packages/com.immutable.passport/Runtime/Resources"); if (!Directory.Exists(passportWebFilesDir)) { Debug.LogError("The Passport files directory doesn't exist!"); return; } - foreach (string dir in Directory.GetDirectories(passportWebFilesDir, "*", SearchOption.AllDirectories)) + foreach (var dir in Directory.GetDirectories(passportWebFilesDir, "*", SearchOption.AllDirectories)) { - string dirToCreate = dir.Replace(passportWebFilesDir, destinationPath); + var dirToCreate = dir.Replace(passportWebFilesDir, destinationPath); Directory.CreateDirectory(dirToCreate); } - foreach (string newPath in Directory.GetFiles(passportWebFilesDir, "*.*", SearchOption.AllDirectories)) - { + foreach (var newPath in Directory.GetFiles(passportWebFilesDir, "*.*", SearchOption.AllDirectories)) if (!newPath.EndsWith(".meta")) - { File.Copy(newPath, newPath.Replace(passportWebFilesDir, destinationPath), true); - } - } } } -} - +} + #endif \ No newline at end of file diff --git a/src/Packages/Passport/LICENSE.md b/src/Packages/Passport/LICENSE.md index d9a10c0d..f47af0ac 100644 --- a/src/Packages/Passport/LICENSE.md +++ b/src/Packages/Passport/LICENSE.md @@ -2,175 +2,175 @@ Version 2.0, January 2004 http://www.apache.org/licenses/ - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/src/Packages/Passport/README.md b/src/Packages/Passport/README.md index 39eb07e8..4807e739 100644 --- a/src/Packages/Passport/README.md +++ b/src/Packages/Passport/README.md @@ -21,27 +21,42 @@ The Immutable SDK for Unity helps you integrate your game with Immutable Passpor Thank you for your interest in contributing to our project! Here's a quick guide on how you can get started: -1. **Fork this Repository**: Fork the repository to your GitHub account by clicking the "Fork" button at the top right of the repository page. -2. **Create a Branch**: Once you've forked the repository, create a new branch in your forked repository where you'll be making your changes. Branch naming convention is enforced [according to patterns here](https://github.com/deepakputhraya/action-branch-name). -3. **Make Changes**: Make the necessary changes in your branch. Ensure that your changes are clear, well-documented, and aligned with the project's guidelines. -4. **Commit Changes**: Commit your changes with clear and descriptive messages following [commit message pattern here](https://github.com/conventional-changelog/commitlint?tab=readme-ov-file#what-is-commitlint). It follows [Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0/#specification), which helps maintain a consistent and informative commit history. Read [here](https://www.conventionalcommits.org/en/v1.0.0/#why-use-conventional-commits) to learn more about the benefits of Conventional Commits. -5. **Create a Pull Request (PR)**: After you've made and committed your changes, create a PR against the original repository. Provide a clear description of the changes you've made in the PR. -6. **Example Contribution**: Refer to [this contribution](https://github.com/immutable/unity-immutable-sdk/pull/182) as an example. +1. **Fork this Repository**: Fork the repository to your GitHub account by clicking the "Fork" button at the top right + of the repository page. +2. **Create a Branch**: Once you've forked the repository, create a new branch in your forked repository where you'll be + making your changes. Branch naming convention is + enforced [according to patterns here](https://github.com/deepakputhraya/action-branch-name). +3. **Make Changes**: Make the necessary changes in your branch. Ensure that your changes are clear, well-documented, and + aligned with the project's guidelines. +4. **Commit Changes**: Commit your changes with clear and descriptive messages + following [commit message pattern here](https://github.com/conventional-changelog/commitlint?tab=readme-ov-file#what-is-commitlint). + It follows [Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0/#specification), which + helps maintain a consistent and informative commit history. + Read [here](https://www.conventionalcommits.org/en/v1.0.0/#why-use-conventional-commits) to learn more about the + benefits of Conventional Commits. +5. **Create a Pull Request (PR)**: After you've made and committed your changes, create a PR against the original + repository. Provide a clear description of the changes you've made in the PR. +6. **Example Contribution**: Refer to [this contribution](https://github.com/immutable/unity-immutable-sdk/pull/182) as + an example. ## Getting Help -Immutable X is open to all to build on, with no approvals required. If you want to talk to us to learn more, or apply for developer grants, click below: +Immutable X is open to all to build on, with no approvals required. If you want to talk to us to learn more, or apply +for developer grants, click below: [Contact us](https://www.immutable.com/contact) ### Project Support -To get help from other developers, discuss ideas, and stay up-to-date on what's happening, become a part of our community on Discord. +To get help from other developers, discuss ideas, and stay up-to-date on what's happening, become a part of our +community on Discord. [Join us on Discord](https://discord.gg/TkVumkJ9D6) #### Still need help? -You can also apply for marketing support for your project. Or, if you need help with an issue related to what you're building with Immutable X, click below to submit an issue. Select _I have a question_ or _issue related to building on Immutable X_ as your issue type. +You can also apply for marketing support for your project. Or, if you need help with an issue related to what you're +building with Immutable X, click below to submit an issue. Select _I have a question_ or _issue related to building on +Immutable X_ as your issue type. [Contact support](https://support.immutable.com/hc/en-us/requests/new) diff --git a/src/Packages/Passport/Runtime/Resources/index.html b/src/Packages/Passport/Runtime/Resources/index.html index fc8b5389..11ca6d54 100644 --- a/src/Packages/Passport/Runtime/Resources/index.html +++ b/src/Packages/Passport/Runtime/Resources/index.html @@ -1,4 +1,601 @@ -GameSDK Bridge

Bridge Running

\ No newline at end of file +)[]`, e4 = (e, t) => { + let r = [], i = new f.ethers.utils.Interface(d.walletContracts.mainModule.abi); + for (let n of t) { + let t = (0, f.ethers).utils.arrayify(n.data || "0x"); + if (n.to === e && (0, f.ethers).utils.hexlify(t.slice(0, 4)) === e5) { + let e = t.slice(4), i = (0, f.ethers).utils.defaultAbiCoder.decode([e8], e)[0]; + r.push(...e4(n.to, i.map(e => c({}, e, {to: e.target})))) + } else try { + let n = i.decodeFunctionData("execute", t)[0], a = e4(e, n.map(e => c({}, e, {to: e.target}))); + r.push(...a) + } catch (e) { + r.push(n) + } + } + return r + }; + var e7 = Object.freeze({ + __proto__: null, + MetaTransactionsType: eZ, + intendTransactionBundle: function (e, t, r, i) { + return c({}, e, {chainId: r, intent: {id: i, wallet: t}}) + }, + intendedTransactionID: function (e) { + return (0, f.ethers).utils.keccak256((0, f.ethers).utils.defaultAbiCoder.encode(["address", "uint256", "bytes32"], [e.intent.wallet, e.chainId, e.intent.id])) + }, + unpackMetaTransactionsData: function (e) { + let t = (0, f.ethers).utils.defaultAbiCoder.decode(["uint256", eZ], e); + if (2 !== t.length || !t[0] || !t[1]) throw Error("Invalid meta transaction data"); + return [t[0], t[1]] + }, + packMetaTransactionsData: eX, + digestOfTransactions: e$, + subdigestOfTransactions: function (e, t, r, i) { + return l({address: e, chainId: t, digest: e$(r, i)}) + }, + subdigestOfGuestModuleTransactions: function (e, t, r) { + return l({ + address: e, + chainId: t, + digest: (0, f.ethers).utils.keccak256((0, f.ethers).utils.defaultAbiCoder.encode(["string", eZ], ["guest:", e2(r)])) + }) + }, + toSequenceTransactions: eY, + toSequenceTransaction: eQ, + isSequenceTransaction: e0, + hasSequenceTransactions: e1, + sequenceTxAbiEncode: e2, + fromTxAbiEncode: function (e) { + return e.map(e => ({ + delegateCall: e.delegateCall, + revertOnError: e.revertOnError, + gasLimit: e.gasLimit, + to: e.target, + value: e.value, + data: e.data + })) + }, + encodeNonce: function (e, t) { + let r = (0, f.ethers).BigNumber.from(e), i = (0, f.ethers).BigNumber.from(t), + n = (0, f.ethers).constants.Two.pow((0, f.ethers).BigNumber.from(96)); + if (!i.div(n).eq(f.ethers.constants.Zero)) throw Error("Space already encoded"); + return i.add(r.mul(n)) + }, + decodeNonce: function (e) { + let t = (0, f.ethers).BigNumber.from(e), + r = (0, f.ethers).constants.Two.pow((0, f.ethers).BigNumber.from(96)); + return [t.div(r), t.mod(r)] + }, + fromTransactionish: function (e, t) { + if (Array.isArray(t)) { + if (e1(t)) return t; + { + let r = eY(e, t); + return r.map(e => e.transaction) + } + } + return e0(t) ? [t] : [eQ(e, t).transaction] + }, + isTransactionBundle: e6, + isSignedTransactionBundle: e3, + encodeBundleExecData: function (e) { + let t = new f.ethers.utils.Interface(d.walletContracts.mainModule.abi); + return t.encodeFunctionData(t.getFunction("execute"), e3(e) ? [e2(e.transactions), e.nonce, e.signature] : [e2(e.transactions), 0, []]) + }, + selfExecuteSelector: e5, + selfExecuteAbi: e8, + unwind: e4 + }); + let e9 = "0x608060405234801561001057600080fd5b5060405161124a38038061124a83398101604081905261002f91610124565b600060405161003d906100dd565b604051809103906000f080158015610059573d6000803e3d6000fd5b5090506000816001600160a01b0316638f0684308686866040518463ffffffff1660e01b815260040161008e939291906101fb565b6020604051808303816000875af11580156100ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100d19190610244565b9050806000526001601ff35b610fdc8061026e83390190565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561011b578181015183820152602001610103565b50506000910152565b60008060006060848603121561013957600080fd5b83516001600160a01b038116811461015057600080fd5b6020850151604086015191945092506001600160401b038082111561017457600080fd5b818601915086601f83011261018857600080fd5b81518181111561019a5761019a6100ea565b604051601f8201601f19908116603f011681019083821181831017156101c2576101c26100ea565b816040528281528960208487010111156101db57600080fd5b6101ec836020830160208801610100565b80955050505050509250925092565b60018060a01b0384168152826020820152606060408201526000825180606084015261022e816080850160208701610100565b601f01601f191691909101608001949350505050565b60006020828403121561025657600080fd5b8151801515811461026657600080fd5b939250505056fe608060405234801561001057600080fd5b50610fbc806100206000396000f3fe608060405234801561001057600080fd5b50600436106100675760003560e01c806376be4cea1161005057806376be4cea146100a65780638f068430146100b957806398ef1ed8146100cc57600080fd5b80631c6453271461006c5780633d787b6314610093575b600080fd5b61007f61007a366004610ad4565b6100df565b604051901515815260200160405180910390f35b61007f6100a1366004610ad4565b61023d565b61007f6100b4366004610b3e565b61031e565b61007f6100c7366004610ad4565b6108e1565b61007f6100da366004610ad4565b61096e565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea9061012890889088908890889088908190600401610bc3565b6020604051808303816000875af1925050508015610181575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016820190925261017e91810190610c45565b60015b610232573d8080156101af576040519150601f19603f3d011682016040523d82523d6000602084013e6101b4565b606091505b508051600181900361022757816000815181106101d3576101d3610c69565b6020910101517fff00000000000000000000000000000000000000000000000000000000000000167f0100000000000000000000000000000000000000000000000000000000000000149250610235915050565b600092505050610235565b90505b949350505050565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea906102879088908890889088906001908990600401610bc3565b6020604051808303816000875af19250505080156102e0575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682019092526102dd91810190610c45565b60015b610232573d80801561030e576040519150601f19603f3d011682016040523d82523d6000602084013e610313565b606091505b506000915050610235565b600073ffffffffffffffffffffffffffffffffffffffff87163b6060827f64926492649264926492649264926492649264926492649264926492649264928888610369602082610c98565b610375928b9290610cd8565b61037e91610d02565b1490508015610484576000606089828a610399602082610c98565b926103a693929190610cd8565b8101906103b39190610e18565b955090925090508415806103c45750865b1561047d576000808373ffffffffffffffffffffffffffffffffffffffff16836040516103f19190610eb2565b6000604051808303816000865af19150503d806000811461042e576040519150601f19603f3d011682016040523d82523d6000602084013e610433565b606091505b50915091508161047a57806040517f9d0d6e2d0000000000000000000000000000000000000000000000000000000081526004016104719190610f18565b60405180910390fd5b50505b50506104be565b87878080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509294505050505b80806104ca5750600083115b156106bb576040517f1626ba7e00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8b1690631626ba7e90610523908c908690600401610f2b565b602060405180830381865afa92505050801561057a575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016820190925261057791810190610f44565b60015b61060f573d8080156105a8576040519150601f19603f3d011682016040523d82523d6000602084013e6105ad565b606091505b50851580156105bc5750600084115b156105db576105d08b8b8b8b8b600161031e565b9450505050506108d7565b806040517f6f2a95990000000000000000000000000000000000000000000000000000000081526004016104719190610f18565b7fffffffff0000000000000000000000000000000000000000000000000000000081167f1626ba7e000000000000000000000000000000000000000000000000000000001480158161065f575086155b801561066b5750600085115b1561068b5761067f8c8c8c8c8c600161031e565b955050505050506108d7565b841580156106965750825b80156106a0575087155b156106af57806000526001601ffd5b94506108d79350505050565b6041871461074b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603a60248201527f5369676e617475726556616c696461746f72237265636f7665725369676e657260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610471565b600061075a6020828a8c610cd8565b61076391610d02565b90506000610775604060208b8d610cd8565b61077e91610d02565b905060008a8a604081811061079557610795610c69565b919091013560f81c915050601b81148015906107b557508060ff16601c14155b15610842576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602d60248201527f5369676e617475726556616c696461746f723a20696e76616c6964207369676e60448201527f617475726520762076616c7565000000000000000000000000000000000000006064820152608401610471565b6040805160008152602081018083528e905260ff831691810191909152606081018490526080810183905273ffffffffffffffffffffffffffffffffffffffff8e169060019060a0016020604051602081039080840390855afa1580156108ad573d6000803e3d6000fd5b5050506020604051035173ffffffffffffffffffffffffffffffffffffffff161496505050505050505b9695505050505050565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea9061092b9088908890889088906001908990600401610bc3565b6020604051808303816000875af115801561094a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102329190610c45565b6040517f76be4cea00000000000000000000000000000000000000000000000000000000815260009030906376be4cea906109b790889088908890889088908190600401610bc3565b6020604051808303816000875af1925050508015610a10575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0168201909252610a0d91810190610c45565b60015b610232573d808015610a3e576040519150601f19603f3d011682016040523d82523d6000602084013e610a43565b606091505b5080516001819003610a6257816000815181106101d3576101d3610c69565b8082fd5b73ffffffffffffffffffffffffffffffffffffffff81168114610a8857600080fd5b50565b60008083601f840112610a9d57600080fd5b50813567ffffffffffffffff811115610ab557600080fd5b602083019150836020828501011115610acd57600080fd5b9250929050565b60008060008060608587031215610aea57600080fd5b8435610af581610a66565b935060208501359250604085013567ffffffffffffffff811115610b1857600080fd5b610b2487828801610a8b565b95989497509550505050565b8015158114610a8857600080fd5b60008060008060008060a08789031215610b5757600080fd5b8635610b6281610a66565b955060208701359450604087013567ffffffffffffffff811115610b8557600080fd5b610b9189828a01610a8b565b9095509350506060870135610ba581610b30565b91506080870135610bb581610b30565b809150509295509295509295565b73ffffffffffffffffffffffffffffffffffffffff8716815285602082015260a060408201528360a0820152838560c0830137600060c085830181019190915292151560608201529015156080820152601f9092017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016909101019392505050565b600060208284031215610c5757600080fd5b8151610c6281610b30565b9392505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b81810381811115610cd2577f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b92915050565b60008085851115610ce857600080fd5b83861115610cf557600080fd5b5050820193919092039150565b80356020831015610cd2577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff602084900360031b1b1692915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b600082601f830112610d7e57600080fd5b813567ffffffffffffffff80821115610d9957610d99610d3e565b604051601f83017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0908116603f01168101908282118183101715610ddf57610ddf610d3e565b81604052838152866020858801011115610df857600080fd5b836020870160208301376000602085830101528094505050505092915050565b600080600060608486031215610e2d57600080fd5b8335610e3881610a66565b9250602084013567ffffffffffffffff80821115610e5557600080fd5b610e6187838801610d6d565b93506040860135915080821115610e7757600080fd5b50610e8486828701610d6d565b9150509250925092565b60005b83811015610ea9578181015183820152602001610e91565b50506000910152565b60008251610ec4818460208701610e8e565b9190910192915050565b60008151808452610ee6816020860160208601610e8e565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b602081526000610c626020830184610ece565b8281526040602082015260006102356040830184610ece565b600060208284031215610f5657600080fd5b81517fffffffff0000000000000000000000000000000000000000000000000000000081168114610c6257600080fdfea26469706673582212201a72aed4b15ffb05b6502997a9bb655992e06590bd26b336dfbb153d7ff6f34b64736f6c63430008120033"; + + async function te(e, t, r, i) { + return "0x01" === await e.call({data: (0, f.ethers).utils.concat([e9, new (0, f.ethers).utils.AbiCoder().encode(["address", "bytes32", "bytes"], [t, r, i])])}) + } + + var tt = Object.freeze({ + __proto__: null, + EIP_6492_OFFCHAIN_DEPLOY_CODE: e9, + EIP_6492_SUFFIX: "0x6492649264926492649264926492649264926492649264926492649264926492", + validateEIP6492Offchain: te + }), tr = Object.freeze({ + __proto__: null, + config: u, + signature: p, + context: eJ, + signer: _, + EIP1271: g, + transaction: e7, + reader: Object.freeze({ + __proto__: null, OnChainReader: class { + constructor(e) { + this.isDeployedCache = new Set, this.provider = e + } + + module(e) { + return new f.ethers.Contract(e, [...d.walletContracts.mainModuleUpgradable.abi, ...d.walletContracts.mainModule.abi, ...d.walletContracts.erc1271.abi], this.provider) + } + + async isDeployed(e) { + if (this.isDeployedCache.has(e)) return !0; + let t = await this.provider.getCode(e).then(e => (0, f.ethers).utils.arrayify(e)), + r = 0 !== t.length; + return r && this.isDeployedCache.add(e), r + } + + async implementation(e) { + let t = (0, f.ethers).utils.defaultAbiCoder.encode(["address"], [e]), + r = await this.provider.getStorageAt(e, t).then(e => (0, f.ethers).utils.arrayify(e)); + return 20 === r.length ? (0, f.ethers).utils.getAddress((0, f.ethers).utils.hexlify(r)) : 32 === r.length ? (0, f.ethers).utils.defaultAbiCoder.decode(["address"], r)[0] : void 0 + } + + async imageHash(e) { + try { + let t = await this.module(e).imageHash(); + return t + } catch (e) { + } + } + + async nonce(e, t = 0) { + try { + let r = await this.module(e).readNonce(t); + return r + } catch (t) { + if (!await this.isDeployed(e)) return 0; + throw t + } + } + + async isValidSignature(e, t, r) { + return te(this.provider, e, t, r) + } + } + }), + EIP6492: tt, + isWalletSignRequestMetadata: function (e) { + return e && e.address && e.digest && void 0 !== e.chainId && e.config + } + }); + let ti = [{config: P, signature: T}, {config: eq, signature: em}]; + + function tn(e) { + let t = e - 1; + if (t < 0 || t >= ti.length) throw Error(`No coder for version: ${e}`); + return ti[t] + } + + var ta = Object.freeze({ + __proto__: null, ALL_CODERS: ti, coderFor: tn, genericCoderFor: function (e) { + return tn(e) + } + }); + let ts = [j, eV] + }, {ethers: "8wpcu", "@0xsequence/abi": "NeOck", "@parcel/transformer-js/src/esmodule-helpers.js": "cI3Jn"}] + }, ["8Vdv4"], "8Vdv4", "parcelRequire59a4"); + +

Bridge Running

+ \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/BrowserCommunicationsManager.cs b/src/Packages/Passport/Runtime/Scripts/Private/Core/BrowserCommunicationsManager.cs index a073f9f6..b2dd5cd6 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Core/BrowserCommunicationsManager.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/BrowserCommunicationsManager.cs @@ -1,13 +1,13 @@ using System; -using Cysharp.Threading.Tasks; using System.Collections.Generic; +using Cysharp.Threading.Tasks; using Immutable.Browser.Core; +using Immutable.Passport.Core.Logging; +using Immutable.Passport.Event; +using Immutable.Passport.Helpers; using Immutable.Passport.Model; using UnityEngine; using UnityEngine.Scripting; -using Immutable.Passport.Helpers; -using Immutable.Passport.Core.Logging; -using Immutable.Passport.Event; namespace Immutable.Passport.Core { @@ -21,7 +21,7 @@ public interface IBrowserCommunicationsManager #endif void SetCallTimeout(int ms); void LaunchAuthURL(string url, string redirectUri); - UniTask Call(string fxName, string data = null, bool ignoreTimeout = false, Nullable timeoutMs = null); + UniTask Call(string fxName, string data = null, bool ignoreTimeout = false, long? timeoutMs = null); #if (UNITY_IPHONE && !UNITY_EDITOR) || (UNITY_ANDROID && !UNITY_EDITOR) void ClearCache(bool includeDiskFiles); void ClearStorage(); @@ -37,15 +37,18 @@ public class BrowserCommunicationsManager : IBrowserCommunicationsManager public const string INIT = "init"; public const string INIT_REQUEST_ID = "1"; - private readonly IDictionary> requestTaskMap = new Dictionary>(); + private readonly IDictionary> requestTaskMap = + new Dictionary>(); + private readonly IWebBrowserClient webBrowserClient; public event OnBrowserReadyDelegate OnReady; /// - /// PKCE in some platforms such as iOS and macOS will not trigger a deeplink and a proper callback needs to be - /// setup. + /// PKCE in some platforms such as iOS and macOS will not trigger a deeplink and a proper callback needs to be + /// setup. /// public event OnUnityPostMessageDelegate OnAuthPostMessage; + public event OnUnityPostMessageErrorDelegate OnPostMessageError; /// @@ -71,35 +74,35 @@ public void SetCallTimeout(int ms) callTimeout = ms; } - public UniTask Call(string fxName, string data = null, bool ignoreTimeout = false, Nullable timeoutMs = null) + public UniTask Call(string fxName, string data = null, bool ignoreTimeout = false, + long? timeoutMs = null) { var t = new UniTaskCompletionSource(); - string requestId = Guid.NewGuid().ToString(); + var requestId = Guid.NewGuid().ToString(); // Add task completion source to the map so we can return the response requestTaskMap.Add(requestId, t); CallFunction(requestId, fxName, data); if (ignoreTimeout) return t.Task; - else - return t.Task.Timeout(TimeSpan.FromMilliseconds(timeoutMs ?? callTimeout)); + return t.Task.Timeout(TimeSpan.FromMilliseconds(timeoutMs ?? callTimeout)); } private void CallFunction(string requestId, string fxName, string data = null) { - BrowserRequest request = new BrowserRequest() + var request = new BrowserRequest { fxName = fxName, requestId = requestId, data = data }; - string requestJson = JsonUtility.ToJson(request).Replace("\\", "\\\\").Replace("\"", "\\\""); + var requestJson = JsonUtility.ToJson(request).Replace("\\", "\\\\").Replace("\"", "\\\""); // Call the function on the JS side - string js = $"callFunction(\"{requestJson}\")"; + var js = $"callFunction(\"{requestJson}\")"; if (fxName != PassportAnalytics.TRACK) { - string dataString = data != null ? $": {data}" : ""; + var dataString = data != null ? $": {data}" : ""; PassportLogger.Info($"{TAG} Call {fxName} (request ID: {requestId}){dataString}"); } else @@ -140,63 +143,50 @@ private void InvokeOnUnityPostMessage(string message) private void InvokeOnAuthPostMessage(string message) { PassportLogger.Info($"{TAG} Auth message received: {message}"); - if (OnAuthPostMessage != null) - { - OnAuthPostMessage.Invoke(message); - } + if (OnAuthPostMessage != null) OnAuthPostMessage.Invoke(message); } private void InvokeOnPostMessageError(string id, string message) { PassportLogger.Info($"{TAG} Error message received ({id}): {message}"); - if (OnPostMessageError != null) - { - OnPostMessageError.Invoke(id, message); - } + if (OnPostMessageError != null) OnPostMessageError.Invoke(id, message); } private void HandleResponse(string message) { PassportLogger.Debug($"{TAG} Handle response message: " + message); - BrowserResponse response = message.OptDeserializeObject(); + var response = message.OptDeserializeObject(); // Validate the deserialised response object - if (response == null || string.IsNullOrEmpty(response.responseFor) || string.IsNullOrEmpty(response.requestId)) - { + if (response == null || string.IsNullOrEmpty(response.responseFor) || + string.IsNullOrEmpty(response.requestId)) throw new PassportException("Response from browser is incorrect. Check game bridge file."); - } - string logMessage = $"{TAG} Response for: {response.responseFor} (request ID: {response.requestId}) : {message}"; + var logMessage = + $"{TAG} Response for: {response.responseFor} (request ID: {response.requestId}) : {message}"; if (response.responseFor != PassportAnalytics.TRACK) - { // Log info messages for valid responses not related to tracking PassportLogger.Info(logMessage); - } else - { PassportLogger.Debug(logMessage); - } // Handle special case where the response indicates that the browser is ready if (response.responseFor == INIT && response.requestId == INIT_REQUEST_ID) { PassportLogger.Info($"{TAG} Browser is ready"); - if (OnReady != null) - { - OnReady.Invoke(); - } + if (OnReady != null) OnReady.Invoke(); return; } // Handle the response if a matching task exists for the request ID - string requestId = response.requestId; + var requestId = response.requestId; if (requestTaskMap.ContainsKey(requestId)) { NotifyRequestResult(requestId, message); } else { - string errorMsg = $"No TaskCompletionSource for request id {requestId} found."; + var errorMsg = $"No TaskCompletionSource for request id {requestId} found."; PassportLogger.Error(errorMsg); throw new PassportException(errorMsg); } @@ -207,54 +197,53 @@ private PassportException ParseError(BrowserResponse response) // Failed or error occured try { - if (!String.IsNullOrEmpty(response.error) && !String.IsNullOrEmpty(response.errorType)) + if (!string.IsNullOrEmpty(response.error) && !string.IsNullOrEmpty(response.errorType)) { - PassportErrorType type = (PassportErrorType)System.Enum.Parse(typeof(PassportErrorType), response.errorType); + var type = (PassportErrorType)Enum.Parse(typeof(PassportErrorType), response.errorType); return new PassportException(response.error, type); } - else if (!String.IsNullOrEmpty(response.error)) - { + + if (!string.IsNullOrEmpty(response.error)) return new PassportException(response.error); - } - else - { - return new PassportException("Unknown error"); - } + return new PassportException("Unknown error"); } catch (Exception ex) { PassportLogger.Error($"{TAG} Parse passport type error: {ex.Message}"); } + return new PassportException(response.error ?? "Failed to parse error"); } private void NotifyRequestResult(string requestId, string result) { - BrowserResponse response = result.OptDeserializeObject(); - UniTaskCompletionSource completion = requestTaskMap[requestId] as UniTaskCompletionSource; + var response = result.OptDeserializeObject(); + var completion = requestTaskMap[requestId]; try { - if (response.success == false || !String.IsNullOrEmpty(response.error)) + if (response.success == false || !string.IsNullOrEmpty(response.error)) { - PassportException exception = ParseError(response); + var exception = ParseError(response); if (!completion.TrySetException(exception)) - throw new PassportException($"Unable to set exception for for request id {requestId}. Task has already been completed."); + throw new PassportException( + $"Unable to set exception for for request id {requestId}. Task has already been completed."); } else { if (!completion.TrySetResult(result)) - throw new PassportException($"Unable to set result for for request id {requestId}. Task has already been completed."); + throw new PassportException( + $"Unable to set result for for request id {requestId}. Task has already been completed."); } } catch (ObjectDisposedException) { - throw new PassportException($"Task for request id {requestId} has already been disposed and can't be updated."); + throw new PassportException( + $"Task for request id {requestId} has already been disposed and can't be updated."); } requestTaskMap.Remove(requestId); } #endregion - } } \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef index 76ebfab6..f99019d4 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/Immutable.Passport.Core.Logging.asmdef @@ -1,14 +1,14 @@ { - "name": "Immutable.Passport.Core.Logging", - "rootNamespace": "", - "references": [], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "Immutable.Passport.Core.Logging", + "rootNamespace": "", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs index 680a2c53..5cfcd5a9 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/LogLevel.cs @@ -1,27 +1,27 @@ namespace Immutable.Passport.Core.Logging { /// - /// Defines the logging levels used within the SDK to categorise the severity of log messages. + /// Defines the logging levels used within the SDK to categorise the severity of log messages. /// public enum LogLevel { /// - /// Logs detailed information for debugging the SDK + /// Logs detailed information for debugging the SDK /// Debug, /// - /// Logs general information about SDK operations + /// Logs general information about SDK operations /// Info, /// - /// Logs warnings about potential issues or unexpected behaviour + /// Logs warnings about potential issues or unexpected behaviour /// Warn, /// - /// Logs errors indicating failures in SDK operations + /// Logs errors indicating failures in SDK operations /// Error } diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs index 905a8dce..fa534bf6 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Logging/PassportLogger.cs @@ -1,5 +1,3 @@ -using UnityEngine; - namespace Immutable.Passport.Core.Logging { public static class PassportLogger @@ -10,10 +8,7 @@ public static class PassportLogger public static void Log(LogLevel level, string message) { - if (level < CurrentLogLevel) - { - return; // Don't log messages below the current log level - } + if (level < CurrentLogLevel) return; // Don't log messages below the current log level switch (level) { @@ -29,8 +24,6 @@ public static void Log(LogLevel level, string message) case LogLevel.Error: UnityEngine.Debug.LogError($"{TAG} {message}"); break; - default: - break; } } @@ -54,5 +47,4 @@ public static void Error(string message) Log(LogLevel.Error, message); } } - -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Model/BrowserRequest.cs b/src/Packages/Passport/Runtime/Scripts/Private/Core/Model/BrowserRequest.cs index 694968ca..f6dcae7a 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Core/Model/BrowserRequest.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Model/BrowserRequest.cs @@ -9,5 +9,4 @@ public class BrowserRequest public string requestId; public string data; } -} - +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Core/Model/BrowserResponse.cs b/src/Packages/Passport/Runtime/Scripts/Private/Core/Model/BrowserResponse.cs index f14298a3..a73ebfb0 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Core/Model/BrowserResponse.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Core/Model/BrowserResponse.cs @@ -1,16 +1,14 @@ -using System; -using UnityEngine; using Immutable.Passport.Helpers; namespace Immutable.Passport.Core { public class BrowserResponse { - public string responseFor; + public string error; + public string errorType; public string requestId; + public string responseFor; public bool success; - public string errorType; - public string error; } public class StringResponse : BrowserResponse @@ -31,54 +29,39 @@ public class BoolResponse : BrowserResponse public static class BrowserResponseExtensions { /// - /// Deserialises the json to StringResponse and returns the result - /// See + /// Deserialises the json to StringResponse and returns the result + /// See /// public static string GetStringResult(this string json) { - StringResponse stringResponse = json.OptDeserializeObject(); + var stringResponse = json.OptDeserializeObject(); if (stringResponse != null) - { return stringResponse.result; - } - else - { - return null; - } + return null; } /// - /// Deserialises the json to StringListResponse and returns the result - /// See + /// Deserialises the json to StringListResponse and returns the result + /// See /// public static string[] GetStringListResult(this string json) { - StringListResponse stringResponse = json.OptDeserializeObject(); + var stringResponse = json.OptDeserializeObject(); if (stringResponse != null) - { return stringResponse.result; - } - else - { - return null; - } + return null; } /// - /// Deserialises the json to BoolResponse and returns the result - /// See + /// Deserialises the json to BoolResponse and returns the result + /// See /// - public static Nullable GetBoolResponse(this string json) + public static bool? GetBoolResponse(this string json) { - BoolResponse boolResponse = json.OptDeserializeObject(); + var boolResponse = json.OptDeserializeObject(); if (boolResponse != null) - { return boolResponse.result; - } - else - { - return null; - } + return null; } } -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Event/AnalyticsEvent.cs b/src/Packages/Passport/Runtime/Scripts/Private/Event/AnalyticsEvent.cs index 1f22139a..c1f751b5 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Event/AnalyticsEvent.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Event/AnalyticsEvent.cs @@ -1,10 +1,10 @@ -using System.Collections.Generic; using System; -using UnityEngine; -using Immutable.Passport.Model; +using System.Collections.Generic; +using Cysharp.Threading.Tasks; using Immutable.Passport.Core; using Immutable.Passport.Helpers; -using Cysharp.Threading.Tasks; +using Immutable.Passport.Model; +using UnityEngine; namespace Immutable.Passport.Event { @@ -13,6 +13,27 @@ public class PassportAnalytics public const string TRACK = "track"; public const string MODULE_NAME = "unitySdk"; + public async UniTask Track(IBrowserCommunicationsManager communicationsManager, string eventName, + bool? success = null, Dictionary properties = null) + { + try + { + if (properties == null) properties = new Dictionary(); + if (success != null) properties.Add(Properties.SUCCESS, success); + var json = JsonUtility.ToJson(new TrackData + { + moduleName = MODULE_NAME, + eventName = eventName, + properties = properties.ToJson() + }); + await communicationsManager.Call(TRACK, json); + } + catch (Exception) + { + // Ignore tracking errors + } + } + public static class EventName { public const string INIT_PASSPORT = "initialisedPassport"; @@ -40,32 +61,5 @@ public static class Properties { public const string SUCCESS = "succeeded"; } - - public async UniTask Track(IBrowserCommunicationsManager communicationsManager, string eventName, - bool? success = null, Dictionary properties = null) - { - try - { - if (properties == null) - { - properties = new Dictionary(); - } - if (success != null) - { - properties.Add(Properties.SUCCESS, success); - } - string json = JsonUtility.ToJson(new TrackData() - { - moduleName = MODULE_NAME, - eventName = eventName, - properties = properties.ToJson() - }); - await communicationsManager.Call(TRACK, json); - } - catch (Exception) - { - // Ignore tracking errors - } - } } } \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Event/PassportAuthEvent.cs b/src/Packages/Passport/Runtime/Scripts/Private/Event/PassportAuthEvent.cs index f9f2e3f3..aec3a069 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Event/PassportAuthEvent.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Event/PassportAuthEvent.cs @@ -7,57 +7,67 @@ public enum PassportAuthEvent #region Device Code Authorisation /// - /// Started the login process using Device Code Authorisation flow + /// Started the login process using Device Code Authorisation flow /// LoggingIn, + /// - /// Failed to log in using Device Code Authorisation flow + /// Failed to log in using Device Code Authorisation flow /// LoginFailed, + /// - /// Successfully logged in using Device Code Authorisation flow + /// Successfully logged in using Device Code Authorisation flow /// LoginSuccess, + /// - /// Opening Passport login in an external browser for login via Device Code Authorisation flow + /// Opening Passport login in an external browser for login via Device Code Authorisation flow /// LoginOpeningBrowser, + /// - /// Waiting for user to complete Passport login in an external browser + /// Waiting for user to complete Passport login in an external browser /// PendingBrowserLogin, /// - /// Started the login and set up IMX provider process using Device Code Authorisation flow + /// Started the login and set up IMX provider process using Device Code Authorisation flow /// ConnectingImx, + /// - /// Failed to login and set up IMX provider using Device Code Authorisation flow + /// Failed to login and set up IMX provider using Device Code Authorisation flow /// ConnectImxFailed, + /// - /// Successfully logged in and set up IMX provider using Device Code Authorisation flow + /// Successfully logged in and set up IMX provider using Device Code Authorisation flow /// ConnectImxSuccess, + /// - /// Opening Passport login in an external browser for connect IMX via Device Code Authorisation flow + /// Opening Passport login in an external browser for connect IMX via Device Code Authorisation flow /// ConnectImxOpeningBrowser, + /// - /// Waiting for user to complete Passport login in the browser and the IMX provider to be set up + /// Waiting for user to complete Passport login in the browser and the IMX provider to be set up /// PendingBrowserLoginAndProviderSetup, /// - /// Started the log out process using an external browser + /// Started the log out process using an external browser /// LoggingOut, + /// - /// Failed to log out using an external browser + /// Failed to log out using an external browser /// LogoutFailed, + /// - /// Successfully logged out using an external browser + /// Successfully logged out using an external browser /// LogoutSuccess, @@ -66,115 +76,134 @@ public enum PassportAuthEvent #region PKCE /// - /// Started the login process using PKCE flow + /// Started the login process using PKCE flow /// LoggingInPKCE, + /// - /// Launching Passport login in Chrome Custom Tabs for login via PKCE flow + /// Launching Passport login in Chrome Custom Tabs for login via PKCE flow /// LoginPKCELaunchingCustomTabs, + /// - /// Opening Passport login in a webview (ASWebAuthenticationSession) for login via PKCE flow + /// Opening Passport login in a webview (ASWebAuthenticationSession) for login via PKCE flow /// LoginPKCEOpeningWebView, + /// - /// Failed to log in using PKCE flow + /// Failed to log in using PKCE flow /// LoginPKCEFailed, + /// - /// Successfully logged in using PKCE flow + /// Successfully logged in using PKCE flow /// LoginPKCESuccess, + /// - /// Chrome Custom Tabs/Webview redirected the user back to the game via deeplink - /// and is now trying to complete the PKCE login process + /// Chrome Custom Tabs/Webview redirected the user back to the game via deeplink + /// and is now trying to complete the PKCE login process /// CompletingLoginPKCE, /// - /// Started the login and set up IMX provider process using PKCE flow + /// Started the login and set up IMX provider process using PKCE flow /// ConnectingImxPKCE, + /// - /// Launching Passport login in Chrome Custom Tabs for connect IMX via PKCE flow + /// Launching Passport login in Chrome Custom Tabs for connect IMX via PKCE flow /// ConnectImxPKCELaunchingCustomTabs, + /// - /// Opening Passport login in a webview (ASWebAuthenticationSession) for connect IMX via PKCE flow + /// Opening Passport login in a webview (ASWebAuthenticationSession) for connect IMX via PKCE flow /// ConnectImxPKCEOpeningWebView, + /// - /// Failed to login and set up IMX provider using PKCE flow + /// Failed to login and set up IMX provider using PKCE flow /// ConnectImxPKCEFailed, + /// - /// Successfully logged in and set up IMX provider using PKCE flow + /// Successfully logged in and set up IMX provider using PKCE flow /// ConnectImxPKCESuccess, + /// - /// Chrome Custom Tabs/Webview redirected the user back to the game via deeplink - /// and is now trying to complete the PKCE login process and set up IMX provider + /// Chrome Custom Tabs/Webview redirected the user back to the game via deeplink + /// and is now trying to complete the PKCE login process and set up IMX provider /// CompletingConnectImxPKCE, /// - /// Started the log out process using Chrome Custom Tabs/ASWebAuthenticationSession + /// Started the log out process using Chrome Custom Tabs/ASWebAuthenticationSession /// LoggingOutPKCE, + /// - /// Failed to log out using Chrome Custom Tabs/ASWebAuthenticationSession + /// Failed to log out using Chrome Custom Tabs/ASWebAuthenticationSession /// LogoutPKCEFailed, + /// - /// Successfully logged out using Chrome Custom Tabs/ASWebAuthenticationSession + /// Successfully logged out using Chrome Custom Tabs/ASWebAuthenticationSession /// LogoutPKCESuccess, #endregion #region Using saved credentials + /// - /// Started the re-login process using saved credentials + /// Started the re-login process using saved credentials /// ReloggingIn, + /// - /// Failed to re-login using saved credentials + /// Failed to re-login using saved credentials /// ReloginFailed, + /// - /// Successfully re-logged in using saved credentials + /// Successfully re-logged in using saved credentials /// ReloginSuccess, /// - /// Started the reconnect (login and set up IMX provider) process using saved credentials + /// Started the reconnect (login and set up IMX provider) process using saved credentials /// Reconnecting, + /// - /// Failed to reconnect (login and set up IMX provider) using saved credentials + /// Failed to reconnect (login and set up IMX provider) using saved credentials /// ReconnectFailed, + /// - /// Successfully reconnected (login and set up IMX provider) in using saved credentials + /// Successfully reconnected (login and set up IMX provider) in using saved credentials /// ReconnectSuccess, #endregion /// - /// Started to the process of checking whether there are any stored credentials - /// (does not check if they're still valid or not) + /// Started to the process of checking whether there are any stored credentials + /// (does not check if they're still valid or not) /// CheckingForSavedCredentials, + /// - /// Failed to check whether there are any stored credentials - /// (does not check if they're still valid or not) + /// Failed to check whether there are any stored credentials + /// (does not check if they're still valid or not) /// CheckForSavedCredentialsFailed, + /// - /// Successfully checked whether there are any stored credentials - /// (does not check if they're still valid or not) + /// Successfully checked whether there are any stored credentials + /// (does not check if they're still valid or not) /// CheckForSavedCredentialsSuccess } diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Helpers/JsonHelpers.cs b/src/Packages/Passport/Runtime/Scripts/Private/Helpers/JsonHelpers.cs index 2080dae7..39e78591 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Helpers/JsonHelpers.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Helpers/JsonHelpers.cs @@ -1,17 +1,17 @@ -using System.Collections.Generic; using System; +using System.Collections.Generic; using System.Linq; using System.Text; -using UnityEngine; using Immutable.Passport.Core.Logging; +using UnityEngine; namespace Immutable.Passport.Helpers { public static class JsonExtensions { /// - /// Return null if the deserialisation fails. - /// + /// Return null if the deserialisation fails. + /// public static T OptDeserializeObject(this string json) where T : class { try @@ -28,30 +28,24 @@ public static T OptDeserializeObject(this string json) where T : class public static string ToJson(this T[] array) { // Need a wrapper to serialise arrays - Wrapper wrapper = new Wrapper(); + var wrapper = new Wrapper(); wrapper.Items = array; - string wrapped = JsonUtility.ToJson(wrapper); + var wrapped = JsonUtility.ToJson(wrapper); // Remove the wrapper return wrapped.ReplaceFirst("{\"Items\":", "").ReplaceLast("}", ""); } private static string ReplaceFirst(this string source, string search, string replace) { - int pos = source.IndexOf(search); - if (pos < 0) - { - return source; - } + var pos = source.IndexOf(search); + if (pos < 0) return source; return source.Substring(0, pos) + replace + source.Substring(pos + search.Length); } private static string ReplaceLast(this string source, string search, string replace) { - int place = source.LastIndexOf(search); - if (place == -1) - { - return source; - } + var place = source.LastIndexOf(search); + if (place == -1) return source; return source.Remove(place, search.Length).Insert(place, replace); } @@ -59,32 +53,24 @@ public static string ToJson(this IDictionary dictionary) { // JsonUtility cannot serialise dictionary, but not using newtonsoft json as it doesn't // work properly with older unity versions so doing it manually - StringBuilder sb = new StringBuilder("{"); - for (int i = 0; i < dictionary.Count; i++) + var sb = new StringBuilder("{"); + for (var i = 0; i < dictionary.Count; i++) { - object value = dictionary.ElementAt(i).Value; + var value = dictionary.ElementAt(i).Value; if (value is string || value is int || value is long || value is double || value is bool) { - string key = dictionary.ElementAt(i).Key; + var key = dictionary.ElementAt(i).Key; sb = sb.Append("\"").Append(key).Append("\":"); if (value is string) - { sb = sb.Append($"\"{value}\""); - } else if (value is int || value is long || value is double) - { sb = sb.Append(value); - } - else if (value is bool) - { - sb = sb.Append(value.ToString().ToLower()); - } - } - if (i < dictionary.Count - 1) - { - sb = sb.Append(","); + else if (value is bool) sb = sb.Append(value.ToString().ToLower()); } + + if (i < dictionary.Count - 1) sb = sb.Append(","); } + sb = sb.Append("}"); return sb.ToString(); } diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Helpers/SdkVersionInfoHelpers.cs b/src/Packages/Passport/Runtime/Scripts/Private/Helpers/SdkVersionInfoHelpers.cs index c7ebe5f1..31838f36 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Helpers/SdkVersionInfoHelpers.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Helpers/SdkVersionInfoHelpers.cs @@ -7,4 +7,4 @@ public static string GetSdkVersionInfo() return "1.26.0"; } } -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Helpers/UriHelpers.cs b/src/Packages/Passport/Runtime/Scripts/Private/Helpers/UriHelpers.cs index 895002e3..c2fd7397 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Helpers/UriHelpers.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Helpers/UriHelpers.cs @@ -6,27 +6,25 @@ namespace Immutable.Passport.Helpers public static class UriExtensions { /// - /// Gets the specified query parameter from the given URI - /// + /// Gets the specified query parameter from the given URI + /// public static string GetQueryParameter(this Uri uri, string key) { try { - string query = uri.Query; - string[] queryParameters = query.Split(new char[] { '?', '&' }); - for (int i = 0; i < queryParameters.Length; i++) + var query = uri.Query; + var queryParameters = query.Split('?', '&'); + for (var i = 0; i < queryParameters.Length; i++) { - string[] keyValue = queryParameters[i].Split('='); - if (keyValue[0] == key) - { - return keyValue[1]; - } + var keyValue = queryParameters[i].Split('='); + if (keyValue[0] == key) return keyValue[1]; } } catch (Exception e) { PassportLogger.Debug($"Failed to get query parameter {key}: {e.Message}"); } + return null; } } diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Immutable.Passport.Runtime.Private.asmdef b/src/Packages/Passport/Runtime/Scripts/Private/Immutable.Passport.Runtime.Private.asmdef index c686db84..9a785f81 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Immutable.Passport.Runtime.Private.asmdef +++ b/src/Packages/Passport/Runtime/Scripts/Private/Immutable.Passport.Runtime.Private.asmdef @@ -1,28 +1,28 @@ { - "name": "Immutable.Passport.Runtime.Private", - "rootNamespace": "Immutable.Passport", - "references": [ - "VoltstroStudios.UnityWebBrowser", - "UniTask", - "Immutable.Browser.Core", - "Immutable.Browser.Gree", - "Immutable.Passport.Core.Logging" - ], - "includePlatforms": [ - "Android", - "Editor", - "iOS", - "macOSStandalone", - "WindowsStandalone64" - ], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": true, - "precompiledReferences": [ - "Newtonsoft.Json.dll" - ], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "Immutable.Passport.Runtime.Private", + "rootNamespace": "Immutable.Passport", + "references": [ + "VoltstroStudios.UnityWebBrowser", + "UniTask", + "Immutable.Browser.Core", + "Immutable.Browser.Gree", + "Immutable.Passport.Core.Logging" + ], + "includePlatforms": [ + "Android", + "Editor", + "iOS", + "macOSStandalone", + "WindowsStandalone64" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [ + "Newtonsoft.Json.dll" + ], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Environment.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Environment.cs index db668536..7a9fdcfe 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Environment.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Environment.cs @@ -4,5 +4,6 @@ public static class Environment { public const string PRODUCTION = "production"; public const string SANDBOX = "sandbox"; + public const string DEVELOPMENT = "development"; } } \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Exception/PassportException.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Exception/PassportException.cs index 2afd8f2c..31d6f892 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Exception/PassportException.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Exception/PassportException.cs @@ -21,16 +21,16 @@ public enum PassportErrorType public class PassportException : Exception { - public Nullable Type; + public PassportErrorType? Type; - public PassportException(string message, Nullable type = null) : base(message) + public PassportException(string message, PassportErrorType? type = null) : base(message) { - this.Type = type; + Type = type; } /** * The error message for api requests via axios that fail due to network connectivity is "Network Error". - * This isn't the most reliable way to determine connectivity but it is currently the best we have. + * This isn't the most reliable way to determine connectivity but it is currently the best we have. */ public bool IsNetworkError() { diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/ConfirmCodeRequest.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/ConfirmCodeRequest.cs index afc5c075..77a6929b 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/ConfirmCodeRequest.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/ConfirmCodeRequest.cs @@ -9,5 +9,4 @@ internal class ConfirmCodeRequest public int interval; public long? timeoutMs; } -} - +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/ConnectPKCERequest.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/ConnectPKCERequest.cs index cafaa4af..0d570474 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/ConnectPKCERequest.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/ConnectPKCERequest.cs @@ -2,12 +2,10 @@ namespace Immutable.Passport.Model { - [Serializable] internal class ConnectPKCERequest { public string authorizationCode; public string state; } -} - +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/InitRequest.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/InitRequest.cs index 61ceb5ce..08b15800 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/InitRequest.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/InitRequest.cs @@ -1,5 +1,4 @@ using System; -using Immutable.Passport.Model; namespace Immutable.Passport.Model { @@ -21,4 +20,4 @@ internal class InitRequest public string logoutRedirectUri; public VersionInfo engineVersion; } -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/NftTransferDetails.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/NftTransferDetails.cs index 2bd1b3ee..9e829209 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/NftTransferDetails.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/NftTransferDetails.cs @@ -9,6 +9,7 @@ public class NftTransferDetails * Ethereum address of the receiving user */ public string receiver; + /** * The token ID */ @@ -23,7 +24,7 @@ public NftTransferDetails( string receiver, string tokenId, string tokenAddress - ) + ) { this.receiver = receiver; this.tokenId = tokenId; diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/SignPayloadRequest.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/SignPayloadRequest.cs index b88fbdd2..fc9272fa 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/SignPayloadRequest.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/SignPayloadRequest.cs @@ -3,9 +3,9 @@ namespace Immutable.Passport.Model { /// - /// Represents the payload for signing an EIP-712 typed data message using ZK-EVM. - /// This payload consists of three components: domain, types, and message. - /// Each component is a JSON string that conforms to the EIP-712 standard. + /// Represents the payload for signing an EIP-712 typed data message using ZK-EVM. + /// This payload consists of three components: domain, types, and message. + /// Each component is a JSON string that conforms to the EIP-712 standard. /// [Serializable] public class SignPayloadRequest diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/TrackData.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/TrackData.cs index 6a8cc805..3884363e 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/TrackData.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/TrackData.cs @@ -9,4 +9,4 @@ internal class TrackData public string eventName; public string properties; } -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/UnsignedTransferRequest.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/UnsignedTransferRequest.cs index c222e91f..17c28d99 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/UnsignedTransferRequest.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/UnsignedTransferRequest.cs @@ -36,7 +36,7 @@ public UnsignedTransferRequest( string receiver, string tokenId = null, string tokenAddress = null - ) + ) { this.type = type; this.amount = amount; diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/VersionInfo.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/VersionInfo.cs index b743e607..b11e1044 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/VersionInfo.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Request/VersionInfo.cs @@ -12,4 +12,4 @@ public class VersionInfo public string platformVersion; public string deviceModel; } -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/CreateBatchTransferResponse.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/CreateBatchTransferResponse.cs index 80ba22b8..21ad72c0 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/CreateBatchTransferResponse.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/CreateBatchTransferResponse.cs @@ -4,4 +4,4 @@ public class CreateBatchTransferResponse { public long[] transfer_ids; } -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/CreateTransferResponseV1.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/CreateTransferResponseV1.cs index 745e7357..9d3835be 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/CreateTransferResponseV1.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/CreateTransferResponseV1.cs @@ -2,9 +2,8 @@ namespace Immutable.Passport.Model { public class CreateTransferResponseV1 { - public string sent_signature; - public string receiver; + public string sent_signature; public string status; @@ -12,4 +11,4 @@ public class CreateTransferResponseV1 public long transfer_id; } -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/DeviceConnectResponse.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/DeviceConnectResponse.cs index 5581fe71..d9476dc4 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/DeviceConnectResponse.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/DeviceConnectResponse.cs @@ -6,7 +6,7 @@ public class DeviceConnectResponse : BrowserResponse { public string code; public string deviceCode; - public string url; public int interval; + public string url; } -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/TransactionReceiptResponse.cs b/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/TransactionReceiptResponse.cs index 065c43bf..558f3d32 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/TransactionReceiptResponse.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/Model/Response/TransactionReceiptResponse.cs @@ -21,14 +21,14 @@ public class TransactionReceiptResponse public string logsBloom; /// - /// Possible reponses: - /// - /// - /// Success: 1 or 0x1 - /// - /// - /// Failure: 0 or 0x0 - /// + /// Possible reponses: + /// + /// + /// Success: 1 or 0x1 + /// + /// + /// Failure: 0 or 0x0 + /// /// public string status; @@ -44,21 +44,21 @@ public class Log { public string address; - public string[] topics; - - public string data; + public string blockHash; public string blockNumber; - public string transactionHash; - - public string transactionIndex; - - public string blockHash; + public string data; public string logIndex; public bool removed; + + public string[] topics; + + public string transactionHash; + + public string transactionIndex; } } -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/PassportFunction.cs b/src/Packages/Passport/Runtime/Scripts/Private/PassportFunction.cs index 2bd25901..a3c3ff73 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/PassportFunction.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/PassportFunction.cs @@ -18,6 +18,7 @@ public static class PassportFunction public const string GET_EMAIL = "getEmail"; public const string GET_PASSPORT_ID = "getPassportId"; public const string GET_LINKED_ADDRESSES = "getLinkedAddresses"; + public static class IMX { public const string GET_ADDRESS = "getAddress"; @@ -38,4 +39,4 @@ public static class ZK_EVM public const string GET_BALANCE = "zkEvmGetBalance"; } } -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Private/PassportImpl.cs b/src/Packages/Passport/Runtime/Scripts/Private/PassportImpl.cs index ed20259b..a30f3223 100644 --- a/src/Packages/Passport/Runtime/Scripts/Private/PassportImpl.cs +++ b/src/Packages/Passport/Runtime/Scripts/Private/PassportImpl.cs @@ -1,13 +1,13 @@ -using System.Collections.Generic; using System; +using System.Collections.Generic; using System.Linq; -using UnityEngine; -using Immutable.Passport.Event; -using Immutable.Passport.Model; -using Immutable.Passport.Core; -using Immutable.Passport.Helpers; using Cysharp.Threading.Tasks; +using Immutable.Passport.Core; using Immutable.Passport.Core.Logging; +using Immutable.Passport.Event; +using Immutable.Passport.Helpers; +using Immutable.Passport.Model; +using UnityEngine; #if UNITY_ANDROID using UnityEngine.Android; #endif @@ -22,16 +22,16 @@ public class PassportImpl { private const string TAG = "[Passport Implementation]"; public readonly IBrowserCommunicationsManager communicationsManager; - private PassportAnalytics analytics = new PassportAnalytics(); + private readonly PassportAnalytics analytics = new(); // Used for device code auth private DeviceConnectResponse deviceConnectResponse; // Used for PKCE - private bool pkceLoginOnly = false; // Used to differentiate between a login and connect + private bool pkceLoginOnly; // Used to differentiate between a login and connect private UniTaskCompletionSource pkceCompletionSource; - private string redirectUri = null; - private string logoutRedirectUri = null; + private string redirectUri; + private string logoutRedirectUri; #if UNITY_ANDROID // Used for the PKCE callback @@ -40,7 +40,7 @@ public class PassportImpl #endif // Used to prevent calling login/connect functions multiple times - private bool isLoggedIn = false; + private bool isLoggedIn; public event OnAuthEventDelegate OnAuthEvent; @@ -56,8 +56,8 @@ public async UniTask Init(string clientId, string environment, string redirectUr this.logoutRedirectUri = logoutRedirectUri; #if (UNITY_ANDROID && !UNITY_EDITOR_WIN) || (UNITY_IPHONE && !UNITY_EDITOR_WIN) || UNITY_STANDALONE_OSX - this.communicationsManager.OnAuthPostMessage += OnDeepLinkActivated; - this.communicationsManager.OnPostMessageError += OnPostMessageError; + communicationsManager.OnAuthPostMessage += OnDeepLinkActivated; + communicationsManager.OnPostMessageError += OnPostMessageError; #endif var versionInfo = new VersionInfo @@ -73,7 +73,7 @@ public async UniTask Init(string clientId, string environment, string redirectUr string initRequest; if (redirectUri != null) { - InitRequestWithRedirectUri requestWithRedirectUri = new InitRequestWithRedirectUri() + var requestWithRedirectUri = new InitRequestWithRedirectUri { clientId = clientId, environment = environment, @@ -85,7 +85,7 @@ public async UniTask Init(string clientId, string environment, string redirectUr } else { - InitRequest request = new InitRequest() + var request = new InitRequest { clientId = clientId, environment = environment, @@ -95,60 +95,56 @@ public async UniTask Init(string clientId, string environment, string redirectUr initRequest = JsonUtility.ToJson(request); } - string response = await communicationsManager.Call(PassportFunction.INIT, initRequest); - BrowserResponse initResponse = response.OptDeserializeObject(); + var response = await communicationsManager.Call(PassportFunction.INIT, initRequest); + var initResponse = response.OptDeserializeObject(); if (initResponse.success == false) { - Track(PassportAnalytics.EventName.INIT_PASSPORT, success: false); + Track(PassportAnalytics.EventName.INIT_PASSPORT, false); throw new PassportException(initResponse.error ?? "Unable to initialise Passport"); } - else if (deeplink != null) + + if (deeplink != null) { OnDeepLinkActivated(deeplink); } - Track(PassportAnalytics.EventName.INIT_PASSPORT, success: true); + Track(PassportAnalytics.EventName.INIT_PASSPORT, true); } - public async UniTask Login(bool useCachedSession = false, Nullable timeoutMs = null) + public async UniTask Login(bool useCachedSession = false, long? timeoutMs = null) { - string functionName = "Login"; + var functionName = "Login"; if (useCachedSession) - { return await Relogin(); + try + { + Track(PassportAnalytics.EventName.START_LOGIN); + SendAuthEvent(PassportAuthEvent.LoggingIn); + + await InitialiseDeviceCodeAuth(functionName); + await ConfirmCode( + PassportAuthEvent.LoginOpeningBrowser, PassportAuthEvent.PendingBrowserLogin, functionName, + PassportFunction.LOGIN_CONFIRM_CODE, timeoutMs); + + Track(PassportAnalytics.EventName.COMPLETE_LOGIN, true); + SendAuthEvent(PassportAuthEvent.LoginSuccess); + isLoggedIn = true; + return true; } - else + catch (Exception ex) { - try - { - Track(PassportAnalytics.EventName.START_LOGIN); - SendAuthEvent(PassportAuthEvent.LoggingIn); - - await InitialiseDeviceCodeAuth(functionName); - await ConfirmCode( - PassportAuthEvent.LoginOpeningBrowser, PassportAuthEvent.PendingBrowserLogin, functionName, - PassportFunction.LOGIN_CONFIRM_CODE, timeoutMs); - - Track(PassportAnalytics.EventName.COMPLETE_LOGIN, success: true); - SendAuthEvent(PassportAuthEvent.LoginSuccess); - isLoggedIn = true; - return true; - } - catch (Exception ex) - { - Track(PassportAnalytics.EventName.COMPLETE_LOGIN, success: false); - SendAuthEvent(PassportAuthEvent.LoginFailed); - throw ex; - } + Track(PassportAnalytics.EventName.COMPLETE_LOGIN, false); + SendAuthEvent(PassportAuthEvent.LoginFailed); + throw ex; } } /// - /// Attempts to re-login using saved credentials. + /// Attempts to re-login using saved credentials. /// /// - /// Returns true if re-login is successful, otherwise false. + /// Returns true if re-login is successful, otherwise false. /// private async UniTask Relogin() { @@ -156,8 +152,8 @@ private async UniTask Relogin() { SendAuthEvent(PassportAuthEvent.ReloggingIn); - string callResponse = await communicationsManager.Call(PassportFunction.RELOGIN); - Track(PassportAnalytics.EventName.COMPLETE_RELOGIN, success: true); + var callResponse = await communicationsManager.Call(PassportFunction.RELOGIN); + Track(PassportAnalytics.EventName.COMPLETE_RELOGIN, true); SendAuthEvent(PassportAuthEvent.ReloginSuccess); isLoggedIn = true; @@ -167,63 +163,59 @@ private async UniTask Relogin() { // Log a warning if re-login fails. PassportLogger.Warn($"{TAG} Failed to login using saved credentials. " + - $"Please check if user has saved credentials first by calling HasCredentialsSaved() : {ex.Message}"); + $"Please check if user has saved credentials first by calling HasCredentialsSaved() : {ex.Message}"); isLoggedIn = false; } - Track(PassportAnalytics.EventName.COMPLETE_RELOGIN, success: false); + Track(PassportAnalytics.EventName.COMPLETE_RELOGIN, false); SendAuthEvent(PassportAuthEvent.ReloginFailed); return false; } - public async UniTask ConnectImx(bool useCachedSession = false, Nullable timeoutMs = null) + public async UniTask ConnectImx(bool useCachedSession = false, long? timeoutMs = null) { - string functionName = "ConnectImx"; + var functionName = "ConnectImx"; if (useCachedSession) { return await Reconnect(); } - else + + // If the user called Login before and then ConnectImx, there is no point triggering device flow again + var hasCredsSaved = await HasCredentialsSaved(); + if (hasCredsSaved) { - // If the user called Login before and then ConnectImx, there is no point triggering device flow again - bool hasCredsSaved = await HasCredentialsSaved(); - if (hasCredsSaved) - { - bool reconnected = await Reconnect(); - if (reconnected) - { - // Successfully reconnected - return reconnected; - } - // Otherwise fallback to device code flow - } + var reconnected = await Reconnect(); + if (reconnected) + // Successfully reconnected + return reconnected; + // Otherwise fallback to device code flow + } - try - { - Track(PassportAnalytics.EventName.START_CONNECT_IMX); - SendAuthEvent(PassportAuthEvent.ConnectingImx); - - await InitialiseDeviceCodeAuth(functionName); - await ConfirmCode( - PassportAuthEvent.ConnectImxOpeningBrowser, PassportAuthEvent.PendingBrowserLoginAndProviderSetup, - functionName, PassportFunction.CONNECT_CONFIRM_CODE, timeoutMs); - - Track(PassportAnalytics.EventName.COMPLETE_CONNECT_IMX, success: true); - SendAuthEvent(PassportAuthEvent.ConnectImxSuccess); - isLoggedIn = true; - return true; - } - catch (Exception ex) - { - Track(PassportAnalytics.EventName.COMPLETE_CONNECT_IMX, success: false); - SendAuthEvent(PassportAuthEvent.ConnectImxFailed); - throw ex; - } + try + { + Track(PassportAnalytics.EventName.START_CONNECT_IMX); + SendAuthEvent(PassportAuthEvent.ConnectingImx); + + await InitialiseDeviceCodeAuth(functionName); + await ConfirmCode( + PassportAuthEvent.ConnectImxOpeningBrowser, PassportAuthEvent.PendingBrowserLoginAndProviderSetup, + functionName, PassportFunction.CONNECT_CONFIRM_CODE, timeoutMs); + + Track(PassportAnalytics.EventName.COMPLETE_CONNECT_IMX, true); + SendAuthEvent(PassportAuthEvent.ConnectImxSuccess); + isLoggedIn = true; + return true; + } + catch (Exception ex) + { + Track(PassportAnalytics.EventName.COMPLETE_CONNECT_IMX, false); + SendAuthEvent(PassportAuthEvent.ConnectImxFailed); + throw ex; } } /// - /// Attempts to reconnect using saved credentials. + /// Attempts to reconnect using saved credentials. /// /// True if reconnect is successful, otherwise false. private async UniTask Reconnect() @@ -232,9 +224,9 @@ private async UniTask Reconnect() { SendAuthEvent(PassportAuthEvent.Reconnecting); - string callResponse = await communicationsManager.Call(PassportFunction.RECONNECT); + var callResponse = await communicationsManager.Call(PassportFunction.RECONNECT); - Track(PassportAnalytics.EventName.COMPLETE_RECONNECT, success: true); + Track(PassportAnalytics.EventName.COMPLETE_RECONNECT, true); SendAuthEvent(PassportAuthEvent.ReconnectSuccess); isLoggedIn = true; return true; @@ -243,46 +235,42 @@ private async UniTask Reconnect() { // Log a warning if reconnect fails. PassportLogger.Warn($"{TAG} Failed to connect using saved credentials. " + - $"Please check if user has saved credentials first by calling HasCredentialsSaved() : {ex.Message}"); + $"Please check if user has saved credentials first by calling HasCredentialsSaved() : {ex.Message}"); isLoggedIn = false; } - Track(PassportAnalytics.EventName.COMPLETE_RECONNECT, success: false); + Track(PassportAnalytics.EventName.COMPLETE_RECONNECT, false); SendAuthEvent(PassportAuthEvent.ReconnectFailed); return false; } private async UniTask InitialiseDeviceCodeAuth(string callingFunction) { - string callResponse = await communicationsManager.Call(PassportFunction.INIT_DEVICE_FLOW); + var callResponse = await communicationsManager.Call(PassportFunction.INIT_DEVICE_FLOW); deviceConnectResponse = callResponse.OptDeserializeObject(); - if (deviceConnectResponse != null && deviceConnectResponse.success == true) - { - return new ConnectResponse() + if (deviceConnectResponse != null && deviceConnectResponse.success) + return new ConnectResponse { url = deviceConnectResponse.url, code = deviceConnectResponse.code }; - } throw new PassportException( - deviceConnectResponse?.error ?? $"Something went wrong, please call {callingFunction} again", - PassportErrorType.AUTHENTICATION_ERROR - ); + deviceConnectResponse?.error ?? $"Something went wrong, please call {callingFunction} again", + PassportErrorType.AUTHENTICATION_ERROR + ); } private async UniTask ConfirmCode( PassportAuthEvent openingBrowserAuthEvent, PassportAuthEvent pendingAuthEvent, - string callingFunction, string functionToCall, Nullable timeoutMs = null) + string callingFunction, string functionToCall, long? timeoutMs = null) { if (deviceConnectResponse != null) { long intervalMs = deviceConnectResponse.interval * 1000; if (timeoutMs != null && timeoutMs < intervalMs) - { throw new ArgumentException($"timeoutMs should be longer than {intervalMs}ms"); - } // Open URL for user to confirm SendAuthEvent(openingBrowserAuthEvent); @@ -290,17 +278,17 @@ private async UniTask ConfirmCode( // Start polling for token SendAuthEvent(pendingAuthEvent); - ConfirmCodeRequest request = new ConfirmCodeRequest() + var request = new ConfirmCodeRequest { deviceCode = deviceConnectResponse.deviceCode, interval = deviceConnectResponse.interval, timeoutMs = timeoutMs }; - string callResponse = await communicationsManager.Call( + var callResponse = await communicationsManager.Call( functionToCall, JsonUtility.ToJson(request), - ignoreTimeout: timeoutMs == null, + timeoutMs == null, timeoutMs); } else @@ -316,21 +304,13 @@ public async void OnDeepLinkActivated(string url) { PassportLogger.Info($"{TAG} Received deeplink URL: {url}"); - Uri uri = new Uri(url); - string domain = $"{uri.Scheme}://{uri.Host}{uri.AbsolutePath}"; - if (domain.EndsWith("/")) - { - domain = domain.Remove(domain.Length - 1); - } + var uri = new Uri(url); + var domain = $"{uri.Scheme}://{uri.Host}{uri.AbsolutePath}"; + if (domain.EndsWith("/")) domain = domain.Remove(domain.Length - 1); if (domain.Equals(logoutRedirectUri)) - { HandleLogoutPKCESuccess(); - } - else if (domain.Equals(redirectUri)) - { - await CompleteLoginPKCEFlow(url); - } + else if (domain.Equals(redirectUri)) await CompleteLoginPKCEFlow(url); } catch (Exception ex) { @@ -345,7 +325,7 @@ public UniTask LoginPKCE() Track(PassportAnalytics.EventName.START_LOGIN_PKCE); SendAuthEvent(PassportAuthEvent.LoggingInPKCE); - UniTaskCompletionSource task = new UniTaskCompletionSource(); + var task = new UniTaskCompletionSource(); pkceCompletionSource = task; pkceLoginOnly = true; _ = LaunchAuthUrl(); @@ -353,10 +333,10 @@ public UniTask LoginPKCE() } catch (Exception ex) { - string errorMessage = $"Failed to log in using PKCE flow: {ex.Message}"; + var errorMessage = $"Failed to log in using PKCE flow: {ex.Message}"; PassportLogger.Error($"{TAG} {errorMessage}"); - Track(PassportAnalytics.EventName.COMPLETE_LOGIN_PKCE, success: false); + Track(PassportAnalytics.EventName.COMPLETE_LOGIN_PKCE, false); SendAuthEvent(PassportAuthEvent.LoginPKCEFailed); throw new PassportException(errorMessage, PassportErrorType.AUTHENTICATION_ERROR); } @@ -368,7 +348,7 @@ public UniTask ConnectImxPKCE() { Track(PassportAnalytics.EventName.START_CONNECT_IMX_PKCE); SendAuthEvent(PassportAuthEvent.ConnectingImxPKCE); - UniTaskCompletionSource task = new UniTaskCompletionSource(); + var task = new UniTaskCompletionSource(); pkceCompletionSource = task; pkceLoginOnly = false; _ = LaunchAuthUrl(); @@ -376,10 +356,10 @@ public UniTask ConnectImxPKCE() } catch (Exception ex) { - string errorMessage = $"Failed to connect using PKCE flow: {ex.Message}"; + var errorMessage = $"Failed to connect using PKCE flow: {ex.Message}"; PassportLogger.Error($"{TAG} {errorMessage}"); - Track(PassportAnalytics.EventName.COMPLETE_CONNECT_IMX_PKCE, success: false); + Track(PassportAnalytics.EventName.COMPLETE_CONNECT_IMX_PKCE, false); SendAuthEvent(PassportAuthEvent.ConnectImxPKCEFailed); throw new PassportException(errorMessage, PassportErrorType.AUTHENTICATION_ERROR); } @@ -389,26 +369,26 @@ private async UniTask LaunchAuthUrl() { try { - string callResponse = await communicationsManager.Call(PassportFunction.GET_PKCE_AUTH_URL); - StringResponse response = callResponse.OptDeserializeObject(); + var callResponse = await communicationsManager.Call(PassportFunction.GET_PKCE_AUTH_URL); + var response = callResponse.OptDeserializeObject(); - if (response != null && response.success == true && response.result != null) + if (response != null && response.success && response.result != null) { - string url = response.result.Replace(" ", "+"); + var url = response.result.Replace(" ", "+"); #if UNITY_ANDROID && !UNITY_EDITOR loginPKCEUrl = url; SendAuthEvent(pkceLoginOnly ? PassportAuthEvent.LoginPKCELaunchingCustomTabs : PassportAuthEvent.ConnectImxPKCELaunchingCustomTabs); LaunchAndroidUrl(url); #else - SendAuthEvent(pkceLoginOnly ? PassportAuthEvent.LoginPKCEOpeningWebView : PassportAuthEvent.ConnectImxPKCEOpeningWebView); + SendAuthEvent(pkceLoginOnly + ? PassportAuthEvent.LoginPKCEOpeningWebView + : PassportAuthEvent.ConnectImxPKCEOpeningWebView); communicationsManager.LaunchAuthURL(url, redirectUri); #endif return; } - else - { - PassportLogger.Error($"{TAG} Failed to get PKCE Auth URL"); - } + + PassportLogger.Error($"{TAG} Failed to get PKCE Auth URL"); } catch (Exception e) { @@ -429,18 +409,24 @@ public async UniTask CompleteLoginPKCEFlow(string uriString) #endif try { - SendAuthEvent(pkceLoginOnly ? PassportAuthEvent.CompletingLoginPKCE : PassportAuthEvent.CompletingConnectImxPKCE); - Uri uri = new Uri(uriString); - string state = uri.GetQueryParameter("state"); - string authCode = uri.GetQueryParameter("code"); + SendAuthEvent(pkceLoginOnly + ? PassportAuthEvent.CompletingLoginPKCE + : PassportAuthEvent.CompletingConnectImxPKCE); + var uri = new Uri(uriString); + var state = uri.GetQueryParameter("state"); + var authCode = uri.GetQueryParameter("code"); - if (String.IsNullOrEmpty(state) || String.IsNullOrEmpty(authCode)) + if (string.IsNullOrEmpty(state) || string.IsNullOrEmpty(authCode)) { Track( - pkceLoginOnly ? PassportAnalytics.EventName.COMPLETE_LOGIN_PKCE : PassportAnalytics.EventName.COMPLETE_CONNECT_IMX_PKCE, - success: false + pkceLoginOnly + ? PassportAnalytics.EventName.COMPLETE_LOGIN_PKCE + : PassportAnalytics.EventName.COMPLETE_CONNECT_IMX_PKCE, + false ); - SendAuthEvent(pkceLoginOnly ? PassportAuthEvent.LoginPKCEFailed : PassportAuthEvent.ConnectImxPKCEFailed); + SendAuthEvent(pkceLoginOnly + ? PassportAuthEvent.LoginPKCEFailed + : PassportAuthEvent.ConnectImxPKCEFailed); await UniTask.SwitchToMainThread(); TrySetPKCEException(new PassportException( "Uri was missing state and/or code. Please call ConnectImxPKCE() again", @@ -449,27 +435,31 @@ public async UniTask CompleteLoginPKCEFlow(string uriString) } else { - ConnectPKCERequest request = new ConnectPKCERequest() + var request = new ConnectPKCERequest { authorizationCode = authCode, state = state }; - string callResponse = await communicationsManager.Call( - pkceLoginOnly ? PassportFunction.LOGIN_PKCE : PassportFunction.CONNECT_PKCE, - JsonUtility.ToJson(request) - ); + var callResponse = await communicationsManager.Call( + pkceLoginOnly ? PassportFunction.LOGIN_PKCE : PassportFunction.CONNECT_PKCE, + JsonUtility.ToJson(request) + ); - BrowserResponse response = callResponse.OptDeserializeObject(); + var response = callResponse.OptDeserializeObject(); await UniTask.SwitchToMainThread(); if (response != null && response.success != true) { Track( - pkceLoginOnly ? PassportAnalytics.EventName.COMPLETE_LOGIN_PKCE : PassportAnalytics.EventName.COMPLETE_CONNECT_IMX_PKCE, - success: false + pkceLoginOnly + ? PassportAnalytics.EventName.COMPLETE_LOGIN_PKCE + : PassportAnalytics.EventName.COMPLETE_CONNECT_IMX_PKCE, + false ); - SendAuthEvent(pkceLoginOnly ? PassportAuthEvent.LoginPKCEFailed : PassportAuthEvent.ConnectImxPKCEFailed); + SendAuthEvent(pkceLoginOnly + ? PassportAuthEvent.LoginPKCEFailed + : PassportAuthEvent.ConnectImxPKCEFailed); TrySetPKCEException(new PassportException( response.error ?? "Something went wrong, please call ConnectImxPKCE() again", PassportErrorType.AUTHENTICATION_ERROR @@ -477,16 +467,17 @@ public async UniTask CompleteLoginPKCEFlow(string uriString) } else { - if (!isLoggedIn) - { - TrySetPKCEResult(true); - } + if (!isLoggedIn) TrySetPKCEResult(true); Track( - pkceLoginOnly ? PassportAnalytics.EventName.COMPLETE_LOGIN_PKCE : PassportAnalytics.EventName.COMPLETE_CONNECT_IMX_PKCE, - success: true + pkceLoginOnly + ? PassportAnalytics.EventName.COMPLETE_LOGIN_PKCE + : PassportAnalytics.EventName.COMPLETE_CONNECT_IMX_PKCE, + true ); - SendAuthEvent(pkceLoginOnly ? PassportAuthEvent.LoginPKCESuccess : PassportAuthEvent.ConnectImxPKCESuccess); + SendAuthEvent(pkceLoginOnly + ? PassportAuthEvent.LoginPKCESuccess + : PassportAuthEvent.ConnectImxPKCESuccess); isLoggedIn = true; } } @@ -494,10 +485,13 @@ public async UniTask CompleteLoginPKCEFlow(string uriString) catch (Exception ex) { Track( - pkceLoginOnly ? PassportAnalytics.EventName.COMPLETE_LOGIN_PKCE : PassportAnalytics.EventName.COMPLETE_CONNECT_IMX_PKCE, - success: false + pkceLoginOnly + ? PassportAnalytics.EventName.COMPLETE_LOGIN_PKCE + : PassportAnalytics.EventName.COMPLETE_CONNECT_IMX_PKCE, + false ); - SendAuthEvent(pkceLoginOnly ? PassportAuthEvent.LoginPKCEFailed : PassportAuthEvent.ConnectImxPKCEFailed); + SendAuthEvent( + pkceLoginOnly ? PassportAuthEvent.LoginPKCEFailed : PassportAuthEvent.ConnectImxPKCEFailed); // Ensure any failure results in completing the flow regardless. TrySetPKCEException(ex); } @@ -532,16 +526,11 @@ public void OnDeeplinkResult(string url) public async UniTask GetLogoutUrl() { - string response = await communicationsManager.Call(PassportFunction.LOGOUT); - string logoutUrl = response.GetStringResult(); + var response = await communicationsManager.Call(PassportFunction.LOGOUT); + var logoutUrl = response.GetStringResult(); if (string.IsNullOrEmpty(logoutUrl)) - { throw new PassportException("Failed to get logout URL", PassportErrorType.AUTHENTICATION_ERROR); - } - else - { - return response.GetStringResult(); - } + return response.GetStringResult(); } public async UniTask Logout(bool hardLogout = true) @@ -550,22 +539,19 @@ public async UniTask Logout(bool hardLogout = true) { SendAuthEvent(PassportAuthEvent.LoggingOut); - string logoutUrl = await GetLogoutUrl(); - if (hardLogout) - { - OpenUrl(logoutUrl); - } + var logoutUrl = await GetLogoutUrl(); + if (hardLogout) OpenUrl(logoutUrl); - Track(PassportAnalytics.EventName.COMPLETE_LOGOUT, success: true); + Track(PassportAnalytics.EventName.COMPLETE_LOGOUT, true); SendAuthEvent(PassportAuthEvent.LogoutSuccess); isLoggedIn = false; } catch (Exception ex) { - string errorMessage = $"Failed to log out: {ex.Message}"; + var errorMessage = $"Failed to log out: {ex.Message}"; PassportLogger.Error($"{TAG} {errorMessage}"); - Track(PassportAnalytics.EventName.COMPLETE_LOGOUT, success: false); + Track(PassportAnalytics.EventName.COMPLETE_LOGOUT, false); SendAuthEvent(PassportAuthEvent.LogoutFailed); throw new PassportException(errorMessage, PassportErrorType.AUTHENTICATION_ERROR); } @@ -577,17 +563,17 @@ public UniTask LogoutPKCE(bool hardLogout = true) { SendAuthEvent(PassportAuthEvent.LoggingOutPKCE); - UniTaskCompletionSource task = new UniTaskCompletionSource(); + var task = new UniTaskCompletionSource(); pkceCompletionSource = task; LaunchLogoutPKCEUrl(hardLogout); return task.Task; } catch (Exception ex) { - string errorMessage = $"Failed to log out: {ex.Message}"; + var errorMessage = $"Failed to log out: {ex.Message}"; PassportLogger.Error($"{TAG} {errorMessage}"); - Track(PassportAnalytics.EventName.COMPLETE_LOGOUT_PKCE, success: false); + Track(PassportAnalytics.EventName.COMPLETE_LOGOUT_PKCE, false); SendAuthEvent(PassportAuthEvent.LogoutPKCEFailed); throw new PassportException(errorMessage, PassportErrorType.AUTHENTICATION_ERROR); } @@ -596,11 +582,8 @@ public UniTask LogoutPKCE(bool hardLogout = true) private async void HandleLogoutPKCESuccess() { await UniTask.SwitchToMainThread(); - if (isLoggedIn) - { - TrySetPKCEResult(true); - } - Track(PassportAnalytics.EventName.COMPLETE_LOGOUT_PKCE, success: true); + if (isLoggedIn) TrySetPKCEResult(true); + Track(PassportAnalytics.EventName.COMPLETE_LOGOUT_PKCE, true); SendAuthEvent(PassportAuthEvent.LogoutPKCESuccess); isLoggedIn = false; pkceCompletionSource = null; @@ -608,7 +591,7 @@ private async void HandleLogoutPKCESuccess() private async void LaunchLogoutPKCEUrl(bool hardLogout) { - string logoutUrl = await GetLogoutUrl(); + var logoutUrl = await GetLogoutUrl(); if (hardLogout) { #if UNITY_ANDROID && !UNITY_EDITOR @@ -628,14 +611,14 @@ public async UniTask HasCredentialsSaved() try { SendAuthEvent(PassportAuthEvent.CheckingForSavedCredentials); - string accessToken = await GetAccessToken(); - string idToken = await GetIdToken(); + var accessToken = await GetAccessToken(); + var idToken = await GetIdToken(); SendAuthEvent(PassportAuthEvent.CheckForSavedCredentialsSuccess); return accessToken != null && idToken != null; } catch (Exception ex) { - string errorMessage = $"Failed to check if there are credentials saved: {ex.Message}"; + var errorMessage = $"Failed to check if there are credentials saved: {ex.Message}"; PassportLogger.Debug($"{TAG} {errorMessage}"); SendAuthEvent(PassportAuthEvent.CheckForSavedCredentialsFailed); return false; @@ -644,66 +627,66 @@ public async UniTask HasCredentialsSaved() public async UniTask GetAddress() { - string response = await communicationsManager.Call(PassportFunction.IMX.GET_ADDRESS); + var response = await communicationsManager.Call(PassportFunction.IMX.GET_ADDRESS); return response.GetStringResult(); } public async UniTask IsRegisteredOffchain() { - string response = await communicationsManager.Call(PassportFunction.IMX.IS_REGISTERED_OFFCHAIN); + var response = await communicationsManager.Call(PassportFunction.IMX.IS_REGISTERED_OFFCHAIN); return response.GetBoolResponse() ?? false; } public async UniTask RegisterOffchain() { - string callResponse = await communicationsManager.Call(PassportFunction.IMX.REGISTER_OFFCHAIN); + var callResponse = await communicationsManager.Call(PassportFunction.IMX.REGISTER_OFFCHAIN); return callResponse.OptDeserializeObject(); } public async UniTask GetEmail() { - string response = await communicationsManager.Call(PassportFunction.GET_EMAIL); + var response = await communicationsManager.Call(PassportFunction.GET_EMAIL); return response.GetStringResult(); } public async UniTask GetPassportId() { - string response = await communicationsManager.Call(PassportFunction.GET_PASSPORT_ID); + var response = await communicationsManager.Call(PassportFunction.GET_PASSPORT_ID); return response.GetStringResult(); } public async UniTask GetAccessToken() { - string response = await communicationsManager.Call(PassportFunction.GET_ACCESS_TOKEN); + var response = await communicationsManager.Call(PassportFunction.GET_ACCESS_TOKEN); return response.GetStringResult(); } public async UniTask GetIdToken() { - string response = await communicationsManager.Call(PassportFunction.GET_ID_TOKEN); + var response = await communicationsManager.Call(PassportFunction.GET_ID_TOKEN); return response.GetStringResult(); } public async UniTask> GetLinkedAddresses() { - string response = await communicationsManager.Call(PassportFunction.GET_LINKED_ADDRESSES); - string[] addresses = response.GetStringListResult(); + var response = await communicationsManager.Call(PassportFunction.GET_LINKED_ADDRESSES); + var addresses = response.GetStringListResult(); return addresses != null ? addresses.ToList() : new List(); } // Imx public async UniTask ImxTransfer(UnsignedTransferRequest request) { - string json = JsonUtility.ToJson(request); - string callResponse = await communicationsManager.Call(PassportFunction.IMX.TRANSFER, json); + var json = JsonUtility.ToJson(request); + var callResponse = await communicationsManager.Call(PassportFunction.IMX.TRANSFER, json); return callResponse.OptDeserializeObject(); } public async UniTask ImxBatchNftTransfer(NftTransferDetails[] details) { - string json = details.ToJson(); - string callResponse = await communicationsManager.Call(PassportFunction.IMX.BATCH_NFT_TRANSFER, json); + var json = details.ToJson(); + var callResponse = await communicationsManager.Call(PassportFunction.IMX.BATCH_NFT_TRANSFER, json); return callResponse.OptDeserializeObject(); } @@ -718,79 +701,73 @@ private string SerialiseTransactionRequest(TransactionRequest request) string json; // Nulls are serialised as empty strings when using JsonUtility // so we need to use another model that doesn't have the 'data' field instead - if (String.IsNullOrEmpty(request.data)) - { - json = JsonUtility.ToJson(new TransactionRequestNoData() + if (string.IsNullOrEmpty(request.data)) + json = JsonUtility.ToJson(new TransactionRequestNoData { to = request.to, value = request.value }); - } else - { json = JsonUtility.ToJson(request); - } return json; } public async UniTask ZkEvmSendTransaction(TransactionRequest request) { - string json = SerialiseTransactionRequest(request); - string callResponse = await communicationsManager.Call(PassportFunction.ZK_EVM.SEND_TRANSACTION, json); + var json = SerialiseTransactionRequest(request); + var callResponse = await communicationsManager.Call(PassportFunction.ZK_EVM.SEND_TRANSACTION, json); return callResponse.GetStringResult(); } - public async UniTask ZkEvmSendTransactionWithConfirmation(TransactionRequest request) + public async UniTask ZkEvmSendTransactionWithConfirmation( + TransactionRequest request) { - string json = SerialiseTransactionRequest(request); - string callResponse = await communicationsManager.Call(PassportFunction.ZK_EVM.SEND_TRANSACTION_WITH_CONFIRMATION, json); + var json = SerialiseTransactionRequest(request); + var callResponse = + await communicationsManager.Call(PassportFunction.ZK_EVM.SEND_TRANSACTION_WITH_CONFIRMATION, json); return callResponse.OptDeserializeObject(); } public async UniTask ZkEvmSignTypedDataV4(string payload) { - string callResponse = await communicationsManager.Call(PassportFunction.ZK_EVM.SIGN_TYPED_DATA_v4, payload); + var callResponse = await communicationsManager.Call(PassportFunction.ZK_EVM.SIGN_TYPED_DATA_v4, payload); return callResponse.GetStringResult(); } public async UniTask ZkEvmGetTransactionReceipt(string hash) { - string json = JsonUtility.ToJson(new TransactionReceiptRequest() + var json = JsonUtility.ToJson(new TransactionReceiptRequest { txHash = hash }); - string jsonResponse = await communicationsManager.Call(PassportFunction.ZK_EVM.GET_TRANSACTION_RECEIPT, json); + var jsonResponse = await communicationsManager.Call(PassportFunction.ZK_EVM.GET_TRANSACTION_RECEIPT, json); return jsonResponse.OptDeserializeObject(); } public async UniTask> ZkEvmRequestAccounts() { - string callResponse = await communicationsManager.Call(PassportFunction.ZK_EVM.REQUEST_ACCOUNTS); - RequestAccountsResponse accountsResponse = callResponse.OptDeserializeObject(); + var callResponse = await communicationsManager.Call(PassportFunction.ZK_EVM.REQUEST_ACCOUNTS); + var accountsResponse = callResponse.OptDeserializeObject(); return accountsResponse != null ? accountsResponse.accounts.ToList() : new List(); } public async UniTask ZkEvmGetBalance(string address, string blockNumberOrTag) { - string json = JsonUtility.ToJson(new GetBalanceRequest() + var json = JsonUtility.ToJson(new GetBalanceRequest { address = address, blockNumberOrTag = blockNumberOrTag }); - string callResponse = await communicationsManager.Call(PassportFunction.ZK_EVM.GET_BALANCE, json); + var callResponse = await communicationsManager.Call(PassportFunction.ZK_EVM.GET_BALANCE, json); return callResponse.GetStringResult() ?? "0x0"; } private async void OnPostMessageError(string id, string message) { if (id == "CallFromAuthCallbackError" && pkceCompletionSource != null) - { await CallFromAuthCallbackError(id, message); - } else - { PassportLogger.Error($"{TAG} id: {id} err: {message}"); - } } private async UniTask CallFromAuthCallbackError(string id, string message) @@ -818,48 +795,33 @@ private void TrySetPKCEResult(bool result) { PassportLogger.Debug($"{TAG} Trying to set PKCE result to {result}..."); if (pkceCompletionSource != null) - { pkceCompletionSource.TrySetResult(result); - } else - { PassportLogger.Error($"{TAG} PKCE completed with {result} but unable to bind result"); - } } private void TrySetPKCEException(Exception exception) { PassportLogger.Debug($"{TAG} Trying to set PKCE exception..."); if (pkceCompletionSource != null) - { pkceCompletionSource.TrySetException(exception); - } else - { PassportLogger.Error($"{TAG} {exception.Message}"); - } } private void TrySetPKCECanceled() { PassportLogger.Debug($"{TAG} Trying to set PKCE canceled..."); if (pkceCompletionSource != null) - { pkceCompletionSource.TrySetCanceled(); - } else - { PassportLogger.Warn($"{TAG} PKCE canceled"); - } } private void SendAuthEvent(PassportAuthEvent authEvent) { PassportLogger.Debug($"{TAG} Send auth event: {authEvent}"); - if (OnAuthEvent != null) - { - OnAuthEvent.Invoke(authEvent); - } + if (OnAuthEvent != null) OnAuthEvent.Invoke(authEvent); } protected virtual void OpenUrl(string url) @@ -889,7 +851,8 @@ public void ClearStorage() } #endif - protected virtual async void Track(string eventName, bool? success = null, Dictionary properties = null) + protected virtual async void Track(string eventName, bool? success = null, + Dictionary properties = null) { await analytics.Track(communicationsManager, eventName, success, properties); } diff --git a/src/Packages/Passport/Runtime/Scripts/Public/Immutable.Passport.Runtime.asmdef b/src/Packages/Passport/Runtime/Scripts/Public/Immutable.Passport.Runtime.asmdef index 3571bee6..78852798 100644 --- a/src/Packages/Passport/Runtime/Scripts/Public/Immutable.Passport.Runtime.asmdef +++ b/src/Packages/Passport/Runtime/Scripts/Public/Immutable.Passport.Runtime.asmdef @@ -1,30 +1,30 @@ { - "name": "Immutable.Passport.Runtime.Public", - "rootNamespace": "Immutable.Passport", - "references": [ - "VoltstroStudios.UnityWebBrowser", - "UniTask", - "Immutable.Browser.Core", - "Immutable.Browser.Gree", - "Immutable.Passport.Runtime.Private", - "Immutable.Passport.Core.Logging" - ], - "includePlatforms": [ - "Android", - "Editor", - "iOS", - "macOSStandalone", - "WindowsStandalone64" - ], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": true, - "precompiledReferences": [ - "Newtonsoft.Json.dll", - "VoltstroStudios.UnityWebBrowser.Shared.dll" - ], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "Immutable.Passport.Runtime.Public", + "rootNamespace": "Immutable.Passport", + "references": [ + "VoltstroStudios.UnityWebBrowser", + "UniTask", + "Immutable.Browser.Core", + "Immutable.Browser.Gree", + "Immutable.Passport.Runtime.Private", + "Immutable.Passport.Core.Logging" + ], + "includePlatforms": [ + "Android", + "Editor", + "iOS", + "macOSStandalone", + "WindowsStandalone64" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [ + "Newtonsoft.Json.dll", + "VoltstroStudios.UnityWebBrowser.Shared.dll" + ], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/Scripts/Public/Passport.cs b/src/Packages/Passport/Runtime/Scripts/Public/Passport.cs index 1b09d876..bf1a85ff 100644 --- a/src/Packages/Passport/Runtime/Scripts/Public/Passport.cs +++ b/src/Packages/Passport/Runtime/Scripts/Public/Passport.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; -using System; #if UNITY_STANDALONE_WIN || (UNITY_ANDROID && UNITY_EDITOR_WIN) || (UNITY_IPHONE && UNITY_EDITOR_WIN) #if !IMMUTABLE_CUSTOM_BROWSER using VoltstroStudios.UnityWebBrowser.Core; @@ -8,47 +6,49 @@ #elif (UNITY_ANDROID && !UNITY_EDITOR_WIN) || (UNITY_IPHONE && !UNITY_EDITOR_WIN) || UNITY_STANDALONE_OSX using Immutable.Browser.Gree; #endif -using Immutable.Passport.Event; +#if UNITY_EDITOR +using UnityEditor; +#endif +using System; +using System.Collections.Generic; +using Cysharp.Threading.Tasks; using Immutable.Browser.Core; -using Immutable.Passport.Model; using Immutable.Passport.Core; using Immutable.Passport.Core.Logging; -using Cysharp.Threading.Tasks; +using Immutable.Passport.Event; +using Immutable.Passport.Model; using UnityEngine; -#if UNITY_EDITOR -using UnityEditor; -#endif namespace Immutable.Passport { - public class Passport { private const string TAG = "[Passport]"; public static Passport Instance { get; private set; } - private PassportImpl passportImpl = null; + private PassportImpl passportImpl; private IWebBrowserClient webBrowserClient; // Keeps track of the latest received deeplink - private static string deeplink = null; - private static bool readySignalReceived = false; + private static string deeplink; + private static bool readySignalReceived; /// - /// Passport auth events + /// Passport auth events /// /// public event OnAuthEventDelegate OnAuthEvent; /// - /// The log level for the SDK. + /// The log level for the SDK. /// /// - /// The log level determines which messages are recorded based on their severity. The default value is . - /// - /// See for valid log levels and their meanings. - /// + /// The log level determines which messages are recorded based on their severity. The default value is + /// . + /// + /// See for valid log levels and their meanings. + /// /// public static LogLevel LogLevel { @@ -77,10 +77,8 @@ private Passport() // Check if there is a deep link URL provided on application start if (!string.IsNullOrEmpty(Application.absoluteURL)) - { // Handle the deep link if provided during a cold start OnDeepLinkActivated(Application.absoluteURL); - } #endif #if UNITY_EDITOR @@ -89,14 +87,23 @@ private Passport() } /// - /// Initialises Passport with the specified parameters. - /// This sets up the Passport instance, configures the web browser, and waits for the ready signal. + /// Initialises Passport with the specified parameters. + /// This sets up the Passport instance, configures the web browser, and waits for the ready signal. /// /// The client ID /// The environment to connect to - /// (Android, iOS, and macOS only) The URL where the browser will redirect after successful authentication. - /// (Android, iOS, and macOS only) The URL where the browser will redirect after logout is complete. - /// (Windows only) Timeout duration in milliseconds to wait for the default Windows browser engine to start. + /// + /// (Android, iOS, and macOS only) The URL where the browser will redirect after successful + /// authentication. + /// + /// + /// (Android, iOS, and macOS only) The URL where the browser will redirect after logout is + /// complete. + /// + /// + /// (Windows only) Timeout duration in milliseconds to wait for the default Windows + /// browser engine to start. + /// /// (Windows only) Custom Windows browser to use instead of the default browser in the SDK. public static UniTask Init( string clientId, @@ -124,35 +131,36 @@ public static UniTask Init( { // Wait for the ready signal PassportLogger.Info($"{TAG} Waiting for ready signal..."); - await UniTask.WaitUntil(() => readySignalReceived == true); + await UniTask.WaitUntil(() => readySignalReceived); }) .ContinueWith(async () => { - if (readySignalReceived == true) + if (readySignalReceived) { // Initialise Passport with provided parameters - await Instance.GetPassportImpl().Init(clientId, environment, redirectUri, logoutRedirectUri, deeplink); + await Instance.GetPassportImpl().Init(clientId, environment, redirectUri, logoutRedirectUri, + deeplink); return Instance; } - else - { - PassportLogger.Error($"{TAG} Failed to initialise Passport"); - throw new PassportException("Failed to initiliase Passport", PassportErrorType.INITALISATION_ERROR); - } + + PassportLogger.Error($"{TAG} Failed to initialise Passport"); + throw new PassportException("Failed to initiliase Passport", + PassportErrorType.INITALISATION_ERROR); }); } - else - { - // Return the existing instance if already initialised - readySignalReceived = true; - return UniTask.FromResult(Instance); - } + + // Return the existing instance if already initialised + readySignalReceived = true; + return UniTask.FromResult(Instance); } /// - /// Initialises the appropriate web browser and sets up browser communication. + /// Initialises the appropriate web browser and sets up browser communication. /// - /// (Windows only) Timeout duration in milliseconds to wait for the default Windows browser engine to start. + /// + /// (Windows only) Timeout duration in milliseconds to wait for the default Windows + /// browser engine to start. + /// /// (Windows only) Custom Windows browser to use instead of the default browser in the SDK. private async UniTask Initialise( #if UNITY_STANDALONE_WIN || (UNITY_ANDROID && UNITY_EDITOR_WIN) || (UNITY_IPHONE && UNITY_EDITOR_WIN) @@ -189,7 +197,7 @@ private async UniTask Initialise( #endif // Set up browser communication - BrowserCommunicationsManager communicationsManager = new BrowserCommunicationsManager(webBrowserClient); + var communicationsManager = new BrowserCommunicationsManager(webBrowserClient); // Mark ready when browser is initialised and game bridge file is loaded communicationsManager.OnReady += () => readySignalReceived = true; @@ -208,8 +216,8 @@ private async UniTask Initialise( } /// - /// Sets the timeout time for waiting for each call to respond (in milliseconds). - /// This only applies to functions that use the browser communications manager. + /// Sets the timeout time for waiting for each call to respond (in milliseconds). + /// This only applies to functions that use the browser communications manager. /// public void SetCallTimeout(int ms) { @@ -217,29 +225,42 @@ public void SetCallTimeout(int ms) } /// - /// Logs the user into Passport via device code auth. This will open the user's default browser and take them through Passport login. - /// If true, the saved access token or refresh token will be used to log the user in. If this fails, it will not fallback to device code auth. - /// (Optional) The maximum time, in milliseconds, the function is allowed to take before a TimeoutException is thrown. If not set, the function will wait indefinitely. + /// Logs the user into Passport via device code auth. This will open the user's default browser and take them through + /// Passport login. + /// + /// If true, the saved access token or refresh token will be used to log the user in. If + /// this fails, it will not fallback to device code auth. + /// + /// + /// (Optional) The maximum time, in milliseconds, the function is allowed to take before a + /// TimeoutException is thrown. If not set, the function will wait indefinitely. + /// /// - public async UniTask Login(bool useCachedSession = false, Nullable timeoutMs = null) + public async UniTask Login(bool useCachedSession = false, long? timeoutMs = null) { return await GetPassportImpl().Login(useCachedSession, timeoutMs); } /// - /// Logs the user into Passport via device code auth and sets up the Immutable X provider. This will open the user's - /// default browser and take them through Passport login. - /// If true, the saved access token or refresh token will be used to connect the user. If this fails, it will not fallback to device code auth. - /// (Optional) The maximum time, in milliseconds, the function is allowed to take before a TimeoutException is thrown. If not set, the function will wait indefinitely. + /// Logs the user into Passport via device code auth and sets up the Immutable X provider. This will open the user's + /// default browser and take them through Passport login. + /// + /// If true, the saved access token or refresh token will be used to connect the user. + /// If this fails, it will not fallback to device code auth. + /// + /// + /// (Optional) The maximum time, in milliseconds, the function is allowed to take before a + /// TimeoutException is thrown. If not set, the function will wait indefinitely. + /// /// - public async UniTask ConnectImx(bool useCachedSession = false, Nullable timeoutMs = null) + public async UniTask ConnectImx(bool useCachedSession = false, long? timeoutMs = null) { return await GetPassportImpl().ConnectImx(useCachedSession, timeoutMs); } #if (UNITY_ANDROID && !UNITY_EDITOR_WIN) || (UNITY_IPHONE && !UNITY_EDITOR_WIN) || UNITY_STANDALONE_OSX /// - /// Connects the user into Passport via PKCE auth. + /// Connects the user into Passport via PKCE auth. /// public async UniTask LoginPKCE() { @@ -247,10 +268,9 @@ public async UniTask LoginPKCE() } /// - /// Connects the user into Passport via PKCE auth and sets up the Immutable X provider. - /// - /// The user does not need to go through this flow if the saved access token is still valid or - /// the refresh token can be used to get a new access token. + /// Connects the user into Passport via PKCE auth and sets up the Immutable X provider. + /// The user does not need to go through this flow if the saved access token is still valid or + /// the refresh token can be used to get a new access token. /// public async UniTask ConnectImxPKCE() { @@ -259,10 +279,10 @@ public async UniTask ConnectImxPKCE() #endif /// - /// Gets the wallet address of the logged in user. - /// - /// The wallet address - /// + /// Gets the wallet address of the logged in user. + /// + /// The wallet address + /// /// public async UniTask GetAddress() { @@ -270,8 +290,8 @@ public async UniTask GetAddress() } /// - /// Logs the user out of Passport and removes any stored credentials. - /// Recommended to use when logging in using device auth flow - ConnectImx() + /// Logs the user out of Passport and removes any stored credentials. + /// Recommended to use when logging in using device auth flow - ConnectImx() /// /// If false, the user will not be logged out of Passport in the browser. The default is true. public async UniTask Logout(bool hardLogout = true) @@ -281,8 +301,8 @@ public async UniTask Logout(bool hardLogout = true) #if (UNITY_ANDROID && !UNITY_EDITOR_WIN) || (UNITY_IPHONE && !UNITY_EDITOR_WIN) || UNITY_STANDALONE_OSX /// - /// Logs the user out of Passport and removes any stored credentials. - /// Recommended to use when logging in using PKCE flow - ConnectImxPKCE() + /// Logs the user out of Passport and removes any stored credentials. + /// Recommended to use when logging in using PKCE flow - ConnectImxPKCE() /// /// If false, the user will not be logged out of Passport in the browser. The default is true. public async UniTask LogoutPKCE(bool hardLogout = true) @@ -292,10 +312,10 @@ public async UniTask LogoutPKCE(bool hardLogout = true) #endif /// - /// Checks if credentials exist but does not check if they're valid - /// - /// True if there are crendentials saved - /// + /// Checks if credentials exist but does not check if they're valid + /// + /// True if there are crendentials saved + /// /// public UniTask HasCredentialsSaved() { @@ -303,10 +323,10 @@ public UniTask HasCredentialsSaved() } /// - /// Checks if the user is registered off-chain - /// - /// True if the user is registered with Immutable X, false otherwise - /// + /// Checks if the user is registered off-chain + /// + /// True if the user is registered with Immutable X, false otherwise + /// /// public async UniTask IsRegisteredOffchain() { @@ -314,7 +334,7 @@ public async UniTask IsRegisteredOffchain() } /// - /// Registers the user to Immutable X if they are not already registered + /// Registers the user to Immutable X if they are not already registered /// public async UniTask RegisterOffchain() { @@ -322,34 +342,34 @@ public async UniTask RegisterOffchain() } /// - /// Retrieves the email address of the user whose credentials are currently stored. - /// - /// The email address - /// + /// Retrieves the email address of the user whose credentials are currently stored. + /// + /// The email address + /// /// public async UniTask GetEmail() { - string email = await GetPassportImpl().GetEmail(); + var email = await GetPassportImpl().GetEmail(); return email; } /// - /// Retrieves the Passport ID of the user whose credentials are currently stored. - /// - /// The Passport ID - /// + /// Retrieves the Passport ID of the user whose credentials are currently stored. + /// + /// The Passport ID + /// /// public async UniTask GetPassportId() { - string passportId = await GetPassportImpl().GetPassportId(); + var passportId = await GetPassportImpl().GetPassportId(); return passportId; } /// - /// Gets the currently saved access token without verifying its validity. - /// - /// The access token - /// + /// Gets the currently saved access token without verifying its validity. + /// + /// The access token + /// /// public UniTask GetAccessToken() { @@ -357,10 +377,10 @@ public UniTask GetAccessToken() } /// - /// Gets the currently saved ID token without verifying its validity. - /// - /// The ID token - /// + /// Gets the currently saved ID token without verifying its validity. + /// + /// The ID token + /// /// public UniTask GetIdToken() { @@ -368,11 +388,11 @@ public UniTask GetIdToken() } /// - /// Gets the list of external wallets the user has linked to their Passport account via the - /// Dashboard. - /// - /// Linked addresses - /// + /// Gets the list of external wallets the user has linked to their Passport account via the + /// Dashboard. + /// + /// Linked addresses + /// /// public async UniTask> GetLinkedAddresses() { @@ -380,31 +400,31 @@ public async UniTask> GetLinkedAddresses() } /// - /// Create a new transfer request with the given unsigned transfer request. - /// - /// The transfer response if successful - /// + /// Create a new transfer request with the given unsigned transfer request. + /// + /// The transfer response if successful + /// /// public async UniTask ImxTransfer(UnsignedTransferRequest request) { - CreateTransferResponseV1 response = await GetPassportImpl().ImxTransfer(request); + var response = await GetPassportImpl().ImxTransfer(request); return response; } /// - /// Create a new batch nft transfer request with the given transfer details. - /// - /// The transfer response if successful - /// + /// Create a new batch nft transfer request with the given transfer details. + /// + /// The transfer response if successful + /// /// public async UniTask ImxBatchNftTransfer(NftTransferDetails[] details) { - CreateBatchTransferResponse response = await GetPassportImpl().ImxBatchNftTransfer(details); + var response = await GetPassportImpl().ImxBatchNftTransfer(details); return response; } /// - /// Instantiates the zkEVM provider + /// Instantiates the zkEVM provider /// /// public async UniTask ConnectEvm() @@ -413,10 +433,10 @@ public async UniTask ConnectEvm() } /// - /// Sends a transaction to the network and signs it using the logged-in Passport account. - /// - /// The transaction hash, or the zero hash if the transaction is not yet available. - /// + /// Sends a transaction to the network and signs it using the logged-in Passport account. + /// + /// The transaction hash, or the zero hash if the transaction is not yet available. + /// /// public async UniTask ZkEvmSendTransaction(TransactionRequest request) { @@ -424,21 +444,23 @@ public async UniTask ZkEvmSendTransaction(TransactionRequest request) } /// - /// Similar to ZkEvmSendTransaction. Sends a transaction to the network, signs it using the logged-in Passport account, and waits for the transaction to be included in a block. - /// - /// The receipt of the transaction or null if it is still processing. - /// + /// Similar to ZkEvmSendTransaction. Sends a transaction to the network, signs it using the logged-in + /// Passport account, and waits for the transaction to be included in a block. + /// + /// The receipt of the transaction or null if it is still processing. + /// /// - public async UniTask ZkEvmSendTransactionWithConfirmation(TransactionRequest request) + public async UniTask ZkEvmSendTransactionWithConfirmation( + TransactionRequest request) { return await GetPassportImpl().ZkEvmSendTransactionWithConfirmation(request); } /// - /// Signs the given value and types for the given domain using the logged-in Passport account. - /// - /// The signed payload string - /// + /// Signs the given value and types for the given domain using the logged-in Passport account. + /// + /// The signed payload string + /// /// public async UniTask ZkEvmSignTypedDataV4(string payload) { @@ -446,10 +468,11 @@ public async UniTask ZkEvmSignTypedDataV4(string payload) } /// - /// Retrieves the transaction information of a given transaction hash. This function uses the Ethereum JSON-RPC eth_getTransactionReceipt method. - /// - /// The receipt of the transaction or null if it is still processing. - /// + /// Retrieves the transaction information of a given transaction hash. This function uses the Ethereum JSON-RPC + /// eth_getTransactionReceipt method. + /// + /// The receipt of the transaction or null if it is still processing. + /// /// public async UniTask ZkEvmGetTransactionReceipt(string hash) { @@ -457,10 +480,10 @@ public async UniTask ZkEvmGetTransactionReceipt(stri } /// - /// Returns a list of addresses owned by the user - /// - /// Addresses owned by the user - /// + /// Returns a list of addresses owned by the user + /// + /// Addresses owned by the user + /// /// public async UniTask> ZkEvmRequestAccounts() { @@ -468,12 +491,12 @@ public async UniTask> ZkEvmRequestAccounts() } /// - /// Returns the balance of the account of given address. + /// Returns the balance of the account of given address. /// /// Address to check for balance /// Integer block number, or the string "latest", "earliest" or "pending" /// - /// The balance in wei + /// The balance in wei /// public async UniTask ZkEvmGetBalance(string address, string blockNumberOrTag = "latest") { @@ -524,10 +547,7 @@ private static void SetDefaultWindowsBrowserLogLevel() private PassportImpl GetPassportImpl() { - if (passportImpl != null) - { - return passportImpl; - } + if (passportImpl != null) return passportImpl; throw new PassportException("Passport not initialised"); } @@ -535,22 +555,16 @@ private void OnDeepLinkActivated(string url) { deeplink = url; - if (passportImpl != null) - { - GetPassportImpl().OnDeepLinkActivated(url); - } + if (passportImpl != null) GetPassportImpl().OnDeepLinkActivated(url); } private void OnPassportAuthEvent(PassportAuthEvent authEvent) { - if (OnAuthEvent != null) - { - OnAuthEvent.Invoke(authEvent); - } + if (OnAuthEvent != null) OnAuthEvent.Invoke(authEvent); } /// - /// Handles clean-up when the application quits + /// Handles clean-up when the application quits /// private void OnQuit() { @@ -565,21 +579,18 @@ private void OnQuit() #if UNITY_EDITOR /// - /// Handles play mode state changes in the editor + /// Handles play mode state changes in the editor /// /// The current play mode state private void OnPlayModeStateChanged(PlayModeStateChange state) { // Dispose of all resources when exiting play mode - if (state == PlayModeStateChange.ExitingPlayMode) - { - DisposeAll(); - } + if (state == PlayModeStateChange.ExitingPlayMode) DisposeAll(); } #endif /// - /// Disposes of all resources and unsubscribes from events + /// Disposes of all resources and unsubscribes from events /// private void DisposeAll() { @@ -614,4 +625,4 @@ private void DisposeAll() readySignalReceived = false; } } -} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/ImmutableWebView.bundle/Contents/Info.plist b/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/ImmutableWebView.bundle/Contents/Info.plist index b53c3f00..3d5ee63f 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/ImmutableWebView.bundle/Contents/Info.plist +++ b/src/Packages/Passport/Runtime/ThirdParty/Gree/Assets/Plugins/ImmutableWebView.bundle/Contents/Info.plist @@ -1,48 +1,48 @@ - - BuildMachineOSBuild - 23G93 - CFBundleDevelopmentRegion - English - CFBundleExecutable - ImmutableWebView - CFBundleIdentifier - Immutable.Browser.WebView - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ImmutableWebView - CFBundlePackageType - BNDL - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleSupportedPlatforms - - MacOSX - - CFBundleVersion - 1 - DTCompiler - com.apple.compilers.llvm.clang.1_0 - DTPlatformBuild - 24A336 - DTPlatformName - macosx - DTPlatformVersion - 15.0 - DTSDKBuild - 24A336 - DTSDKName - macosx15.0 - DTXcode - 1600 - DTXcodeBuild - 16A242d - LSMinimumSystemVersion - 12.4 - + + BuildMachineOSBuild + 23G93 + CFBundleDevelopmentRegion + English + CFBundleExecutable + ImmutableWebView + CFBundleIdentifier + Immutable.Browser.WebView + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ImmutableWebView + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleSupportedPlatforms + + MacOSX + + CFBundleVersion + 1 + DTCompiler + com.apple.compilers.llvm.clang.1_0 + DTPlatformBuild + 24A336 + DTPlatformName + macosx + DTPlatformVersion + 15.0 + DTSDKBuild + 24A336 + DTSDKName + macosx15.0 + DTXcode + 1600 + DTXcodeBuild + 16A242d + LSMinimumSystemVersion + 12.4 + diff --git a/src/Packages/Passport/Runtime/ThirdParty/Gree/ImmutableWebView.asmdef b/src/Packages/Passport/Runtime/ThirdParty/Gree/ImmutableWebView.asmdef index fa0dcb48..dba87d58 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/Gree/ImmutableWebView.asmdef +++ b/src/Packages/Passport/Runtime/ThirdParty/Gree/ImmutableWebView.asmdef @@ -1,22 +1,22 @@ { - "name": "Immutable.Browser.Gree", - "rootNamespace": "Immutable.Browser.Gree", - "references": [ - "GUID:95d173a3e67b39d40803000ed05b79f4", - "GUID:a0996310e1aa34b7fbf14df5d255461d" - ], - "includePlatforms": [ - "Android", - "Editor", - "iOS", - "macOSStandalone" - ], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "Immutable.Browser.Gree", + "rootNamespace": "Immutable.Browser.Gree", + "references": [ + "GUID:95d173a3e67b39d40803000ed05b79f4", + "GUID:a0996310e1aa34b7fbf14df5d255461d" + ], + "includePlatforms": [ + "Android", + "Editor", + "iOS", + "macOSStandalone" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/ThirdParty/ImmutableBrowserCore/Immutable.Browser.Core.asmdef b/src/Packages/Passport/Runtime/ThirdParty/ImmutableBrowserCore/Immutable.Browser.Core.asmdef index b7969ec4..cc07b560 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/ImmutableBrowserCore/Immutable.Browser.Core.asmdef +++ b/src/Packages/Passport/Runtime/ThirdParty/ImmutableBrowserCore/Immutable.Browser.Core.asmdef @@ -1,16 +1,16 @@ { - "name": "Immutable.Browser.Core", - "rootNamespace": "Immutable.Browser.Core", - "references": [ - "GUID:f51ebe6a0ceec4240a699833d6309b23" - ], - "includePlatforms": [], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "Immutable.Browser.Core", + "rootNamespace": "Immutable.Browser.Core", + "references": [ + "GUID:f51ebe6a0ceec4240a699833d6309b23" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser.Engine.Cef.Win-x64/Engine/vk_swiftshader_icd.json b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser.Engine.Cef.Win-x64/Engine/vk_swiftshader_icd.json index 525fbc5a..0add28f1 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser.Engine.Cef.Win-x64/Engine/vk_swiftshader_icd.json +++ b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser.Engine.Cef.Win-x64/Engine/vk_swiftshader_icd.json @@ -1 +1,7 @@ -{"file_format_version": "1.0.0", "ICD": {"library_path": ".\\vk_swiftshader.dll", "api_version": "1.0.5"}} \ No newline at end of file +{ + "file_format_version": "1.0.0", + "ICD": { + "library_path": ".\\vk_swiftshader.dll", + "api_version": "1.0.5" + } +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/VoltstroStudios.UnityWebBrowser.asmdef b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/VoltstroStudios.UnityWebBrowser.asmdef index 0c0060d2..ed9cb37a 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/VoltstroStudios.UnityWebBrowser.asmdef +++ b/src/Packages/Passport/Runtime/ThirdParty/UnityWebBrowser/Runtime/VoltstroStudios.UnityWebBrowser.asmdef @@ -1,39 +1,39 @@ { - "name": "VoltstroStudios.UnityWebBrowser", - "rootNamespace": "VoltstroStudios.UnityWebBrowser", - "references": [ - "UniTask", - "Unity.InputSystem", - "Immutable.Browser.Core", - "Immutable.Passport.Core.Logging" - ], - "includePlatforms": [ - "Editor", - "LinuxStandalone64", - "macOSStandalone", - "WindowsStandalone64" - ], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": true, - "precompiledReferences": [ - "VoltstroStudios.UnityWebBrowser.Shared.dll", - "VoltRpc.dll", - "Newtonsoft.Json.dll" - ], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [ - { - "name": "com.unity.textmeshpro", - "expression": "3.0", - "define": "TMP_ENABLED" - }, - { - "name": "dev.voltstro.unitywebbrowser.unix-support", - "expression": "1", - "define": "UNIX_SUPPORT" - } - ], - "noEngineReferences": false + "name": "VoltstroStudios.UnityWebBrowser", + "rootNamespace": "VoltstroStudios.UnityWebBrowser", + "references": [ + "UniTask", + "Unity.InputSystem", + "Immutable.Browser.Core", + "Immutable.Passport.Core.Logging" + ], + "includePlatforms": [ + "Editor", + "LinuxStandalone64", + "macOSStandalone", + "WindowsStandalone64" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [ + "VoltstroStudios.UnityWebBrowser.Shared.dll", + "VoltRpc.dll", + "Newtonsoft.Json.dll" + ], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [ + { + "name": "com.unity.textmeshpro", + "expression": "3.0", + "define": "TMP_ENABLED" + }, + { + "name": "dev.voltstro.unitywebbrowser.unix-support", + "expression": "1", + "define": "UNIX_SUPPORT" + } + ], + "noEngineReferences": false } \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/License.md b/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/License.md index 36f36cd0..6b0bc215 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/License.md +++ b/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/License.md @@ -1,12 +1,19 @@ -SPDX identifier -MIT -License text - MIT License _____ +SPDX identifier +MIT +License text +MIT License _____ -Permission is hereby granted, free of charge, to any person obtaining a copy of _____ (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of _____ (the "Software"), to deal in the +Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: -The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL _____ BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL _____ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - diff --git a/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/netstandard2.1/VoltRpc.xml b/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/netstandard2.1/VoltRpc.xml index 0cafc808..5073a69e 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/netstandard2.1/VoltRpc.xml +++ b/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/netstandard2.1/VoltRpc.xml @@ -6,26 +6,40 @@ - An related to when an action is attempted to be done that cannot be done while the - is already connected + An + + related to when an action is attempted to be done that cannot be done while the + + is already connected - An related to when an action is attempted to be done that cannot be done while the - is already running + An + + related to when an action is attempted to be done that cannot be done while the + + is already running - The is what is used to send messages to a + The + + is what is used to send messages to a + - This base has no implementation of actually connecting, a "communication layer" - needs to be used, such as the communication layer + This base + + has no implementation of actually connecting, a "communication layer" + needs to be used, such as the + + communication layer In most normal cases, you will only have to use the generated proxy layer to interact with - the + the + @@ -46,69 +60,120 @@ - Creates a new instance + Creates a new + + instance The initial size of the buffers - Will throw if the buffer size is less then 16 + Will throw if the buffer size is less then 16 + - The for + The + + for + - Is the connected + Is the + + connected - Connects the to a host + Connects the + + to a host - Tells the what interfaces you might be using + Tells the + + what interfaces you might be using The same interface that you are using on the server - Thrown if T's is null - Thrown if T is not an interface, or has already been added as a service. + Thrown if T's + + is null + + Thrown if T is not an interface, or has already been + added as a service. + - Tells the what interfaces you might be using + Tells the + + what interfaces you might be using - Thrown if interfaceType's is null + Thrown if interfaceType's + + is null + Thrown if interfaceType is not an interface, or has already been added as a service. - Thrown if we are already connected + Thrown if we are already connected + Sets what protocol version to use. Set value to null to reset back to none. - Value can be any object you want, as long as the has a for it. - Thrown if the is already connected to a - Thrown if the doesn't have a for the value . + Value can be any object you want, as long as the + + has a + + for it. + + Thrown if the + + is already connected to a + + + Thrown if the + + doesn't have a + + for the value. + Initialize streams - The to read from - The to write to + The + + to read from + + The + + to write to + Thrown if either provided stream is null - Thrown if we can't read or write to the respected streams + Thrown if we can't read or write to the respected + streams + Initialize streams - The that will be read from - The that will be written to + The + + that will be read from + + The + + that will be written to + Thrown if either provided buffers is null @@ -117,18 +182,23 @@ The full method name All parameters to be passed to the method - Thrown if the client is not connected to a host + Thrown if the client is not connected to a + host + Thrown if the method name doesn't exist on either the client or host - Thrown if the return type or parameter types doesn't have a + Thrown if the return type or parameter types doesn't have a + Thrown if the type reader/writer fails on the host - Thrown if an occurs while invoking a method on the host + Thrown if an + + occurs while invoking a method on the host @@ -146,7 +216,8 @@ - Handles a + Handles a + @@ -163,42 +234,56 @@ - Deconstructor for . + Deconstructor for. Tells the server that we have disconnected and releases resources if it hasn't been done by - already. + + already. - Destroys the instance + Destroys the + + instance - An related to when the connection fails to connect + An + + related to when the connection fails to connect - Creates a new instance + Creates a new + + instance - Creates a new instance + Creates a new + + instance - The is what receives and responds to a 's requests + The + + is what receives and responds to a's requests - This base has no actual implementation of handling connections, - a "communication layer" needs to be used for that, such as + This base + + has no actual implementation of handling connections, + a "communication layer" needs to be used for that, such as + @@ -229,15 +314,24 @@ - Creates a new instance + Creates a new + + instance - The to use + The + + to use + The initial size of the buffers - Will throw if the buffer size is less then 16 + Will throw if the buffer size is less then 16 + - The for + The + + for + @@ -253,12 +347,16 @@ - Is the running? + Is the + + running? - Hides the stacktrace from the client when an is thrown + Hides the stacktrace from the client when an + + is thrown @@ -278,19 +376,30 @@ - Adds a service to this + Adds a service to this + - The service to add + The service + + to add + The service type Thrown if the service has already been added Thrown if T is not an interface - Adds a service to this - - The of a service - The actual service itself + Adds a service to this + + + The + + of a service + + The actual service + + itself + Thrown if the service has already been added Thrown if serviceType is not an interface @@ -299,36 +408,73 @@ Sets what protocol version to use. Set value to null to reset back to none. - Value can be any object you want, as long as the has a for it. - Thrown if the is already running - Thrown if the doesn't have a for the value . + Value can be any object you want, as long as the + + has a + + for it. + + Thrown if the + + is already running + + Thrown if the + + doesn't have a + + for the value. + Processes a request from a client - This override will automatically create the and for + This override will automatically create the + + and + + for you - then call . + then call + . This is the preferred process request method to call. - The to read from - The to write to + The + + to read from + + The + + to write to + Thrown if either provide stream is null - Thrown if we can't read or write to the respected stream + Thrown if we can't read or write to the respected + stream + Processes a request from a client - You should only call this if you need to provide a custom and/or - . - For example you are using a that needs . + You should only call this if you need to provide a custom + + and/or + . + For example you are using a + + that needs. - The to read from - The to write to + The + + to read from + + The + + to write to + Thrown if either buffer is null @@ -352,7 +498,9 @@ - Destroys the instance + Destroys the + + instance @@ -392,7 +540,9 @@ - The of the protocol value doesn't match + The + + of the protocol value doesn't match @@ -432,19 +582,25 @@ - An related to when a method fails on the host + An + + related to when a method fails on the host - Creates a new instance + Creates a new + + instance - Creates a new instance + Creates a new + + instance @@ -452,42 +608,62 @@ - + - An related to when a method is attempted to be called, - but the has not connected yet + An + + related to when a method is attempted to be called, + but the + + has not connected yet - Create new + Create new + - An related to a protocol sync error + An + + related to a protocol sync error - This could be due to the set protocol being different between the and - , either from different or different + This could be due to the set protocol being different between the + + and + , either from different + + or different values - An related to an error with syncing + An + + related to an error with syncing - The is thrown when the interfaces that the - and use have differences + The + + is thrown when the interfaces that the + + and + + use have differences - A that uses TCP to communicate + A + + that uses TCP to communicate @@ -507,9 +683,14 @@ - Creates a new instance + Creates a new + + instance - The to connect to + The + + to connect to + The size of the buffers The timeout time for connection The receive timeout @@ -517,36 +698,55 @@ - Creates a new instance + Creates a new + + instance - The to connect to + The + + to connect to + The receive timeout The send timeout - Creates a new instance + Creates a new + + instance - The to connect to + The + + to connect to + The timeout time for connection - Creates a new instance + Creates a new + + instance - The to connect to + The + + to connect to + - + Thrown if a connection timeout occurs - Thrown if an unknown error occurs while connecting. + Thrown if an unknown error occurs while + connecting. + - + - A that uses TCP to communicate + A + + that uses TCP to communicate @@ -561,67 +761,112 @@ - Creates a new instance - - The to listen on - The to use. Will default to if null + Creates a new + + instance + + The + + to listen on + + The + + to use. Will default to + + if null + The initial size of the buffers How long until timeout from receiving How long until timeout from sending - Will throw if the buffer size is less then 16 + Will throw if the buffer size is less then 16 + - Creates a new instance + Creates a new + + instance - The to listen on + The + + to listen on + The initial size of the buffers How long until timeout from receiving How long until timeout from sending - Creates a new instance - - The to listen on - The to use. Will default to if null + Creates a new + + instance + + The + + to listen on + + The + + to use. Will default to + + if null + How long until timeout from receiving How long until timeout from sending - Creates a new instance + Creates a new + + instance - The to listen on + The + + to listen on + How long until timeout from receiving How long until timeout from sending - Creates a new instance - - The to listen on - The to use. Will default to if null + Creates a new + + instance + + The + + to listen on + + The + + to use. Will default to + + if null + - + - + - A buffered reader for a + A buffered reader for a + - The incoming + The incoming + - Internal access to the underlining for s + Internal access to the underlining + + fors @@ -631,12 +876,15 @@ - Current read length of the underlining + Current read length of the underlining + - Creates a new instance + Creates a new + + instance @@ -653,12 +901,16 @@ - You may need to override this if your requires it + You may need to override this if your + + requires it - You may need to override this if your requires it + You may need to override this if your + + requires it @@ -671,14 +923,16 @@ - Reads a + Reads a + - Reads an array of s as an + Reads an array ofs as an + @@ -686,14 +940,16 @@ - Reads a + Reads a + - Reads more of the underlining + Reads more of the underlining + @@ -715,106 +971,131 @@ - Disposes of this instance - This method SHOULD NOT be used! VoltRpc will dispose of this object when it is done with it! - NOTE: This disposal method will NOT call on the underlying + Disposes of this + + instance + This method SHOULD NOT be used! VoltRpc will dispose of this object when it is done with it! + + NOTE: This disposal method will NOT call + + on the underlying + + - Read methods for + Read methods for + - Reads a + Reads a + - Reads a + Reads a + - Reads a + Reads a + - Reads a + Reads a + - Reads a + Reads a + - Reads a + Reads a + - Reads a + Reads a + - Reads a + Reads a + - Reads a + Reads a + - Reads a + Reads a + - Reads a + Reads a + - Reads a + Reads a + - A buffered writer for a + A buffered writer for a + - Max length for a + Max length for a + - Output + Output + - Internal access to the underlining for s + Internal access to the underlining + + fors @@ -824,7 +1105,9 @@ - Creates a new instance + Creates a new + + instance @@ -841,7 +1124,9 @@ - You may need to override this if your requires it + You may need to override this if your + + requires it @@ -851,13 +1136,14 @@ - Writes a + Writes a + The value to write - Writes an array of s + Writes an array ofs @@ -865,14 +1151,16 @@ - Writes a + Writes a + - Writes the buffer to the out + Writes the buffer to the out + @@ -899,74 +1187,94 @@ - Disposes of this instance - This method SHOULD NOT be used! VoltRpc will dispose of this object when it is done with it! - NOTE: This disposal method will NOT call on the underlying + Disposes of this + + instance + This method SHOULD NOT be used! VoltRpc will dispose of this object when it is done with it! + + NOTE: This disposal method will NOT call + + on the underlying + + - Provides extensions for + Provides extensions for + - Writes a + Writes a + - Writes a + Writes a + - Writes a + Writes a + - Writes a + Writes a + - Writes a + Writes a + - Writes a + Writes a + - Writes a + Writes a + - Writes a + Writes a + - Writes a + Writes a + - Writes a + Writes a + - Writes a + Writes a + - Writes a + Writes a + @@ -983,29 +1291,32 @@ - Logger for + Logger for + - Creates a new instance + Creates a new + + instance - + - + - + - + - + @@ -1068,23 +1379,24 @@ - Null + Null + - + - + - + - + - + @@ -1093,7 +1405,9 @@ - Creates a new instance + Creates a new + + instance @@ -1122,7 +1436,8 @@ - Interface for reading and writing a + Interface for reading and writing a + @@ -1147,19 +1462,24 @@ - related to something with a type reader writer + + related to something with a type reader writer - Creates a new instance + Creates a new + + instance - Creates a new instance + Creates a new + + instance @@ -1167,113 +1487,198 @@ - + - Manger for s + Manger fors - Default to be added + Default + + to be added - Creates a new instance + Creates a new + + instance - Adds a + Adds a + - If the has already been added, it will be overriden + If the + + has already been added, it will be overriden - The to add - The base to add + The + + to add + + The base + + to add + - Adds a + Adds a + - If the has already been added, it will be overriden + If the + + has already been added, it will be overriden - The to add - The for - Thrown if the type is an array, and the base type is null. + The + + to add + + The + + for + + + Thrown if the type is an array, and the base type is + null. + - Adds a + Adds a + - If the has already been added, it will be overriden + If the + + has already been added, it will be overriden - The full name to add - The for + The + + full name to add + + The + + for + + - Gets a + Gets a + - The full name - Will return null if hasn't been added for + The + + full name + + Will return null if + + hasn't been added for + + - Gets a + Gets a + - The to get - Will return null if hasn't been added for + The + + to get + + Will return null if + + hasn't been added for + + - Gets a + Gets a + - The to get - Will return null if hasn't been added for + The + + to get + + Will return null if + + hasn't been added for + + Interface for reading and writing a type. - should read exactly how it is written to the in . + + + should read exactly how it is written to the + + in. + - The to read and write + The + + to read and write + Called when the type needs to be written - The to write to - The value that needs to be written to the + The + + to write to + + The value that needs to be written to the + + Called when the type needs to be read - The to read from - Return the read value from the + The + + to read from + + Return the read value from the + + - Helper methods for s + Helper methods fors - Gets a 's full name + Gets a's full name - The to get the full name from - Returns the fullname of the + The + + to get the full name from + + Returns the fullname of the + + Throw if provided type is null - Thrown if type is an array, but it's item type is null! + Thrown if type is an array, but it's item type is null! + - Gets a base, then it's name + Gets a + + base, then it's name @@ -1281,7 +1686,9 @@ - Gets the absolute base of a . + Gets the absolute base + + of a. Checks if refs and arrays @@ -1290,29 +1697,35 @@ - Contains information the VoltRpc needs on a + Contains information the VoltRpc needs on a + - Creates a new + Creates a new + - The base + The base + - The fullname of the + The fullname of the + - Is this an array? + Is this + + an array? @@ -1322,7 +1735,9 @@ - Current about VoltRpc + Current + + about VoltRpc @@ -1347,8 +1762,12 @@ - related to when there is a version miss-match between - the and + + related to when there is a version miss-match between + the + + and + @@ -1358,13 +1777,13 @@ - Provides access to the current assembly information as pure constants, - without requiring reflection. + Provides access to the current assembly information as pure constants, + without requiring reflection. - Gets the AssemblyInfo attributes. + Gets the AssemblyInfo attributes. diff --git a/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/package.json b/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/package.json index f2b8238f..710cb855 100644 --- a/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/package.json +++ b/src/Packages/Passport/Runtime/ThirdParty/org.nuget.voltrpc@3.1.0/package.json @@ -1 +1,20 @@ -{"name":"org.nuget.voltrpc","version":"3.1.0","unity":"2019.1","description":"VoltRpc - A RPC library designed to be simple to use and fast.","keywords":["nuget","IPC","RPC","TCP","Pipes","Named-Pipes","rpc-library","interprocess-communication","dotnet","csharp"],"category":null,"dependencies":{}} \ No newline at end of file +{ + "name": "org.nuget.voltrpc", + "version": "3.1.0", + "unity": "2019.1", + "description": "VoltRpc - A RPC library designed to be simple to use and fast.", + "keywords": [ + "nuget", + "IPC", + "RPC", + "TCP", + "Pipes", + "Named-Pipes", + "rpc-library", + "interprocess-communication", + "dotnet", + "csharp" + ], + "category": null, + "dependencies": {} +} \ No newline at end of file diff --git a/src/Packages/Passport/Runtime/omnisharp.json b/src/Packages/Passport/Runtime/omnisharp.json index fbaad352..a148e006 100644 --- a/src/Packages/Passport/Runtime/omnisharp.json +++ b/src/Packages/Passport/Runtime/omnisharp.json @@ -1,6 +1,8 @@ { - "RoslynExtensionsOptions": { - "EnableAnalyzersSupport": true, - "LocationPaths": ["../../../../analyzers/microsoft.unity.analyzers.1.17.0/analyzers/dotnet/cs"] - } + "RoslynExtensionsOptions": { + "EnableAnalyzersSupport": true, + "LocationPaths": [ + "../../../../analyzers/microsoft.unity.analyzers.1.17.0/analyzers/dotnet/cs" + ] + } } \ No newline at end of file diff --git a/src/Packages/Passport/Tests/Runtime/Scripts/Core/BrowserCommunicationsManagerTests.cs b/src/Packages/Passport/Tests/Runtime/Scripts/Core/BrowserCommunicationsManagerTests.cs index 21655dff..eb7b73c6 100644 --- a/src/Packages/Passport/Tests/Runtime/Scripts/Core/BrowserCommunicationsManagerTests.cs +++ b/src/Packages/Passport/Tests/Runtime/Scripts/Core/BrowserCommunicationsManagerTests.cs @@ -1,25 +1,16 @@ using System; -using NUnit.Framework; +using System.Threading.Tasks; using Immutable.Browser.Core; +using Immutable.Passport.Helpers; using Immutable.Passport.Model; +using NUnit.Framework; using UnityEngine; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using Immutable.Passport.Helpers; namespace Immutable.Passport.Core { [TestFixture] public class BrowserCommunicationsManagerTests { - private const string FUNCTION_NAME = "someFunction"; - private const string ERROR = "some error"; - -#pragma warning disable CS8618 - private BrowserCommunicationsManager manager; - private MockBrowserClient mockClient; -#pragma warning restore CS8618 - [SetUp] public void Init() { @@ -27,6 +18,9 @@ public void Init() manager = new BrowserCommunicationsManager(mockClient); } + private const string FUNCTION_NAME = "someFunction"; + private const string ERROR = "some error"; + [Test] public async Task CallAndResponse_Success_WithData() { @@ -54,7 +48,7 @@ public async Task CallAndResponse_Success_NoData() Assert.NotNull(mockClient.request); Assert.True(mockClient.request.fxName == FUNCTION_NAME); - Assert.True(String.IsNullOrEmpty(mockClient.request.data)); + Assert.True(string.IsNullOrEmpty(mockClient.request.data)); } [Test] @@ -70,7 +64,7 @@ public async Task CallAndResponse_Failed_NoRequestId() Exception e = null; try { - string response = await manager.Call(FUNCTION_NAME); + var response = await manager.Call(FUNCTION_NAME); } catch (PassportException exception) { @@ -78,7 +72,7 @@ public async Task CallAndResponse_Failed_NoRequestId() } Assert.NotNull(e); - Assert.IsTrue(e.Message.Contains("Response from browser is incorrect") == true); + Assert.IsTrue(e.Message.Contains("Response from browser is incorrect")); } [Test] @@ -95,7 +89,7 @@ public async Task CallAndResponse_Failed_ClientError_WithType() PassportException e = null; try { - string response = await manager.Call(FUNCTION_NAME); + var response = await manager.Call(FUNCTION_NAME); } catch (PassportException exception) { @@ -119,7 +113,7 @@ public async Task CallAndResponse_Failed_ClientError_NoType() PassportException e = null; try { - string response = await manager.Call(FUNCTION_NAME); + var response = await manager.Call(FUNCTION_NAME); } catch (PassportException exception) { @@ -135,74 +129,64 @@ public async Task CallAndResponse_Failed_ClientError_NoType() [Test] public void CallAndResponse_Success_BrowserReady() { - BrowserResponse browserResponse = new BrowserResponse() + var browserResponse = new BrowserResponse { responseFor = BrowserCommunicationsManager.INIT, requestId = BrowserCommunicationsManager.INIT_REQUEST_ID, success = true }; - bool onReadyCalled = false; + var onReadyCalled = false; manager.OnReady += () => onReadyCalled = true; mockClient.InvokeUnityPostMessage(JsonUtility.ToJson(browserResponse)); Assert.True(onReadyCalled); } + +#pragma warning disable CS8618 + private BrowserCommunicationsManager manager; + private MockBrowserClient mockClient; +#pragma warning restore CS8618 } internal class MockBrowserClient : IWebBrowserClient { + public BrowserResponse browserResponse; + + public BrowserRequest request; + public bool setRequestId = true; public event OnUnityPostMessageDelegate OnUnityPostMessage; public event OnUnityPostMessageDelegate OnAuthPostMessage; public event OnUnityPostMessageErrorDelegate OnPostMessageError; - public BrowserRequest request = null; - public BrowserResponse browserResponse = null; - public bool setRequestId = true; - public void ExecuteJs(string js) { var json = Between(js, "callFunction(\"", "\")").Replace("\\\\", "\\").Replace("\\\"", "\""); request = json.OptDeserializeObject(); - if (setRequestId && browserResponse != null) - { - browserResponse.requestId = request.requestId; - } + if (setRequestId && browserResponse != null) browserResponse.requestId = request.requestId; InvokeUnityPostMessage(JsonUtility.ToJson(browserResponse)); } - internal void InvokeUnityPostMessage(string message) + public void LaunchAuthURL(string url, string redirectUri) { - if (OnUnityPostMessage != null) - { - OnUnityPostMessage.Invoke(message); - } + throw new NotImplementedException(); } - private string Between(string value, string a, string b) + internal void InvokeUnityPostMessage(string message) { - int posA = value.IndexOf(a); - int posB = value.LastIndexOf(b); - if (posA == -1) - { - return ""; - } - if (posB == -1) - { - return ""; - } - int adjustedPosA = posA + a.Length; - if (adjustedPosA >= posB) - { - return ""; - } - return value.Substring(adjustedPosA, posB - adjustedPosA); + if (OnUnityPostMessage != null) OnUnityPostMessage.Invoke(message); } - public void LaunchAuthURL(string url, string redirectUri) + private string Between(string value, string a, string b) { - throw new NotImplementedException(); + var posA = value.IndexOf(a); + var posB = value.LastIndexOf(b); + if (posA == -1) return ""; + if (posB == -1) return ""; + var adjustedPosA = posA + a.Length; + if (adjustedPosA >= posB) return ""; + return value.Substring(adjustedPosA, posB - adjustedPosA); } public void Dispose() diff --git a/src/Packages/Passport/Tests/Runtime/Scripts/Helpers/JsonHelpersTests.cs b/src/Packages/Passport/Tests/Runtime/Scripts/Helpers/JsonHelpersTests.cs index 8476b6b7..a470e2ab 100644 --- a/src/Packages/Passport/Tests/Runtime/Scripts/Helpers/JsonHelpersTests.cs +++ b/src/Packages/Passport/Tests/Runtime/Scripts/Helpers/JsonHelpersTests.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using NUnit.Framework; using Immutable.Passport.Helpers; +using NUnit.Framework; namespace Immutable.Passport.Core { @@ -10,22 +10,24 @@ public class JsonHelpersTests [Test] public void DictionaryToJson() { - var properties = new Dictionary(){ - {"boolean", true}, - {"string", "immutable"}, - {"int", 1}, - {"long", (long) 2}, - {"double", (double) 3} - }; - Assert.AreEqual("{\"boolean\":true,\"string\":\"immutable\",\"int\":1,\"long\":2,\"double\":3}", properties.ToJson()); + var properties = new Dictionary + { + { "boolean", true }, + { "string", "immutable" }, + { "int", 1 }, + { "long", (long)2 }, + { "double", (double)3 } + }; + Assert.AreEqual("{\"boolean\":true,\"string\":\"immutable\",\"int\":1,\"long\":2,\"double\":3}", + properties.ToJson()); - properties = new Dictionary() { { "boolean", false } }; + properties = new Dictionary { { "boolean", false } }; Assert.AreEqual("{\"boolean\":false}", properties.ToJson()); properties = new Dictionary(); Assert.AreEqual("{}", properties.ToJson()); - properties = new Dictionary() { { "null", null } }; + properties = new Dictionary { { "null", null } }; Assert.AreEqual("{}", properties.ToJson()); } } diff --git a/src/Packages/Passport/Tests/Runtime/Scripts/Helpers/UriHelpersTests.cs b/src/Packages/Passport/Tests/Runtime/Scripts/Helpers/UriHelpersTests.cs index b5424171..8cafecff 100644 --- a/src/Packages/Passport/Tests/Runtime/Scripts/Helpers/UriHelpersTests.cs +++ b/src/Packages/Passport/Tests/Runtime/Scripts/Helpers/UriHelpersTests.cs @@ -1,6 +1,6 @@ using System; -using NUnit.Framework; using Immutable.Passport.Helpers; +using NUnit.Framework; namespace Immutable.Passport.Core { @@ -16,7 +16,8 @@ public class UriHelpersTests [Test] public void GetQueryParameter_Success() { - Uri uri = new Uri($"{DOMAIN}?{QUERY_PARAMETER_KEY1}={QUERY_PARAMETER_VALUE1}&{QUERY_PARAMETER_KEY2}={QUERY_PARAMETER_VALUE2}"); + var uri = new Uri( + $"{DOMAIN}?{QUERY_PARAMETER_KEY1}={QUERY_PARAMETER_VALUE1}&{QUERY_PARAMETER_KEY2}={QUERY_PARAMETER_VALUE2}"); Assert.True(uri.GetQueryParameter(QUERY_PARAMETER_KEY1) == QUERY_PARAMETER_VALUE1); Assert.True(uri.GetQueryParameter(QUERY_PARAMETER_KEY2) == QUERY_PARAMETER_VALUE2); } @@ -24,14 +25,14 @@ public void GetQueryParameter_Success() [Test] public void GetQueryParameter_NoQueryParameterWithKey() { - Uri uri = new Uri($"{DOMAIN}?noKey=some-value"); + var uri = new Uri($"{DOMAIN}?noKey=some-value"); Assert.Null(uri.GetQueryParameter(QUERY_PARAMETER_KEY1)); } [Test] public void GetQueryParameter_NoQueryParameters() { - Uri uri = new Uri(DOMAIN); + var uri = new Uri(DOMAIN); Assert.Null(uri.GetQueryParameter(QUERY_PARAMETER_KEY1)); uri = new Uri($"{DOMAIN}?"); Assert.Null(uri.GetQueryParameter(QUERY_PARAMETER_KEY1)); diff --git a/src/Packages/Passport/Tests/Runtime/Scripts/Immutable.Passport.Runtime.Tests.asmdef b/src/Packages/Passport/Tests/Runtime/Scripts/Immutable.Passport.Runtime.Tests.asmdef index 2d0cfc2a..581fd975 100644 --- a/src/Packages/Passport/Tests/Runtime/Scripts/Immutable.Passport.Runtime.Tests.asmdef +++ b/src/Packages/Passport/Tests/Runtime/Scripts/Immutable.Passport.Runtime.Tests.asmdef @@ -1,22 +1,22 @@ { - "name": "Immutable.Passport.Runtime.Tests", - "references": [ - "GUID:9e287cc7b3c8a0245a7d36254472d3c8", - "GUID:b68f5bb197434c84c8a4cc3e45e8408b", - "GUID:78c2789dfc155bf4b9e815b0ca402b9b", - "GUID:95d173a3e67b39d40803000ed05b79f4", - "GUID:9fc1342f87877ac42a37b19ac1c6653c", - "GUID:f51ebe6a0ceec4240a699833d6309b23" - ], - "includePlatforms": [ - "Editor" - ], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": false, - "precompiledReferences": [], - "autoReferenced": true, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false + "name": "Immutable.Passport.Runtime.Tests", + "references": [ + "GUID:9e287cc7b3c8a0245a7d36254472d3c8", + "GUID:b68f5bb197434c84c8a4cc3e45e8408b", + "GUID:78c2789dfc155bf4b9e815b0ca402b9b", + "GUID:95d173a3e67b39d40803000ed05b79f4", + "GUID:9fc1342f87877ac42a37b19ac1c6653c", + "GUID:f51ebe6a0ceec4240a699833d6309b23" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file diff --git a/src/Packages/Passport/Tests/Runtime/Scripts/PassportTests.cs b/src/Packages/Passport/Tests/Runtime/Scripts/PassportTests.cs index a7c26e93..afdd778f 100644 --- a/src/Packages/Passport/Tests/Runtime/Scripts/PassportTests.cs +++ b/src/Packages/Passport/Tests/Runtime/Scripts/PassportTests.cs @@ -1,22 +1,24 @@ using System; using System.Collections.Generic; -using NUnit.Framework; -using Immutable.Passport.Core; -using Immutable.Passport.Model; -using Immutable.Passport.Event; using System.Threading.Tasks; using Cysharp.Threading.Tasks; using Immutable.Browser.Core; -using UnityEngine; +using Immutable.Passport.Core; +using Immutable.Passport.Event; using Immutable.Passport.Helpers; +using Immutable.Passport.Model; +using NUnit.Framework; +using UnityEngine; using UnityEngine.TestTools; namespace Immutable.Passport { - class TestPassportImpl : PassportImpl + internal class TestPassportImpl : PassportImpl { - private List urlsOpened; - public TestPassportImpl(IBrowserCommunicationsManager communicationsManager, List urlsOpened) : base(communicationsManager) + private readonly List urlsOpened; + + public TestPassportImpl(IBrowserCommunicationsManager communicationsManager, List urlsOpened) : base( + communicationsManager) { this.urlsOpened = urlsOpened; } @@ -26,7 +28,8 @@ protected override void OpenUrl(string url) urlsOpened.Add(url); } - protected override void Track(string eventName, bool? success = null, Dictionary properties = null) + protected override void Track(string eventName, bool? success = null, + Dictionary properties = null) { } } @@ -34,9 +37,29 @@ protected override void Track(string eventName, bool? success = null, Dictionary [TestFixture] public class PassportImplTests { + [SetUp] + public void Init() + { + communicationsManager = new MockBrowserCommsManager(); + urlsOpened = new List(); + authEvents = new List(); + passport = new TestPassportImpl(communicationsManager, urlsOpened); + passport.OnAuthEvent += OnPassportAuthEvent; + communicationsManager.responses.Clear(); + } + + [TearDown] + public void Cleanup() + { + passport.OnAuthEvent -= OnPassportAuthEvent; + } + internal static string DEVICE_CODE = "deviceCode"; - internal static string ACCESS_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikp" + + + internal static string ACCESS_TOKEN = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikp" + "vaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjEyM30.kRqQkJudxgI3koJAp9K4ENp6E2ExFQ5VchogaTWx6Fk"; + internal static string ACCESS_TOKEN_KEY = "accessToken"; internal static string REFRESH_TOKEN = "refreshToken"; internal static string REFRESH_TOKEN_KEY = "refreshToken"; @@ -54,31 +77,9 @@ public class PassportImplTests internal static int INTERVAL = 5; private const string REQUEST_ID = "50"; -#pragma warning disable CS8618 - private MockBrowserCommsManager communicationsManager; - private TestPassportImpl passport; -#pragma warning restore CS8618 - private List urlsOpened; private List authEvents; - [SetUp] - public void Init() - { - communicationsManager = new MockBrowserCommsManager(); - urlsOpened = new List(); - authEvents = new List(); - passport = new TestPassportImpl(communicationsManager, urlsOpened); - passport.OnAuthEvent += OnPassportAuthEvent; - communicationsManager.responses.Clear(); - } - - [TearDown] - public void Cleanup() - { - passport.OnAuthEvent -= OnPassportAuthEvent; - } - private void OnPassportAuthEvent(PassportAuthEvent authEvent) { Debug.Log($"OnPassportAuthEvent {authEvent.ToString()}"); @@ -110,7 +111,7 @@ public async Task Login_Logout_Success() communicationsManager.AddMockResponse(logoutResponse); // Login - bool success = await passport.Login(); + var success = await passport.Login(); Assert.True(success); // Logout @@ -119,14 +120,15 @@ public async Task Login_Logout_Success() Assert.AreEqual(2, urlsOpened.Count); Assert.AreEqual(URL, urlsOpened[0]); Assert.AreEqual(LOGOUT_URL, urlsOpened[1]); - List expectedEvents = new List{ - PassportAuthEvent.LoggingIn, - PassportAuthEvent.LoginOpeningBrowser, - PassportAuthEvent.PendingBrowserLogin, - PassportAuthEvent.LoginSuccess, - PassportAuthEvent.LoggingOut, - PassportAuthEvent.LogoutSuccess - }; + var expectedEvents = new List + { + PassportAuthEvent.LoggingIn, + PassportAuthEvent.LoginOpeningBrowser, + PassportAuthEvent.PendingBrowserLogin, + PassportAuthEvent.LoginSuccess, + PassportAuthEvent.LoggingOut, + PassportAuthEvent.LogoutSuccess + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -156,22 +158,23 @@ public async Task Login_Soft_Logout_Success() communicationsManager.AddMockResponse(logoutResponse); // Login - bool success = await passport.Login(); + var success = await passport.Login(); Assert.True(success); // Logout - await passport.Logout(hardLogout: false); + await passport.Logout(false); Assert.AreEqual(1, urlsOpened.Count); Assert.AreEqual(URL, urlsOpened[0]); - List expectedEvents = new List{ - PassportAuthEvent.LoggingIn, - PassportAuthEvent.LoginOpeningBrowser, - PassportAuthEvent.PendingBrowserLogin, - PassportAuthEvent.LoginSuccess, - PassportAuthEvent.LoggingOut, - PassportAuthEvent.LogoutSuccess - }; + var expectedEvents = new List + { + PassportAuthEvent.LoggingIn, + PassportAuthEvent.LoginOpeningBrowser, + PassportAuthEvent.PendingBrowserLogin, + PassportAuthEvent.LoginSuccess, + PassportAuthEvent.LoggingOut, + PassportAuthEvent.LogoutSuccess + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -198,10 +201,11 @@ public async Task Login_InitialiseDeviceCodeAuth_Failed() Assert.NotNull(e); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.LoggingIn, - PassportAuthEvent.LoginFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.LoggingIn, + PassportAuthEvent.LoginFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -222,10 +226,11 @@ public async Task Login_InitialiseDeviceCodeAuth_NullResponse_Failed() Assert.NotNull(e); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.LoggingIn, - PassportAuthEvent.LoginFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.LoggingIn, + PassportAuthEvent.LoginFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -261,12 +266,13 @@ public async Task Login_ConfirmCode_Failed() Assert.AreEqual(1, urlsOpened.Count); Assert.AreEqual(URL, urlsOpened[0]); - List expectedEvents = new List{ - PassportAuthEvent.LoggingIn, - PassportAuthEvent.LoginOpeningBrowser, - PassportAuthEvent.PendingBrowserLogin, - PassportAuthEvent.LoginFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.LoggingIn, + PassportAuthEvent.LoginOpeningBrowser, + PassportAuthEvent.PendingBrowserLogin, + PassportAuthEvent.LoginFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -297,12 +303,13 @@ public async Task Login_ConfirmCode_NullResponse_Failed() Assert.AreEqual(1, urlsOpened.Count); Assert.AreEqual(URL, urlsOpened[0]); - List expectedEvents = new List{ - PassportAuthEvent.LoggingIn, - PassportAuthEvent.LoginOpeningBrowser, - PassportAuthEvent.PendingBrowserLogin, - PassportAuthEvent.LoginFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.LoggingIn, + PassportAuthEvent.LoginOpeningBrowser, + PassportAuthEvent.PendingBrowserLogin, + PassportAuthEvent.LoginFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -326,7 +333,7 @@ public async Task Login_ValidTimeout() communicationsManager.AddMockResponse(confirmCodeResponse); // Login - bool success = false; + var success = false; ArgumentException e = null; try { @@ -384,7 +391,7 @@ public async Task Relogin_Success() communicationsManager.AddMockResponse(logoutResponse); // Relogin - bool success = await passport.Login(useCachedSession: true); + var success = await passport.Login(true); Assert.True(success); // Logout @@ -392,12 +399,13 @@ public async Task Relogin_Success() Assert.AreEqual(1, urlsOpened.Count); Assert.AreEqual(LOGOUT_URL, urlsOpened[0]); - List expectedEvents = new List{ - PassportAuthEvent.ReloggingIn, - PassportAuthEvent.ReloginSuccess, - PassportAuthEvent.LoggingOut, - PassportAuthEvent.LogoutSuccess - }; + var expectedEvents = new List + { + PassportAuthEvent.ReloggingIn, + PassportAuthEvent.ReloginSuccess, + PassportAuthEvent.LoggingOut, + PassportAuthEvent.LogoutSuccess + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -411,14 +419,15 @@ public async Task Relogin_Failed() }; communicationsManager.AddMockResponse(reloginResponse); - bool success = await passport.Login(useCachedSession: true); + var success = await passport.Login(true); Assert.False(success); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.ReloggingIn, - PassportAuthEvent.ReloginFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.ReloggingIn, + PassportAuthEvent.ReloginFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -428,14 +437,15 @@ public async Task Relogin_CallFailed() { communicationsManager.throwExceptionOnCall = true; - bool success = await passport.Login(useCachedSession: true); + var success = await passport.Login(true); Assert.False(success); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.ReloggingIn, - PassportAuthEvent.ReloginFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.ReloggingIn, + PassportAuthEvent.ReloginFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -443,14 +453,15 @@ public async Task Relogin_CallFailed() [Test] public async Task Relogin_NullResponse_Failed() { - bool success = await passport.Login(useCachedSession: true); + var success = await passport.Login(true); Assert.False(success); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.ReloggingIn, - PassportAuthEvent.ReloginFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.ReloggingIn, + PassportAuthEvent.ReloginFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -493,7 +504,7 @@ public async Task ConnectImx_Logout_Success() communicationsManager.AddMockResponse(logoutResponse); // Connect - bool success = await passport.ConnectImx(); + var success = await passport.ConnectImx(); Assert.True(success); // Logout @@ -502,18 +513,19 @@ public async Task ConnectImx_Logout_Success() Assert.AreEqual(2, urlsOpened.Count); Assert.AreEqual(URL, urlsOpened[0]); Assert.AreEqual(LOGOUT_URL, urlsOpened[1]); - List expectedEvents = new List{ - PassportAuthEvent.CheckingForSavedCredentials, - PassportAuthEvent.CheckForSavedCredentialsSuccess, - PassportAuthEvent.Reconnecting, - PassportAuthEvent.ReconnectFailed, - PassportAuthEvent.ConnectingImx, - PassportAuthEvent.ConnectImxOpeningBrowser, - PassportAuthEvent.PendingBrowserLoginAndProviderSetup, - PassportAuthEvent.ConnectImxSuccess, - PassportAuthEvent.LoggingOut, - PassportAuthEvent.LogoutSuccess - }; + var expectedEvents = new List + { + PassportAuthEvent.CheckingForSavedCredentials, + PassportAuthEvent.CheckForSavedCredentialsSuccess, + PassportAuthEvent.Reconnecting, + PassportAuthEvent.ReconnectFailed, + PassportAuthEvent.ConnectingImx, + PassportAuthEvent.ConnectImxOpeningBrowser, + PassportAuthEvent.PendingBrowserLoginAndProviderSetup, + PassportAuthEvent.ConnectImxSuccess, + PassportAuthEvent.LoggingOut, + PassportAuthEvent.LogoutSuccess + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -553,14 +565,15 @@ public async Task ConnectImx_InitialiseDeviceCodeAuth_Failed() Assert.NotNull(e); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.CheckingForSavedCredentials, - PassportAuthEvent.CheckForSavedCredentialsSuccess, - PassportAuthEvent.Reconnecting, - PassportAuthEvent.ReconnectFailed, - PassportAuthEvent.ConnectingImx, - PassportAuthEvent.ConnectImxFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.CheckingForSavedCredentials, + PassportAuthEvent.CheckForSavedCredentialsSuccess, + PassportAuthEvent.Reconnecting, + PassportAuthEvent.ReconnectFailed, + PassportAuthEvent.ConnectingImx, + PassportAuthEvent.ConnectImxFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -595,14 +608,15 @@ public async Task ConnectImx_InitialiseDeviceCodeAuth_NullResponse_Failed() Assert.NotNull(e); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.CheckingForSavedCredentials, - PassportAuthEvent.CheckForSavedCredentialsSuccess, - PassportAuthEvent.Reconnecting, - PassportAuthEvent.ReconnectFailed, - PassportAuthEvent.ConnectingImx, - PassportAuthEvent.ConnectImxFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.CheckingForSavedCredentials, + PassportAuthEvent.CheckForSavedCredentialsSuccess, + PassportAuthEvent.Reconnecting, + PassportAuthEvent.ReconnectFailed, + PassportAuthEvent.ConnectingImx, + PassportAuthEvent.ConnectImxFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -652,16 +666,17 @@ public async Task ConnectImx_ConfirmCode_Failed() Assert.AreEqual(1, urlsOpened.Count); Assert.AreEqual(URL, urlsOpened[0]); - List expectedEvents = new List{ - PassportAuthEvent.CheckingForSavedCredentials, - PassportAuthEvent.CheckForSavedCredentialsSuccess, - PassportAuthEvent.Reconnecting, - PassportAuthEvent.ReconnectFailed, - PassportAuthEvent.ConnectingImx, - PassportAuthEvent.ConnectImxOpeningBrowser, - PassportAuthEvent.PendingBrowserLoginAndProviderSetup, - PassportAuthEvent.ConnectImxFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.CheckingForSavedCredentials, + PassportAuthEvent.CheckForSavedCredentialsSuccess, + PassportAuthEvent.Reconnecting, + PassportAuthEvent.ReconnectFailed, + PassportAuthEvent.ConnectingImx, + PassportAuthEvent.ConnectImxOpeningBrowser, + PassportAuthEvent.PendingBrowserLoginAndProviderSetup, + PassportAuthEvent.ConnectImxFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -706,16 +721,17 @@ public async Task ConnectImx_ConfirmCode_NullResponse_Failed() Assert.AreEqual(1, urlsOpened.Count); Assert.AreEqual(URL, urlsOpened[0]); - List expectedEvents = new List{ - PassportAuthEvent.CheckingForSavedCredentials, - PassportAuthEvent.CheckForSavedCredentialsSuccess, - PassportAuthEvent.Reconnecting, - PassportAuthEvent.ReconnectFailed, - PassportAuthEvent.ConnectingImx, - PassportAuthEvent.ConnectImxOpeningBrowser, - PassportAuthEvent.PendingBrowserLoginAndProviderSetup, - PassportAuthEvent.ConnectImxFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.CheckingForSavedCredentials, + PassportAuthEvent.CheckForSavedCredentialsSuccess, + PassportAuthEvent.Reconnecting, + PassportAuthEvent.ReconnectFailed, + PassportAuthEvent.ConnectingImx, + PassportAuthEvent.ConnectImxOpeningBrowser, + PassportAuthEvent.PendingBrowserLoginAndProviderSetup, + PassportAuthEvent.ConnectImxFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -760,7 +776,7 @@ public async Task ConnectImx_HasCredentialsSaved_CannotReconnect_Logout_Success( communicationsManager.AddMockResponse(logoutResponse); // Connect - bool success = await passport.ConnectImx(); + var success = await passport.ConnectImx(); Assert.True(success); // Logout @@ -769,18 +785,19 @@ public async Task ConnectImx_HasCredentialsSaved_CannotReconnect_Logout_Success( Assert.AreEqual(2, urlsOpened.Count); Assert.AreEqual(URL, urlsOpened[0]); Assert.AreEqual(LOGOUT_URL, urlsOpened[1]); - List expectedEvents = new List{ - PassportAuthEvent.CheckingForSavedCredentials, - PassportAuthEvent.CheckForSavedCredentialsSuccess, - PassportAuthEvent.Reconnecting, - PassportAuthEvent.ReconnectFailed, - PassportAuthEvent.ConnectingImx, - PassportAuthEvent.ConnectImxOpeningBrowser, - PassportAuthEvent.PendingBrowserLoginAndProviderSetup, - PassportAuthEvent.ConnectImxSuccess, - PassportAuthEvent.LoggingOut, - PassportAuthEvent.LogoutSuccess - }; + var expectedEvents = new List + { + PassportAuthEvent.CheckingForSavedCredentials, + PassportAuthEvent.CheckForSavedCredentialsSuccess, + PassportAuthEvent.Reconnecting, + PassportAuthEvent.ReconnectFailed, + PassportAuthEvent.ConnectingImx, + PassportAuthEvent.ConnectImxOpeningBrowser, + PassportAuthEvent.PendingBrowserLoginAndProviderSetup, + PassportAuthEvent.ConnectImxSuccess, + PassportAuthEvent.LoggingOut, + PassportAuthEvent.LogoutSuccess + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -811,7 +828,7 @@ public async Task ConnectImx_HasCredentialsSaved_Reconnect_Logout_Success() communicationsManager.AddMockResponse(logoutResponse); // Login - bool success = await passport.ConnectImx(); + var success = await passport.ConnectImx(); Assert.True(success); // Logout @@ -819,14 +836,15 @@ public async Task ConnectImx_HasCredentialsSaved_Reconnect_Logout_Success() Assert.AreEqual(1, urlsOpened.Count); Assert.AreEqual(LOGOUT_URL, urlsOpened[0]); - List expectedEvents = new List{ - PassportAuthEvent.CheckingForSavedCredentials, - PassportAuthEvent.CheckForSavedCredentialsSuccess, - PassportAuthEvent.Reconnecting, - PassportAuthEvent.ReconnectSuccess, - PassportAuthEvent.LoggingOut, - PassportAuthEvent.LogoutSuccess - }; + var expectedEvents = new List + { + PassportAuthEvent.CheckingForSavedCredentials, + PassportAuthEvent.CheckForSavedCredentialsSuccess, + PassportAuthEvent.Reconnecting, + PassportAuthEvent.ReconnectSuccess, + PassportAuthEvent.LoggingOut, + PassportAuthEvent.LogoutSuccess + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -847,7 +865,7 @@ public async Task Reconnect_Success() communicationsManager.AddMockResponse(logoutResponse); // Reconnect - bool success = await passport.ConnectImx(useCachedSession: true); + var success = await passport.ConnectImx(true); Assert.True(success); // Logout @@ -855,12 +873,13 @@ public async Task Reconnect_Success() Assert.AreEqual(1, urlsOpened.Count); Assert.AreEqual(LOGOUT_URL, urlsOpened[0]); - List expectedEvents = new List{ - PassportAuthEvent.Reconnecting, - PassportAuthEvent.ReconnectSuccess, - PassportAuthEvent.LoggingOut, - PassportAuthEvent.LogoutSuccess - }; + var expectedEvents = new List + { + PassportAuthEvent.Reconnecting, + PassportAuthEvent.ReconnectSuccess, + PassportAuthEvent.LoggingOut, + PassportAuthEvent.LogoutSuccess + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -874,14 +893,15 @@ public async Task Reconnect_Failed() }; communicationsManager.AddMockResponse(reconnectResponse); - bool success = await passport.ConnectImx(useCachedSession: true); + var success = await passport.ConnectImx(true); Assert.False(success); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.Reconnecting, - PassportAuthEvent.ReconnectFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.Reconnecting, + PassportAuthEvent.ReconnectFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -891,14 +911,15 @@ public async Task Reconnect_CallFailed() { communicationsManager.throwExceptionOnCall = true; - bool success = await passport.ConnectImx(useCachedSession: true); + var success = await passport.ConnectImx(true); Assert.False(success); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.Reconnecting, - PassportAuthEvent.ReconnectFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.Reconnecting, + PassportAuthEvent.ReconnectFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -906,14 +927,15 @@ public async Task Reconnect_CallFailed() [Test] public async Task Reconnect_NullResponse_Failed() { - bool success = await passport.ConnectImx(useCachedSession: true); + var success = await passport.ConnectImx(true); Assert.False(success); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.Reconnecting, - PassportAuthEvent.ReconnectFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.Reconnecting, + PassportAuthEvent.ReconnectFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -932,7 +954,7 @@ public async Task GetAddress_Success() Assert.AreEqual(ADDRESS, address); Assert.AreEqual(PassportFunction.IMX.GET_ADDRESS, communicationsManager.fxName); - Assert.True(String.IsNullOrEmpty(communicationsManager.data)); + Assert.True(string.IsNullOrEmpty(communicationsManager.data)); } [Test] @@ -967,7 +989,7 @@ public async Task GetEmail_Success() Assert.AreEqual(EMAIL, email); Assert.AreEqual(PassportFunction.GET_EMAIL, communicationsManager.fxName); - Assert.True(String.IsNullOrEmpty(communicationsManager.data)); + Assert.True(string.IsNullOrEmpty(communicationsManager.data)); } [Test] @@ -1002,7 +1024,7 @@ public async Task GetPassportId_Success() Assert.AreEqual(PASSPORT_ID, passportId); Assert.AreEqual(PassportFunction.GET_PASSPORT_ID, communicationsManager.fxName); - Assert.True(String.IsNullOrEmpty(communicationsManager.data)); + Assert.True(string.IsNullOrEmpty(communicationsManager.data)); } [Test] @@ -1046,10 +1068,11 @@ public async Task Logout_Success() Assert.Null(e); Assert.AreEqual(1, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.LoggingOut, - PassportAuthEvent.LogoutSuccess - }; + var expectedEvents = new List + { + PassportAuthEvent.LoggingOut, + PassportAuthEvent.LogoutSuccess + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -1073,14 +1096,16 @@ public async Task Logout_FailedGetLogoutUrl() e = ex; } - LogAssert.Expect(LogType.Error, "[Immutable] [Passport Implementation] Failed to log out: Response is invalid!"); + LogAssert.Expect(LogType.Error, + "[Immutable] [Passport Implementation] Failed to log out: Response is invalid!"); Assert.NotNull(e); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.LoggingOut, - PassportAuthEvent.LogoutFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.LoggingOut, + PassportAuthEvent.LogoutFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -1105,14 +1130,16 @@ public async Task Logout_EmptyGetLogoutUrl() e = ex; } - LogAssert.Expect(LogType.Error, "[Immutable] [Passport Implementation] Failed to log out: Failed to get logout URL"); + LogAssert.Expect(LogType.Error, + "[Immutable] [Passport Implementation] Failed to log out: Failed to get logout URL"); Assert.NotNull(e); Assert.AreEqual(0, urlsOpened.Count); - List expectedEvents = new List{ - PassportAuthEvent.LoggingOut, - PassportAuthEvent.LogoutFailed - }; + var expectedEvents = new List + { + PassportAuthEvent.LoggingOut, + PassportAuthEvent.LogoutFailed + }; Assert.AreEqual(expectedEvents.Count, authEvents.Count); Assert.AreEqual(expectedEvents, authEvents); } @@ -1183,45 +1210,42 @@ public async Task GetLinkedAddresses_EmptyResponse() Assert.AreEqual(0, linkedAddresses.Count); } + +#pragma warning disable CS8618 + private MockBrowserCommsManager communicationsManager; + private TestPassportImpl passport; +#pragma warning restore CS8618 } internal class MockBrowserCommsManager : IBrowserCommunicationsManager { - public Queue responses = new Queue(); - public bool throwExceptionOnCall = false; - public string fxName = ""; public string data = ""; + public string fxName = ""; + public Queue responses = new(); + public bool throwExceptionOnCall; public event OnUnityPostMessageDelegate OnAuthPostMessage; public event OnUnityPostMessageErrorDelegate OnPostMessageError; - public void AddMockResponse(object response) - { - responses.Enqueue(JsonUtility.ToJson(response)); - } - - public UniTask Call(string fxName, string data = null, bool ignoreTimeout = false, Nullable timeoutMs = null) + public UniTask Call(string fxName, string data = null, bool ignoreTimeout = false, + long? timeoutMs = null) { if (throwExceptionOnCall) { Debug.Log("Error on call"); throw new PassportException("Error on call!"); } - else - { - this.fxName = fxName; - this.data = data; - string result = responses.Count > 0 ? responses.Dequeue() : ""; - BrowserResponse response = result.OptDeserializeObject(); - if (response == null || response?.success == false || !String.IsNullOrEmpty(response?.error)) - { - Debug.Log("No response"); - throw new PassportException("Response is invalid!"); - } - else - { - return UniTask.FromResult(result); - } + + this.fxName = fxName; + this.data = data; + var result = responses.Count > 0 ? responses.Dequeue() : ""; + var response = result.OptDeserializeObject(); + if (response == null || response?.success == false || !string.IsNullOrEmpty(response?.error)) + { + Debug.Log("No response"); + throw new PassportException("Response is invalid!"); } + + return UniTask.FromResult(result); } public void LaunchAuthURL(string url, string redirectUri) @@ -1232,5 +1256,10 @@ public void LaunchAuthURL(string url, string redirectUri) public void SetCallTimeout(int ms) { } + + public void AddMockResponse(object response) + { + responses.Enqueue(JsonUtility.ToJson(response)); + } } } \ No newline at end of file