diff --git a/.github/actions/notify-slack-publish-status/README.md b/.github/actions/notify-slack-publish-status/README.md
new file mode 100644
index 00000000..02993bbf
--- /dev/null
+++ b/.github/actions/notify-slack-publish-status/README.md
@@ -0,0 +1 @@
+# Slack Notify
diff --git a/.github/actions/notify-slack-publish-status/action.yml b/.github/actions/notify-slack-publish-status/action.yml
new file mode 100644
index 00000000..e6d9b24c
--- /dev/null
+++ b/.github/actions/notify-slack-publish-status/action.yml
@@ -0,0 +1,13 @@
+---
+name: 'Notify Slack Publish Status'
+description: 'Notify Slack with the completion status of the publish action'
+inputs:
+ message:
+ description: 'Message to send to Slack'
+ required: true
+ webhook-url:
+ description: 'Slack incoming webhook URL'
+ required: true
+runs:
+ using: 'node20'
+ main: 'index.js'
diff --git a/.github/actions/notify-slack-publish-status/index.js b/.github/actions/notify-slack-publish-status/index.js
new file mode 100644
index 00000000..f3db3597
--- /dev/null
+++ b/.github/actions/notify-slack-publish-status/index.js
@@ -0,0 +1,52 @@
+const core = require('@actions/core');
+const webhook = core.getInput('webhook-url');
+
+const run = async () => {
+ if (webhook) {
+ try {
+ await postSlackNotification();
+ } catch (e) {
+ console.log(e);
+ throw new Error(`failed because : ${e}`)
+ }
+ } else {
+ throw new Error('No SDK_PUBLISH_SLACK_WEBHOOK environment variable found');
+ }
+}
+
+const postSlackNotification = async () => {
+ const message = core.getInput('message');
+
+ if (!message) {
+ throw new Error('No message input found');
+ }
+
+ const options = {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ text: message,
+ blocks: [
+ {
+ type: 'section',
+ text: {
+ type: 'mrkdwn',
+ text: message,
+ }
+ }
+ ]
+ }),
+ };
+
+ const response = await fetch(webhook, options);
+
+ if (response.status == 200) {
+ console.log('Posted message to Slack successfully');
+ } else {
+ throw new Error(`Failed to post message to Slack. Status code: ${response.status}`);
+ }
+}
+
+run();
diff --git a/.github/actions/notify-slack-publish-status/package.json b/.github/actions/notify-slack-publish-status/package.json
new file mode 100644
index 00000000..bf0b0fa5
--- /dev/null
+++ b/.github/actions/notify-slack-publish-status/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "notify-slack-publish-status",
+ "version": "1.0.0",
+ "description": "Sends a Slack notification with a publish status.",
+ "main": "index.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "ISC",
+ "dependencies": {
+ "@actions/core": "^1.10.1"
+ }
+}
\ No newline at end of file
diff --git a/.github/scripts/aggregate-passport-metadata.js b/.github/scripts/aggregate-passport-metadata.js
index 98568cd7..0d2030f8 100755
--- a/.github/scripts/aggregate-passport-metadata.js
+++ b/.github/scripts/aggregate-passport-metadata.js
@@ -38,23 +38,23 @@ try {
// Find all feature group directories in _tutorials
const findFeatureGroupDirectories = () => {
const featureGroupDirs = [];
-
+
if (!fs.existsSync(TUTORIALS_DIR)) {
console.warn(`Tutorials directory does not exist: ${TUTORIALS_DIR}`);
return featureGroupDirs;
- }
-
- try {
+ }
+
+ try {
const dirs = fs.readdirSync(TUTORIALS_DIR, { withFileTypes: true });
dirs.forEach((dirent) => {
if (dirent.isDirectory()) {
featureGroupDirs.push(path.join(TUTORIALS_DIR, dirent.name));
- }
- });
- } catch (err) {
+ }
+ });
+ } catch (err) {
console.warn(`Error reading tutorials directory ${TUTORIALS_DIR}: ${err.message}`);
- }
+ }
return featureGroupDirs;
};
@@ -82,7 +82,7 @@ const processFeatureGroups = (featureGroupDirs) => {
if (!fs.existsSync(metadataPath)) {
console.warn(`No metadata.json found for feature group ${groupName} in ${groupDir}`);
return;
- }
+ }
// Path to tutorial.md in this feature group directory
const tutorialPath = path.join(groupDir, 'tutorial.md');
diff --git a/.github/scripts/process-passport-tutorials.sh b/.github/scripts/process-passport-tutorials.sh
index 903e51ae..a95be85e 100755
--- a/.github/scripts/process-passport-tutorials.sh
+++ b/.github/scripts/process-passport-tutorials.sh
@@ -12,16 +12,14 @@ TUTORIALS_DIR="${PASSPORT_ROOT}/_tutorials~"
echo "Processing Passport tutorials..."
-# Load features.json to get feature groups
FEATURES_JSON="${PASSPORT_ROOT}/features.json"
if [ ! -f "${FEATURES_JSON}" ]; then
echo "Error: features.json not found at ${FEATURES_JSON}"
exit 1
fi
-# Create _tutorials directory in docs repo
-DOCS_TUTORIALS_DIR="${DOCS_REPO_DIR}/docs/main/example/zkEVM/unity/passport-examples/_tutorials"
-mkdir -p "${DOCS_TUTORIALS_DIR}"
+# Base directory for usage guides in the docs repo
+DOCS_USAGE_GUIDES_DIR="${DOCS_REPO_DIR}/docs/main/build/unity/usage/passport"
# Check if _tutorials~ directory exists
if [ ! -d "${TUTORIALS_DIR}" ]; then
@@ -40,12 +38,16 @@ else
if [ -f "${TUTORIAL_FILE}" ]; then
echo "Found tutorial for ${GROUP_NAME}"
+ # Define the destination directory for this feature group
+ DEST_GROUP_DIR="${DOCS_USAGE_GUIDES_DIR}/_tutorials"
+ mkdir -p "${DEST_GROUP_DIR}"
+
# Use the folder name directly for the destination filename
OUTPUT_FILENAME="${GROUP_NAME}.md"
- # Copy the tutorial file
- cp "${TUTORIAL_FILE}" "${DOCS_TUTORIALS_DIR}/${OUTPUT_FILENAME}"
- echo "Copied ${TUTORIAL_FILE} to ${DOCS_TUTORIALS_DIR}/${OUTPUT_FILENAME}"
+ # Copy the tutorial file to its new group directory
+ cp "${TUTORIAL_FILE}" "${DEST_GROUP_DIR}/${OUTPUT_FILENAME}"
+ echo "Copied ${TUTORIAL_FILE} to ${DEST_GROUP_DIR}/${OUTPUT_FILENAME}"
else
echo "Warning: No tutorial.md found for feature group ${GROUP_NAME}"
fi
@@ -56,12 +58,12 @@ fi
JSON_FILE="./_parsed/passport-features.json"
if [ -f "${JSON_FILE}" ]; then
# Create directory for JSON file if it doesn't exist
- JSON_DIR="${DOCS_REPO_DIR}/docs/main/example/zkEVM/unity/passport-examples"
+ JSON_DIR="${DOCS_REPO_DIR}/docs/main/build/unity/usage/passport"
mkdir -p "${JSON_DIR}"
# Copy JSON file
- cp "${JSON_FILE}" "${JSON_DIR}/passport-features.json"
- echo "Copied ${JSON_FILE} to ${JSON_DIR}/passport-features.json"
+ cp "${JSON_FILE}" "${JSON_DIR}/passport-examples.json"
+ echo "Copied ${JSON_FILE} to ${JSON_DIR}/passport-examples.json"
else
echo "Warning: No passport-features.json found at ${JSON_FILE}"
fi
diff --git a/.github/workflows/publish-passport-tutorials.yml b/.github/workflows/publish-passport-tutorials.yml
index 47f2f255..ee310dfe 100644
--- a/.github/workflows/publish-passport-tutorials.yml
+++ b/.github/workflows/publish-passport-tutorials.yml
@@ -37,7 +37,7 @@ jobs:
repository: immutable/docs
token: ${{ secrets.UNITY_SDK_DOCS_WORKFLOW }}
path: imx-docs
- ref: 'main'
+ ref: 'DVR-295-docs-restructure'
- name: Setup environment variables
run: echo "CLONE_DIR=./imx-docs" >> $GITHUB_ENV
@@ -65,20 +65,39 @@ jobs:
.github/scripts/process-passport-tutorials.sh
shell: bash
- - name: Commit and Push Changes to Docs Repo
+ - name: Create Pull Request in Docs Repo
+ id: create_pr
run: |
cd "$CLONE_DIR"
- if git status --porcelain | grep -q .; then
- git add .
-
- # Commit with reference to source commit
- COMMIT_MSG="docs: Update Passport tutorials from Unity SDK (Ref: ${GITHUB_SHA::8})"
- git commit -m "$COMMIT_MSG"
-
- # Push to the target branch
- git push -u origin main
- echo "Successfully pushed Passport tutorial changes to docs repo"
- else
+ if ! git status --porcelain | grep -q .; then
echo "No changes to commit"
+ echo "pr_url=" >> $GITHUB_OUTPUT
+ exit 0
fi
- shell: bash
\ No newline at end of file
+
+ BRANCH_NAME="chore/unity-sdk-docs-update-${{ github.run_id }}"
+ git checkout -b $BRANCH_NAME
+
+ git add .
+ git commit -m "chore: example app usage guide updated"
+ git push -u origin $BRANCH_NAME
+ echo "Successfully pushed changes to docs repo on branch $BRANCH_NAME"
+
+ PR_URL=$(gh pr create \
+ --title "auto(unity-immutable-sdk): example app usage guide updated" \
+ --body "Automated PR from unity-immutable-sdk to update tutorials. This is safe for anyone to approve and merge." \
+ --base DVR-295-docs-restructure \
+ --repo immutable/docs)
+
+ echo "Successfully created PR in docs repo: $PR_URL"
+ echo "pr_url=${PR_URL}" >> $GITHUB_OUTPUT
+ env:
+ GITHUB_TOKEN: ${{ secrets.UNITY_SDK_DOCS_WORKFLOW }}
+ shell: bash
+
+ - name: Notify Slack
+ if: steps.create_pr.outputs.pr_url != ''
+ uses: ./.github/actions/notify-slack-publish-status
+ with:
+ message: 'New automated Unity SDK sample app tutorials PR is ready for review: ${{ steps.create_pr.outputs.pr_url }}'
+ webhook-url: ${{ secrets.SDK_DOCS_TUTORIALS_SLACK_WEBHOOK }}
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 6aaa93d8..7a5f7fad 100644
--- a/.gitignore
+++ b/.gitignore
@@ -109,4 +109,11 @@ __pycache__/
*.pyc
.pytest_cache/
-xcuserdata/
\ No newline at end of file
+xcuserdata/
+
+# Node.js dependencies and lock files
+**/node_modules/
+**/package-lock.json
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/Authentication/metadata.json b/sample/Assets/Scripts/Passport/_tutorials~/Authentication/metadata.json
index 61bd2f6d..f58269d1 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/Authentication/metadata.json
+++ b/sample/Assets/Scripts/Passport/_tutorials~/Authentication/metadata.json
@@ -1,8 +1,9 @@
{
- "title": "Immutable Passport Authentication",
- "description": "Implement user authentication in Unity games with Immutable Passport SDK, supporting both Device Code and PKCE flows",
- "keywords": ["Immutable", "SDK", "Authentication", "Login", "Logout", "Relogin", "Reconnect", "Passport", "Unity"],
- "tech_stack": ["Unity", "C#", "UniTask", "Immutable Passport SDK"],
+ "title": "Authentication with Immutable Passport SDK",
+ "description": "Complete authentication system demonstrating Login, Logout, Relogin, and Reconnect features using PKCE flow for secure user authentication and session management in Unity games",
+ "keywords": ["Immutable", "SDK", "Authentication", "Login", "Logout", "Relogin", "Reconnect", "PKCE", "OAuth", "Passport", "Session Management"],
+ "tech_stack": ["Unity", "C#", "UniTask", "PKCE", "OAuth 2.0"],
"product": "Passport",
- "programming_language": "C#"
+ "programming_language": "C#",
+ "sidebar_order": 20
}
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/Authentication/tutorial.md b/sample/Assets/Scripts/Passport/_tutorials~/Authentication/tutorial.md
index 219cebfe..ed2fa197 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/Authentication/tutorial.md
+++ b/sample/Assets/Scripts/Passport/_tutorials~/Authentication/tutorial.md
@@ -4,7 +4,7 @@
-The Authentication feature group provides essential tools for integrating user authentication into your Unity application using the Immutable Passport SDK. These features allow players to log in, log out, and maintain their authentication state across sessions, which is fundamental for any blockchain application.
+The Authentication feature group demonstrates the core authentication capabilities of the Immutable Passport SDK. These features enable secure user authentication and session management in Unity games, providing seamless login experiences across different platforms and maintaining user sessions between game sessions.
@@ -14,42 +14,32 @@ The Authentication feature group provides essential tools for integrating user a
## Authentication Overview
-The Authentication feature group contains four key features:
+The Authentication feature group includes four essential features that work together to provide a complete authentication system:
-- **Login**: Authenticate users using Device Code Auth or PKCE flow
-- **Logout**: End a user's authenticated session
-- **Relogin**: Restore a previously authenticated session using cached credentials
-- **Reconnect**: Restore authentication and blockchain connections in a single operation
+- **Login**: Primary authentication using PKCE (Proof Key for Code Exchange) flow
+- **Logout**: Secure session termination and credential cleanup
+- **Relogin**: Silent re-authentication using cached credentials
+- **Reconnect**: Re-authentication with automatic IMX provider setup
-These features work together to create a complete authentication flow for your application. The Login and Logout features handle the primary authentication process, while Relogin and Reconnect provide convenience methods for maintaining session state across application restarts or network interruptions.
+These features work together to create a seamless authentication experience. Login establishes the initial session, Relogin provides quick re-authentication without user interaction, Reconnect combines re-authentication with IMX connectivity, and Logout ensures secure session cleanup.
## Unity SDK Authentication Features
### Feature: Login
-The Login feature allows users to authenticate with Immutable Passport using either Device Code Auth or PKCE (Proof Key for Code Exchange) authentication flows.
+The Login feature implements the primary authentication flow using PKCE (Proof Key for Code Exchange), which opens the user's default browser on desktop or an in-app browser on mobile platforms for secure authentication.
-```csharp title="Login" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/Login/LoginScript.cs"
+```csharp title="Login Implementation" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/Login/LoginScript.cs"
public async void Login()
{
- var timeoutMs = GetDeviceCodeTimeoutMs();
- string formattedTimeout = timeoutMs != null ? $"{timeoutMs} ms" : "none";
- ShowOutput($"Logging in (timeout: {formattedTimeout})...");
try
{
- if (SampleAppManager.UsePKCE)
- {
- await Passport.LoginPKCE();
- }
- else
- {
- await Passport.Login(timeoutMs: timeoutMs);
- }
- NavigateToAuthenticatedScene();
+ await Passport.Login();
+ SceneManager.LoadScene("AuthenticatedScene");
}
- catch (OperationCanceledException)
+ catch (OperationCanceledException ex)
{
- ShowOutput("Failed to login: cancelled");
+ ShowOutput($"Failed to login: cancelled {ex.Message}\\n{ex.StackTrace}");
}
catch (Exception ex)
{
@@ -58,13 +48,18 @@ public async void Login()
}
```
-This implementation checks which authentication method to use based on the `SampleAppManager.UsePKCE` flag. For Device Code Auth (the default on non-WebGL platforms), it calls `Passport.Login()` with an optional timeout parameter. For PKCE auth (required for WebGL), it calls `Passport.LoginPKCE()`. Upon successful login, it navigates to the authenticated scene.
+The Login method uses the Passport SDK's PKCE authentication flow, which provides enhanced security by generating a code verifier and challenge. When successful, the user is automatically navigated to the authenticated scene where they can access protected features.
### Feature: Logout
-The Logout feature ends the user's authenticated session with Immutable Passport.
+The Logout feature securely terminates the user's session and cleans up stored credentials, ensuring proper session management and security.
+
+```csharp title="Logout Implementation" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/Logout/LogoutScript.cs"
+public void Logout()
+{
+ LogoutAsync();
+}
-```csharp title="Logout" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/Logout/LogoutScript.cs"
private async UniTaskVoid LogoutAsync()
{
if (Passport.Instance == null)
@@ -74,14 +69,7 @@ private async UniTaskVoid LogoutAsync()
}
try
{
- if (SampleAppManager.UsePKCE)
- {
- await Passport.Instance.LogoutPKCE();
- }
- else
- {
- await Passport.Instance.Logout();
- }
+ await Passport.Instance.Logout();
SampleAppManager.IsConnectedToImx = false;
SampleAppManager.IsConnectedToZkEvm = false;
AuthenticatedSceneManager.NavigateToUnauthenticatedScene();
@@ -93,13 +81,18 @@ private async UniTaskVoid LogoutAsync()
}
```
-Similar to the Login feature, Logout checks the authentication method and calls the appropriate logout function (`LogoutPKCE()` or `Logout()`). It also resets the connection states for IMX and zkEVM before navigating back to the unauthenticated scene.
+The Logout implementation not only calls the Passport logout method but also resets the application's connection states for both IMX and zkEVM, ensuring a clean slate for the next authentication session.
### Feature: Relogin
-The Relogin feature allows users to authenticate again using cached credentials, providing a smoother user experience for returning users.
+The Relogin feature enables silent re-authentication using previously stored credentials, providing a smooth user experience by avoiding repeated login prompts when credentials are still valid.
+
+```csharp title="Relogin Implementation" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/Relogin/ReloginScript.cs"
+public void Relogin()
+{
+ ReloginAsync();
+}
-```csharp title="Relogin" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/Relogin/ReloginScript.cs"
private async UniTaskVoid ReloginAsync()
{
if (Passport.Instance == null)
@@ -127,13 +120,13 @@ private async UniTaskVoid ReloginAsync()
}
```
-The Relogin feature calls `Passport.Instance.Login()` with the `useCachedSession` parameter set to `true`, which attempts to restore the user's previous session without requiring them to go through the full authentication flow again. If successful, it navigates to the authenticated scene.
+The Relogin feature uses the `useCachedSession: true` parameter to attempt authentication with stored credentials. This provides a seamless experience for returning users while gracefully handling cases where credentials may have expired.
### Feature: Reconnect
-The Reconnect feature combines re-authentication with reconnecting to blockchain services (IMX) in a single operation.
+The Reconnect feature combines re-authentication with automatic IMX provider setup, streamlining the process of restoring both authentication state and blockchain connectivity.
-```csharp title="Reconnect" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/Reconnect/ReconnectScript.cs"
+```csharp title="Reconnect Implementation" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/Reconnect/ReconnectScript.cs"
private async UniTaskVoid ReconnectAsync()
{
if (Passport.Instance == null)
@@ -147,7 +140,6 @@ private async UniTaskVoid ReconnectAsync()
bool connected = await Passport.Instance.ConnectImx(useCachedSession: true);
if (connected)
{
- // Set IMX and zkEVM state and update UI as if user clicked Connect to IMX/EVM
SampleAppManager.IsConnectedToImx = true;
SampleAppManager.IsConnectedToZkEvm = true;
SampleAppManager.PassportInstance = Passport.Instance;
@@ -171,50 +163,75 @@ private async UniTaskVoid ReconnectAsync()
}
```
-The Reconnect feature calls `Passport.Instance.ConnectImx()` with the `useCachedSession` parameter set to `true`, which not only tries to reestablish the authentication session but also reconnects to the IMX blockchain. If successful, it updates the connection states for both IMX and zkEVM, updates the UI, and navigates to the authenticated scene.
+The Reconnect feature uses `ConnectImx(useCachedSession: true)` to both authenticate the user and establish the IMX connection in a single operation. It also updates the UI state to reflect the successful connection to both IMX and zkEVM networks.
-## Running the Authentication Examples
+## Running the Feature Group Examples
### Prerequisites
-Before running the authentication examples, you need to:
+Before running the authentication examples, ensure you have:
-1. Set up an Immutable Hub account at [Immutable Hub](https://hub.immutable.com/)
-2. Clone the Unity Immutable SDK repository
-3. Open the sample app in Unity Editor (2022.3 LTS or newer recommended)
-4. Ensure you have the required packages installed (UniTask, TextMeshPro)
+- Unity 2021.3 or later installed
+- The Immutable Unity SDK properly configured in your project
+- Access to [Immutable Hub](https://hub.immutable.com/) for environment setup and configuration
+- A valid Passport client ID configured in your project
### Step-by-Step Instructions
-1. Open the sample app scene located at `sample/Assets/Scenes/Passport/InitialisationScene.unity`
-2. Enter Play mode in the Unity Editor
-3. In the Initialisation Scene:
- - For non-WebGL builds, choose between "Use Device Code Auth" or "Use PKCE"
- - For WebGL builds, PKCE is automatically selected
-4. After initialization, you'll be taken to the Unauthenticated Scene where you can:
- - Use "Login" to authenticate with a new session
- - Use "Relogin" to try authenticating with cached credentials
- - Use "Reconnect" to authenticate and reconnect to blockchain services
+1. **Open the Sample Project**
+ - Navigate to the `sample` directory in the Unity Immutable SDK
+ - Open the project in Unity Editor
+
+2. **Configure Passport Settings**
+ - Ensure your Passport client ID is properly set in the `PassportInitialisationScript.cs`
+ - Verify the redirect URIs match your application configuration
+
+3. **Run the Authentication Flow**
+ - Start with the PassportInitialisation scene to initialize the SDK
+ - The application will automatically navigate to the UnauthenticatedScene
+ - Test the Login feature by clicking the "Login" button
+ - After successful authentication, you'll be redirected to the AuthenticatedScene
-### Authentication Flow Sequence
+4. **Test Session Management**
+ - Use the Logout feature to terminate your session
+ - Return to the UnauthenticatedScene and test the Relogin feature
+ - Test the Reconnect feature to verify IMX connectivity restoration
-For optimal testing:
-1. Start with "Login" to create a new authenticated session
-2. Use the "Logout" button on the Authenticated Scene to end your session
-3. Try "Relogin" to test session restoration
-4. If you previously connected to IMX, try "Reconnect" to test combined authentication and blockchain reconnection
+5. **Verify State Management**
+ - Check that connection states (IMX/zkEVM) are properly updated
+ - Ensure UI elements reflect the current authentication and connection status
+
+### Sequence Dependencies
+
+The authentication features should be tested in this recommended sequence:
+1. **Login** - Establish initial authentication
+2. **Logout** - Test session termination
+3. **Relogin** - Test cached credential authentication
+4. **Reconnect** - Test authentication with IMX connectivity
## Summary
-The Authentication feature group provides a comprehensive set of tools for handling user authentication in your Unity application with Immutable Passport. It supports both Device Code Auth and PKCE authentication methods, allowing for cross-platform compatibility including WebGL builds.
+The Authentication feature group provides a comprehensive authentication system for Unity games using the Immutable Passport SDK. The four features work together to cover all aspects of user session management:
+
+- **Login** handles initial user authentication using secure PKCE flow
+- **Logout** ensures proper session cleanup and security
+- **Relogin** provides seamless re-authentication for returning users
+- **Reconnect** combines authentication with blockchain connectivity setup
### Best Practices
-- Initialize Passport before attempting any authentication operations
-- Handle authentication exceptions appropriately in your implementation
-- For WebGL applications, always use PKCE authentication
-- For returning users, try the Relogin or Reconnect features before falling back to a full Login
-- Always check if the Passport instance exists before attempting operations
-- Clear connection states when logging out to maintain proper application state
+When implementing these authentication features:
+
+- Always check for null Passport instances before making authentication calls
+- Implement proper error handling for network issues and authentication failures
+- Update application state consistently after authentication state changes
+- Use the cached session options appropriately to improve user experience
+- Ensure UI state reflects the current authentication and connection status
+
+### Key Takeaways
-These authentication features provide the foundation for all other Immutable operations in your Unity application, as users must be authenticated before interacting with blockchain services like IMX and zkEVM.
\ No newline at end of file
+- The PKCE authentication flow provides enhanced security for OAuth 2.0 authentication
+- Cached sessions enable seamless re-authentication without user interaction
+- Proper state management is crucial for maintaining consistent application behavior
+- The Reconnect feature streamlines the process of restoring both authentication and blockchain connectivity
+- All authentication operations are asynchronous and require proper exception handling
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/ClearStorageAndCache/metadata.json b/sample/Assets/Scripts/Passport/_tutorials~/ClearStorageAndCache/metadata.json
index b62c8d82..d520ddef 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/ClearStorageAndCache/metadata.json
+++ b/sample/Assets/Scripts/Passport/_tutorials~/ClearStorageAndCache/metadata.json
@@ -1,8 +1,9 @@
{
- "title": "Clear Storage and Cache on Mobile Devices",
- "description": "Learn how to clear WebView storage and cache on Android and iOS devices using the Immutable Passport SDK",
- "keywords": ["Immutable", "SDK", "ClearStorageAndCache", "Mobile", "Android", "iOS", "WebView"],
- "tech_stack": ["Unity", "C#", "WebView"],
+ "title": "Clear Storage and Cache - WebView Management in Immutable Passport",
+ "description": "Learn how to properly clear WebView cache and storage data in Immutable Passport applications for Android and iOS devices, ensuring optimal performance and user experience",
+ "keywords": ["Immutable", "SDK", "Clear Storage", "Clear Cache", "WebView", "Mobile", "Android", "iOS", "Authentication", "Maintenance", "Passport"],
+ "tech_stack": ["Unity", "C#", "WebView", "Immutable Passport SDK"],
"product": "Passport",
- "programming_language": "C#"
+ "programming_language": "C#",
+ "sidebar_order": 30
}
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/ClearStorageAndCache/tutorial.md b/sample/Assets/Scripts/Passport/_tutorials~/ClearStorageAndCache/tutorial.md
index 7284509f..e3667b06 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/ClearStorageAndCache/tutorial.md
+++ b/sample/Assets/Scripts/Passport/_tutorials~/ClearStorageAndCache/tutorial.md
@@ -4,7 +4,7 @@
-The Clear Storage and Cache feature in the Immutable Passport SDK provides a way to clear WebView storage and cache on mobile devices (Android and iOS). This is particularly useful for testing login flows, handling user log out completely, or managing authentication state for your application.
+The Clear Storage and Cache feature provides essential WebView maintenance functionality for mobile applications using Immutable Passport. This feature allows developers to clear the underlying WebView's cached resources and JavaScript storage data, which is crucial for troubleshooting authentication issues, managing storage space, and ensuring clean application states on Android and iOS devices.
@@ -12,16 +12,24 @@ The Clear Storage and Cache feature in the Immutable Passport SDK provides a way
-#### Unity SDK Clear Storage and Cache Implementation
+## Feature Introduction
-The Clear Storage and Cache feature provides two main functions:
+The Clear Storage and Cache feature demonstrates how to use Immutable Passport's WebView maintenance capabilities to clear cached data and storage. This functionality is particularly valuable for:
-1. `ClearStorage()` - Clears all underlying WebView storage currently being used by JavaScript storage APIs, including Web SQL Database and HTML5 Web Storage APIs.
-2. `ClearCache(bool includeDiskFiles)` - Clears the underlying WebView resource cache, with an option to include disk files.
+- Resolving authentication issues by clearing stale session data
+- Managing device storage by removing cached resources
+- Ensuring clean application states during development and testing
+- Troubleshooting WebView-related problems
-##### Feature: Clear Storage and Cache
+This feature is only available on Android and iOS devices, as it directly interacts with the native WebView components used by Passport for authentication and communication.
-```csharp title="ClearStorageAndCacheScript" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/ClearStorageAndCache/ClearStorageAndCacheScript.cs"
+## Unity SDK Clear Storage and Cache Implementation
+
+### Feature: Clear Storage and Cache
+
+The Clear Storage and Cache feature provides two distinct but complementary operations for maintaining WebView data:
+
+```csharp title="Clear Storage and Cache" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/ClearStorageAndCache/ClearStorageAndCacheScript.cs"
public void ClearStorageAndCache()
{
if (Passport.Instance == null)
@@ -46,41 +54,77 @@ public void ClearStorageAndCache()
}
```
-The implementation is straightforward:
+The implementation demonstrates several key aspects:
+
+**Platform Availability**: The feature uses conditional compilation directives to ensure it only executes on Android and iOS devices. In the Unity editor or other platforms, it displays an informative message about platform limitations.
+
+**Passport Instance Validation**: Before attempting to clear data, the code verifies that the Passport instance has been properly initialized, providing clear feedback if initialization is required.
+
+**Dual Clearing Operations**: The feature calls both `ClearStorage()` and `ClearCache(true)` methods:
+- `ClearStorage()` removes JavaScript storage data including localStorage, sessionStorage, WebSQL databases, and IndexedDB data
+- `ClearCache(true)` clears the WebView's resource cache, with the `true` parameter indicating that disk-based cache files should also be removed
+
+**User Feedback**: The implementation provides clear status messages to inform users about the operation's progress and completion, enhancing the debugging and development experience.
+
+## Running the Feature Example
+
+### Prerequisites
+
+Before running the Clear Storage and Cache example, ensure you have:
+
+- Unity 2022.3 LTS or later installed
+- Immutable Passport SDK properly configured in your project
+- A valid Passport client ID from [Immutable Hub](https://hub.immutable.com)
+- An Android or iOS device for testing (this feature is not available in the Unity editor)
+
+### Step-by-Step Instructions
+
+1. **Open the Sample Project**
+ - Navigate to the Unity sample project in the SDK repository
+ - Open the project in Unity Editor
+
+2. **Configure Passport Settings**
+ - Ensure your Passport client ID is properly configured
+ - Verify that redirect URLs are set up correctly in Immutable Hub
-1. First, it checks if the Passport instance has been initialized
-2. Then, based on the platform:
- - On Android and iOS devices, it calls `ClearStorage()` to clear WebView storage and `ClearCache(true)` to clear the WebView cache including disk files
- - On other platforms, it displays a message indicating that the feature is only available on mobile devices
+3. **Build for Mobile Platform**
+ - Switch to Android or iOS build target in Build Settings
+ - Configure platform-specific settings as needed
+ - Build and deploy to your target device
-Note that this feature is specifically designed for mobile platforms (Android and iOS) and is not available in the Unity Editor or on desktop platforms.
+4. **Initialize Passport**
+ - Launch the application on your mobile device
+ - Navigate to the Passport initialization section
+ - Complete the Passport initialization process
-#### Running the Feature Example
+5. **Test Clear Storage and Cache**
+ - Locate the "Clear Storage & Cache" button in the sample application
+ - Tap the button to execute the clearing operation
+ - Observe the status messages confirming the operation completion
-##### Prerequisites
+6. **Verify Results**
+ - Check that cached authentication data has been cleared
+ - Verify that subsequent authentication flows work as expected
+ - Monitor device storage to confirm cache reduction
-1. Make sure you have set up your Unity project with the Immutable Passport SDK. For detailed setup instructions, visit [Immutable Hub](https://hub.immutable.com/).
-2. For testing on mobile devices, you need to build the application for Android or iOS.
+### Development Considerations
-##### Steps to Run the Example
+When integrating this feature into your own application, consider:
-1. Open the sample project in Unity
-2. Configure the Passport SDK with your application credentials
-3. Build and deploy the application to an Android or iOS device
-4. Navigate to the ClearStorageAndCache feature in the sample app
-5. First login to Passport to initialize the SDK
-6. Click the "Clear Storage and Cache" button to execute the feature
-7. The application will display a message indicating that the storage and cache have been cleared
+- **Timing**: Only call these methods when necessary, as clearing cache and storage will require users to re-authenticate
+- **User Experience**: Provide clear communication to users about what data will be cleared and why
+- **Error Handling**: Implement appropriate error handling for edge cases where clearing operations might fail
+- **Platform Detection**: Always check platform availability before calling these methods
-Note: This feature is particularly useful when testing authentication flows or when you need to clear user data from the device.
+## Summary
-#### Summary
+The Clear Storage and Cache feature provides essential WebView maintenance capabilities for Immutable Passport applications on mobile platforms. By offering both cache clearing and storage clearing operations, developers can effectively manage WebView data, resolve authentication issues, and maintain optimal application performance.
-The Clear Storage and Cache feature provides a simple way to clear WebView storage and cache on mobile devices. This is useful for:
+Key takeaways for developers:
-- Testing authentication flows
-- Ensuring user privacy by clearing stored data
-- Resolving WebView caching issues
-- Completely logging out users and removing saved credentials
+- **Mobile-Only Functionality**: This feature is exclusively available on Android and iOS devices due to its direct interaction with native WebView components
+- **Dual-Purpose Operations**: The feature provides both cache clearing (for resource management) and storage clearing (for session data management)
+- **Development Tool**: Particularly valuable during development and testing phases for ensuring clean application states
+- **User Impact Awareness**: Clearing storage and cache will require users to re-authenticate, so use judiciously in production applications
-When implementing this feature in your own application, remember that it is only available on Android and iOS devices, and requires that the Passport SDK is properly initialized before use.
\ No newline at end of file
+This feature exemplifies best practices for WebView maintenance in Unity applications, providing developers with the tools needed to maintain robust and reliable authentication experiences across mobile platforms.
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/GetUserInfo/metadata.json b/sample/Assets/Scripts/Passport/_tutorials~/GetUserInfo/metadata.json
index 867f4dcf..31fe74cd 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/GetUserInfo/metadata.json
+++ b/sample/Assets/Scripts/Passport/_tutorials~/GetUserInfo/metadata.json
@@ -1,8 +1,9 @@
{
- "title": "Retrieving User Information from Passport",
- "description": "Learn how to retrieve authenticated user information including email, Passport ID, access token, ID token, and linked wallet addresses using Immutable Passport SDK.",
- "keywords": ["Immutable", "SDK", "GetUserInfo", "Passport", "Authentication", "User Information", "Access Token", "ID Token"],
- "tech_stack": ["Unity", "C#", "Cysharp.Threading.Tasks"],
+ "title": "Unity SDK User Information Retrieval",
+ "description": "Demonstrates how to retrieve user information from Immutable Passport including email, Passport ID, authentication tokens, and linked wallet addresses",
+ "keywords": ["Immutable", "SDK", "GetUserInfo", "Passport", "Authentication", "User Profile", "Email", "Tokens", "Wallet Addresses"],
+ "tech_stack": ["Unity", "C#", "UniTask", "Immutable Passport"],
"product": "Passport",
- "programming_language": "C#"
+ "programming_language": "C#",
+ "sidebar_order": 40
}
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/GetUserInfo/tutorial.md b/sample/Assets/Scripts/Passport/_tutorials~/GetUserInfo/tutorial.md
index abe82765..d2fdf373 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/GetUserInfo/tutorial.md
+++ b/sample/Assets/Scripts/Passport/_tutorials~/GetUserInfo/tutorial.md
@@ -1,103 +1,138 @@
-# Get User Info
+# Unity SDK User Information Retrieval
-The Passport GetUserInfo feature group provides methods to access authenticated user information from Immutable Passport. This feature group enables developers to retrieve important user identifiers, authentication tokens, and linked wallet addresses that can be used for user management, authentication verification, and integration with other systems.
+The GetUserInfo feature demonstrates how to retrieve various types of user information from Immutable Passport, including email addresses, Passport IDs, authentication tokens, and linked wallet addresses. This feature is essential for games that need to access user profile data and manage user accounts effectively.
-[View feature group on Github](https://github.com/immutable/unity-immutable-sdk/tree/main/sample/Assets/Scripts/Passport/GetUserInfo) →
+[View feature on Github](https://github.com/immutable/unity-immutable-sdk/tree/main/sample/Assets/Scripts/Passport/GetUserInfo) →
-## GetUserInfo Overview
+## Unity SDK GetUserInfo Implementation
-The GetUserInfo feature group consists of a single feature that provides multiple methods to retrieve different pieces of user information:
-
-- Get user email
-- Get Passport ID
-- Get access token
-- Get ID token
-- Get linked addresses
-
-These methods help developers access authenticated user data that can be used for user management, displaying user information, or integrating with other systems that require authentication tokens.
-
-## Unity SDK GetUserInfo Features
+The GetUserInfo feature provides five core methods for retrieving different types of user information from Passport:
### Feature: GetUserInfo
-The GetUserInfo feature provides several methods to retrieve authenticated user information from Immutable Passport.
-
-```csharp title="GetUserInfo" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/GetUserInfo/GetUserInfoScript.cs"
-// Retrieving the user's email
-string email = await Passport.Instance.GetEmail();
-
-// Retrieving the user's Passport ID
-string passportId = await Passport.Instance.GetPassportId();
-
-// Retrieving the user's access token
-string accessToken = await Passport.Instance.GetAccessToken();
-
-// Retrieving the user's ID token
-string idToken = await Passport.Instance.GetIdToken();
-
-// Retrieving the user's linked external wallets
-List addresses = await Passport.Instance.GetLinkedAddresses();
+The GetUserInfo feature enables developers to access comprehensive user information from authenticated Passport accounts. This includes personal details, authentication credentials, and linked external wallet addresses, making it a crucial component for user profile management and account verification.
+
+```csharp title="GetUserInfo Methods" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/GetUserInfo/GetUserInfoScript.cs"
+// Get user's email address
+public async void GetEmail()
+{
+ try
+ {
+ string email = await Passport.Instance.GetEmail();
+ ShowOutput(email);
+ }
+ catch (System.Exception ex)
+ {
+ ShowOutput($"Failed to get email: {ex.Message}");
+ }
+}
+
+// Get user's Passport ID
+public async void GetPassportId()
+{
+ try
+ {
+ string passportId = await Passport.Instance.GetPassportId();
+ ShowOutput(passportId);
+ }
+ catch (System.Exception ex)
+ {
+ ShowOutput($"Failed to get Passport ID: {ex.Message}");
+ }
+}
+
+// Get user's access token
+public async void GetAccessToken()
+{
+ try
+ {
+ string accessToken = await Passport.Instance.GetAccessToken();
+ ShowOutput(accessToken);
+ }
+ catch (System.Exception ex)
+ {
+ ShowOutput($"Failed to get access token: {ex.Message}");
+ }
+}
+
+// Get user's ID token
+public async void GetIdToken()
+{
+ try
+ {
+ string idToken = await Passport.Instance.GetIdToken();
+ ShowOutput(idToken);
+ }
+ catch (System.Exception ex)
+ {
+ ShowOutput($"Failed to get ID token: {ex.Message}");
+ }
+}
+
+// Get user's linked external wallet addresses
+public async void GetLinkedAddresses()
+{
+ try
+ {
+ List addresses = await Passport.Instance.GetLinkedAddresses();
+ string outputMessage = addresses.Count > 0 ? string.Join(", ", addresses) : "No linked addresses";
+ ShowOutput(outputMessage);
+ }
+ catch (System.Exception ex)
+ {
+ ShowOutput($"Failed to get linked addresses: {ex.Message}");
+ }
+}
```
-#### How It Works
-
-The GetUserInfo feature provides a simple interface to access user information from the authenticated Passport session:
+The implementation uses async/await patterns with UniTask for non-blocking operations and includes comprehensive error handling. Each method checks for Passport instance availability before making API calls, ensuring robust operation. The GetLinkedAddresses method specifically handles both populated and empty address lists, providing clear feedback to users about their linked wallet status.
-1. **GetEmail()**: Retrieves the email address associated with the user's Passport account. This is useful for user identification and communication purposes.
-
-2. **GetPassportId()**: Returns the unique identifier for the user's Passport account. This ID can be used to uniquely identify users in your application.
-
-3. **GetAccessToken()**: Provides the OAuth access token that can be used to make authenticated API calls to Immutable services or your own backend services. This token proves the user's identity and authorization.
-
-4. **GetIdToken()**: Returns the ID token containing the user's identity information in JWT format. This token can be decoded to access additional user profile information.
-
-5. **GetLinkedAddresses()**: Retrieves a list of external wallet addresses that the user has linked to their Passport account. This is useful for identifying which external wallets the user has associated with their account.
-
-All methods are asynchronous and return `UniTask` results, which can be awaited in async methods. Each method performs validation checks on the Passport instance before attempting to retrieve information, and proper error handling is implemented to catch and report any exceptions.
-
-## Running the GetUserInfo Example
+## Running the Feature Example
### Prerequisites
-- Unity Editor (2020.3 LTS or later)
-- Immutable SDK imported into your project
-- Configured Immutable Hub environment ([Configure Immutable Hub](https://docs.immutable.com/docs/x/sdks/unity))
+- Unity 2021.3 or newer
+- Immutable Unity SDK installed
+- [Immutable Hub](https://hub.immutable.com) account for environment configuration
+- Active Passport authentication session
-### Steps to Run the Example
+### Step-by-Step Instructions
-1. Open the sample app in Unity Editor.
-2. Ensure you have already set up and initialized Passport. You must be logged in to retrieve user information.
-3. Navigate to the GetUserInfo scene or component in the sample app.
-4. Each user information method can be tested by clicking the corresponding button in the UI:
- - Click "Get Email" to retrieve the user's email address
- - Click "Get Passport ID" to retrieve the user's Passport ID
- - Click "Get Access Token" to retrieve the user's access token
- - Click "Get ID Token" to retrieve the user's ID token
- - Click "Get Linked Addresses" to retrieve the user's linked wallet addresses
-5. The retrieved information will be displayed in the output text field.
+1. **Open the Sample Project**
+ - Navigate to the Unity sample project in the SDK
+ - Open the `AuthenticatedScene` scene
-Note: You must successfully authenticate (log in) with Passport before you can retrieve user information. If not logged in, the methods will return appropriate error messages.
+2. **Ensure Passport Authentication**
+ - The user must be logged in through Passport before accessing user information
+ - Use the Authentication features to log in if not already authenticated
-## Summary
+3. **Test User Information Retrieval**
+ - Click the "Get Email" button to retrieve the user's email address
+ - Click the "Get Passport ID" button to get the unique Passport identifier
+ - Click the "Get Access Token" button to retrieve the current access token
+ - Click the "Get ID Token" button to get the ID token
+ - Click the "Get Linked Addresses" button to view connected external wallets
-The GetUserInfo feature group provides essential functionality for accessing authenticated user information from Immutable Passport. With these methods, developers can:
+4. **Verify Results**
+ - Check the output display for successful data retrieval
+ - Observe error messages if the user is not authenticated or if network issues occur
+ - Test with different authentication states to understand the feature's behavior
-- Access user identifiers for account management
-- Retrieve authentication tokens for API requests
-- Get linked wallet addresses for blockchain interactions
+## Summary
-Best practices when using the GetUserInfo feature:
+The GetUserInfo feature provides comprehensive access to user profile information and authentication credentials within Immutable Passport. It demonstrates best practices for async API calls, error handling, and user data management in Unity games. Developers can use these methods to create personalized user experiences, implement account verification systems, and manage user profiles effectively.
-1. Always check if the user is authenticated before attempting to retrieve user information
-2. Implement proper error handling for cases where retrieving information fails
-3. Store sensitive information (like access tokens) securely, following security best practices
-4. Use the appropriate method for your specific needs rather than retrieving all information unnecessarily
-5. Consider caching non-sensitive information to reduce API calls
\ No newline at end of file
+Key takeaways for developers:
+- Always verify Passport instance availability before making API calls
+- Implement proper error handling for network and authentication failures
+- Use async/await patterns to maintain responsive UI during API operations
+- Handle empty or null responses gracefully to provide clear user feedback
+- Consider user privacy when displaying sensitive information like tokens and email addresses
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/Imx/metadata.json b/sample/Assets/Scripts/Passport/_tutorials~/Imx/metadata.json
deleted file mode 100644
index 85491a03..00000000
--- a/sample/Assets/Scripts/Passport/_tutorials~/Imx/metadata.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "title": "Immutable X Integration with Passport SDK",
- "description": "How to integrate Immutable X features in your Unity game, including connecting to IMX, registering users, retrieving wallet addresses, and transferring NFTs",
- "keywords": ["Immutable", "SDK", "Imx", "ImxConnect", "ImxRegister", "ImxGetAddress", "ImxNftTransfer", "ImxIsRegisteredOffchain", "NFT", "Blockchain"],
- "tech_stack": ["Unity", "C#", "Passport SDK", "Immutable X", "Blockchain"],
- "product": "Passport",
- "programming_language": "C#"
-}
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/Imx/tutorial.md b/sample/Assets/Scripts/Passport/_tutorials~/Imx/tutorial.md
deleted file mode 100644
index d89da348..00000000
--- a/sample/Assets/Scripts/Passport/_tutorials~/Imx/tutorial.md
+++ /dev/null
@@ -1,297 +0,0 @@
-
-
-# Immutable X Integration
-
-
-
-Immutable X is a Layer 2 scaling solution for NFTs on Ethereum that provides gas-free minting and trading. The Passport SDK enables your Unity game to integrate seamlessly with Immutable X, giving your players the ability to connect to IMX, check registration status, register if needed, retrieve wallet addresses, and transfer NFTs.
-
-
-
-[View feature group on Github](https://github.com/immutable/unity-immutable-sdk/tree/main/sample/Assets/Scripts/Passport) →
-
-
-
-## Immutable X Overview
-
-The Imx feature group includes the following features:
-
-- **ImxConnect**: Connect to Immutable X using saved credentials
-- **ImxRegister**: Register the user with Immutable X (off-chain)
-- **ImxGetAddress**: Retrieve the user's Immutable X wallet address
-- **ImxNftTransfer**: Transfer NFTs to specified receivers
-- **ImxIsRegisteredOffchain**: Check if the user is registered off-chain with Immutable X
-
-These features work together to provide a complete Immutable X integration flow. First, you connect to IMX, then check if the user is registered. If not, you can register them. Once registered, you can retrieve their wallet address and perform NFT transfers.
-
-## Unity SDK Immutable X Features
-
-### Feature: ImxConnect
-
-Connect users to Immutable X by initializing the user's wallet and setting up the Immutable X provider using saved credentials.
-
-```csharp title="ImxConnectScript.cs" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/ImxConnect/ImxConnectScript.cs"
-public async UniTaskVoid ConnectImxAsync()
-{
- if (Passport.Instance == null)
- {
- ShowOutput("Passport instance is null");
- return;
- }
- // Set the static property for global access
- SampleAppManager.PassportInstance = Passport.Instance;
- ShowOutput("Connecting to Passport using saved credentials...");
- try
- {
- await Passport.Instance.ConnectImx();
-
- SampleAppManager.IsConnectedToImx = true;
- ShowOutput("Connected to IMX");
-
- // Update UI states based on connection
- var authSceneManager = FindObjectOfType();
- if (authSceneManager != null)
- {
- authSceneManager.UpdateImxButtonStates();
- authSceneManager.OnImxConnected?.Invoke();
- }
- }
- catch (System.Exception ex)
- {
- ShowOutput($"Failed to connect to IMX: {ex.Message}");
- }
-}
-```
-
-The `ConnectImx` method initializes the connection to Immutable X through the Passport SDK. It uses an async operation with UniTask to connect without blocking the main thread. After successful connection, it updates the static `SampleAppManager.IsConnectedToImx` flag and notifies the scene manager to update UI elements accordingly.
-
-### Feature: ImxIsRegisteredOffchain
-
-Check whether a user is registered off-chain with Immutable X.
-
-```csharp title="ImxIsRegisteredOffchainScript.cs" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/ImxIsRegisteredOffchain/ImxIsRegisteredOffchainScript.cs"
-private async UniTaskVoid CheckIsRegisteredOffchainAsync()
-{
- if (Passport.Instance == null)
- {
- ShowOutput("Passport not initialised.");
- return;
- }
-
- if (!SampleAppManager.IsConnectedToImx)
- {
- ShowOutput("Please connect to Immutable X first.");
- return;
- }
-
- ShowOutput("Checking if registered offchain...");
- try
- {
- bool isRegistered = await SampleAppManager.PassportInstance.IsRegisteredOffchain();
-
- if (isRegistered)
- {
- ShowOutput("Registered");
- }
- else
- {
- ShowOutput("User is NOT registered offchain.");
- }
- }
- catch (System.Exception ex)
- {
- ShowOutput($"Failed to check registration: {ex.Message}");
- }
-}
-```
-
-This feature first verifies that the user is connected to IMX before checking if they're registered off-chain. The `IsRegisteredOffchain` method returns a boolean indicating registration status, which determines whether the user can perform operations like transferring NFTs.
-
-### Feature: ImxRegister
-
-Register the user with Immutable X to enable off-chain operations.
-
-```csharp title="ImxRegisterScript.cs" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/ImxRegister/ImxRegisterScript.cs"
-public async void RegisterOffchain()
-{
- ShowOutput("Registering off-chain...");
- try
- {
- RegisterUserResponse response = await Passport.RegisterOffchain();
- if (response != null)
- {
- ShowOutput($"Successfully registered");
- }
- else
- {
- ShowOutput("Registration failed");
- }
- }
- catch (PassportException e)
- {
- ShowOutput($"Unable to register off-chain: {e.Message} ({e.Type})");
- }
- catch (Exception e)
- {
- ShowOutput($"Unable to register off-chain {e.Message}");
- }
-}
-```
-
-The `RegisterOffchain` method handles user registration with Immutable X. It returns a `RegisterUserResponse` object containing information about the registration. This step is required before users can perform operations like transferring assets on the Immutable X platform.
-
-### Feature: ImxGetAddress
-
-Retrieve the user's Immutable X wallet address.
-
-```csharp title="ImxGetAddressScript.cs" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/ImxGetAddress/ImxGetAddressScript.cs"
-public async void GetAddress()
-{
- ShowOutput("Retrieving wallet address...");
- try
- {
- string address = await Passport.GetAddress();
- ShowOutput(string.IsNullOrEmpty(address) ? "No address found" : address);
- }
- catch (PassportException e)
- {
- ShowOutput($"Unable to retrieve address: {e.Message} ({e.Type})");
- }
- catch (Exception)
- {
- ShowOutput("Unable to retrieve address");
- }
-}
-```
-
-The `GetAddress` method retrieves the wallet address associated with the user's Immutable X account. This address is essential for identifying the user in blockchain transactions and can be used for various operations like checking balances or transaction history.
-
-### Feature: ImxNftTransfer
-
-Transfer NFTs to specified receivers.
-
-```csharp title="ImxNftTransferScript.cs" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/ImxNftTransfer/ImxNftTransferScript.cs"
-private async UniTaskVoid TransferAsync()
-{
- if (Passport.Instance == null)
- {
- ShowOutput("Passport instance is null");
- return;
- }
- if (!string.IsNullOrWhiteSpace(TokenIdInput1.text) &&
- !string.IsNullOrWhiteSpace(TokenAddressInput1.text) &&
- !string.IsNullOrWhiteSpace(ReceiverInput1.text))
- {
- ShowOutput("Transferring NFTs...");
- try
- {
- List transferDetails = GetTransferDetails();
- if (transferDetails.Count > 1)
- {
- CreateBatchTransferResponse response = await Passport.Instance.ImxBatchNftTransfer(transferDetails.ToArray());
- ShowOutput($"Successfully transferred {response.transfer_ids.Length} NFTs.");
- }
- else
- {
- NftTransferDetails nftTransferDetail = transferDetails[0];
- UnsignedTransferRequest transferRequest = UnsignedTransferRequest.ERC721(
- nftTransferDetail.receiver,
- nftTransferDetail.tokenId,
- nftTransferDetail.tokenAddress
- );
- CreateTransferResponseV1 response = await Passport.Instance.ImxTransfer(transferRequest);
- ShowOutput($"NFT transferred successfully. Transfer ID: {response.transfer_id}");
- }
- }
- catch (System.Exception ex)
- {
- ShowOutput($"Failed to transfer NFTs: {ex.Message}");
- }
- }
- else
- {
- ShowOutput("Please fill in all required fields for the first NFT transfer.");
- }
-}
-
-private List GetTransferDetails()
-{
- List details = new List();
- if (!string.IsNullOrWhiteSpace(TokenIdInput1.text) &&
- !string.IsNullOrWhiteSpace(TokenAddressInput1.text) &&
- !string.IsNullOrWhiteSpace(ReceiverInput1.text))
- {
- details.Add(new NftTransferDetails(
- ReceiverInput1.text,
- TokenIdInput1.text,
- TokenAddressInput1.text
- ));
- }
- if (!string.IsNullOrWhiteSpace(TokenIdInput2.text) &&
- !string.IsNullOrWhiteSpace(TokenAddressInput2.text) &&
- !string.IsNullOrWhiteSpace(ReceiverInput2.text))
- {
- details.Add(new NftTransferDetails(
- ReceiverInput2.text,
- TokenIdInput2.text,
- TokenAddressInput2.text
- ));
- }
- return details;
-}
-```
-
-The `ImxNftTransfer` feature demonstrates how to transfer NFTs to specified recipients. The code supports both single and batch transfers, depending on how many inputs are provided. For batch transfers, it uses the `ImxBatchNftTransfer` method, while for single transfers, it uses the `ImxTransfer` method with an `UnsignedTransferRequest` object.
-
-## Running the Feature Group Examples
-
-### Prerequisites
-
-1. Create an account on [Immutable Hub](https://hub.immutable.com/) to set up your development environment
-2. Set up the Unity Editor with the Immutable Passport SDK installed
-3. Configure your Passport settings with your application's client ID and redirect URLs
-
-### Step-by-Step Instructions
-
-1. **Connect to Immutable X**
- - Open the sample scene containing the IMX features
- - Click the "Connect" button to initialize the connection to Immutable X
- - Confirm your connection is successful when "Connected to IMX" message appears
-
-2. **Check Registration Status**
- - After connecting, click the "Check Registration" button to verify if your account is registered off-chain
- - If the result shows "Not registered", proceed to the next step
-
-3. **Register Off-chain**
- - Click the "Register" button to register your account with Immutable X
- - Wait for the "Successfully registered" message to confirm completion
-
-4. **Get Wallet Address**
- - Click the "Get Address" button to retrieve your Immutable X wallet address
- - The address will be displayed in the output field
-
-5. **Transfer NFTs**
- - Navigate to the NFT Transfer screen
- - Enter the token ID, token address, and receiver address for the NFT you want to transfer
- - Click "Transfer" to initiate the transfer
- - Wait for the success message with the transfer ID
-
-### Feature Sequence Dependencies
-
-For proper functionality, follow this sequence:
-1. Connect to IMX first (ImxConnect)
-2. Check registration status (ImxIsRegisteredOffchain)
-3. Register if needed (ImxRegister)
-4. Then proceed with address retrieval (ImxGetAddress) and transfers (ImxNftTransfer)
-
-## Summary
-
-The Immutable X feature group provides a complete integration path for your Unity game with Immutable's Layer 2 solution. By implementing these features, you enable your players to interact with blockchain assets in a gas-free, carbon-neutral environment while maintaining Ethereum's security.
-
-When using these features together, remember to:
-- Always check for IMX connection before performing operations
-- Verify registration status before attempting transfers
-- Handle exceptions appropriately as blockchain operations may sometimes fail
-- Consider the asynchronous nature of these operations in your UI design
-
-The Immutable X integration through Passport SDK simplifies what would otherwise be complex blockchain interactions, allowing you to focus on creating engaging gameplay while providing your players with true ownership of digital assets.
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/PassportInitialisation/metadata.json b/sample/Assets/Scripts/Passport/_tutorials~/PassportInitialisation/metadata.json
index c58fc8e2..88aa4c52 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/PassportInitialisation/metadata.json
+++ b/sample/Assets/Scripts/Passport/_tutorials~/PassportInitialisation/metadata.json
@@ -1,8 +1,9 @@
{
- "title": "Initializing the Immutable Passport SDK",
- "description": "Learn how to properly initialize the Immutable Passport SDK in your Unity application to enable authentication and blockchain interactions",
- "keywords": ["Immutable", "SDK", "PassportInitialisation", "Authentication", "Unity"],
- "tech_stack": ["Unity", "C#", "UniTask"],
+ "title": "Passport Initialisation - Unity SDK Setup and Configuration",
+ "description": "Learn how to properly initialize the Immutable Passport SDK in Unity, including platform-specific configuration, logging setup, and error handling for seamless integration.",
+ "keywords": ["Immutable", "SDK", "PassportInitialisation", "Unity", "Authentication", "Setup", "Configuration", "Initialization"],
+ "tech_stack": ["Unity", "C#", "Immutable Passport SDK"],
"product": "Passport",
- "programming_language": "C#"
+ "programming_language": "C#",
+ "sidebar_order": 10
}
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/PassportInitialisation/tutorial.md b/sample/Assets/Scripts/Passport/_tutorials~/PassportInitialisation/tutorial.md
index 8b99bb4b..fe5a5459 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/PassportInitialisation/tutorial.md
+++ b/sample/Assets/Scripts/Passport/_tutorials~/PassportInitialisation/tutorial.md
@@ -4,11 +4,11 @@
-Passport initialization is a critical first step in integrating Immutable's blockchain capabilities into your Unity game. This feature demonstrates how to properly initialize the Passport SDK, which is required before using any other Passport functionality like authentication, wallet operations, or blockchain interactions.
+The Passport Initialisation feature demonstrates how to properly set up and configure the Immutable Passport SDK in your Unity game. This is the foundational step required before using any other Passport functionality, establishing the connection between your game and Immutable's authentication and wallet services.
-[View feature on Github](https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/PassportInitialisation/PassportInitialisationScript.cs) →
+[View feature on Github](https://github.com/immutable/unity-immutable-sdk/tree/main/sample/Assets/Scripts/Passport/PassportInitialisation) →
@@ -16,82 +16,121 @@ Passport initialization is a critical first step in integrating Immutable's bloc
### Feature: Passport Initialisation
-The Passport Initialisation feature demonstrates how to properly initialize the Immutable Passport SDK in your Unity application. The initialization process configures the SDK with your application's credentials and environment settings, preparing it for authentication and blockchain interactions.
+The Passport Initialisation feature handles the essential setup process for the Immutable Passport SDK. This includes configuring platform-specific redirect URIs, setting up logging preferences, and establishing the initial connection to Immutable's services.
```csharp title="Passport Initialisation" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/PassportInitialisation/PassportInitialisationScript.cs"
-// Set the log level for the SDK
-Passport.LogLevel = LogLevel.Info;
+private async void InitialisePassport()
+{
+ ShowOutput("Initialising Passport...");
-// Don't redact token values from logs
-Passport.RedactTokensInLogs = false;
+ string redirectUri;
+ string logoutRedirectUri;
-// Initialise Passport
-string environment = Immutable.Passport.Model.Environment.SANDBOX;
-string clientId = "mp6rxfMDwwZDogcdgNrAaHnG0qMlXuMK";
-Passport passport = await Passport.Init(clientId, environment, redirectUri, logoutRedirectUri);
+#if UNITY_WEBGL
+ var url = Application.absoluteURL;
+ var uri = new Uri(url);
+ var scheme = uri.Scheme;
+ var hostWithPort = uri.IsDefaultPort ? uri.Host : $"{uri.Host}:{uri.Port}";
+ var fullPath = uri.AbsolutePath.EndsWith("/")
+ ? uri.AbsolutePath
+ : uri.AbsolutePath.Substring(0, uri.AbsolutePath.LastIndexOf('/') + 1);
+
+ redirectUri = $"{scheme}://{hostWithPort}{fullPath}callback.html";
+ logoutRedirectUri = $"{scheme}://{hostWithPort}{fullPath}logout.html";
+#else
+ redirectUri = "immutablerunner://callback";
+ logoutRedirectUri = "immutablerunner://logout";
+#endif
+
+ try
+ {
+ // Set the log level for the SDK
+ Passport.LogLevel = LogLevel.Info;
+
+ // Don't redact token values from logs
+ Passport.RedactTokensInLogs = false;
+
+ // Initialise Passport
+ const string environment = Immutable.Passport.Model.Environment.SANDBOX;
+ const string clientId = "mp6rxfMDwwZDogcdgNrAaHnG0qMlXuMK";
+ var passport = await Passport.Init(clientId, environment, redirectUri, logoutRedirectUri);
+ SampleAppManager.PassportInstance = passport;
+
+ // Navigate to the unauthenticated scene after initialising Passport
+ SceneManager.LoadScene("UnauthenticatedScene");
+ }
+ catch (Exception ex)
+ {
+ Debug.LogException(ex, this);
+ ShowOutput($"Initialise Passport error: {ex.Message}");
+ }
+}
```
-This initialization process handles several important tasks:
-1. **Log Level Configuration**: Sets the logging verbosity to help with debugging.
-2. **Token Redaction**: Controls whether sensitive token information appears in logs.
-3. **Environment Selection**: Determines whether to connect to the sandbox (for testing) or production environment.
-4. **Client ID**: Specifies your application's unique identifier from the Immutable Hub.
-5. **Redirect URIs**: Configures the authentication flow's redirect paths.
+#### How the Code Works
-The implementation supports two authentication methods:
-- **Device Code Auth**: Used for desktop applications where the user authenticates in an external browser.
-- **PKCE Flow**: Used for web and mobile platforms where authentication happens in an embedded browser.
+The Passport initialisation process follows these key steps:
-The code automatically selects the appropriate authentication method based on the platform, with WebGL defaulting to PKCE due to platform limitations:
+1. **Platform-Specific URI Configuration**: The code dynamically configures redirect URIs based on the target platform. For WebGL builds, it constructs URIs using the current application URL with specific callback and logout paths. For other platforms, it uses custom URI schemes (`immutablerunner://`).
-```csharp title="Authentication Method Selection" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/PassportInitialisation/PassportInitialisationScript.cs"
-// WebGL does not support Device Code Auth, so we'll use PKCE by default instead.
-#if UNITY_WEBGL
- UsePKCE();
-#endif
-```
+2. **Logging Configuration**: The SDK's logging level is set to `Info` to provide detailed information during development, and token redaction is disabled to allow full visibility of authentication tokens in logs.
-For PKCE authentication, the redirect URIs must be configured correctly based on the platform:
+3. **SDK Initialisation**: The `Passport.Init()` method is called with essential parameters:
+ - **Client ID**: A unique identifier for your application registered with Immutable
+ - **Environment**: Set to `SANDBOX` for testing (use `PRODUCTION` for live applications)
+ - **Redirect URIs**: URLs where users are redirected after authentication and logout
-```csharp title="Platform-specific PKCE Configuration" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/PassportInitialisation/PassportInitialisationScript.cs"
-#if UNITY_WEBGL
- string url = Application.absoluteURL;
- Uri uri = new Uri(url);
- string scheme = uri.Scheme;
- string hostWithPort = uri.IsDefaultPort ? uri.Host : $"{uri.Host}:{uri.Port}";
- string fullPath = uri.AbsolutePath.EndsWith("/") ? uri.AbsolutePath : uri.AbsolutePath.Substring(0, uri.AbsolutePath.LastIndexOf('/') + 1);
-
- string redirectUri = $"{scheme}://{hostWithPort}{fullPath}callback.html";
- string logoutRedirectUri = $"{scheme}://{hostWithPort}{fullPath}logout.html";
-
- InitialisePassport(redirectUri: redirectUri, logoutRedirectUri: logoutRedirectUri);
-#else
- InitialisePassport(redirectUri: "immutablerunner://callback", logoutRedirectUri: "immutablerunner://logout");
-#endif
-```
+4. **Instance Management**: The successfully initialised Passport instance is stored in `SampleAppManager.PassportInstance` for use throughout the application.
+
+5. **Scene Transition**: After successful initialisation, the application automatically navigates to the "UnauthenticatedScene" to begin the user authentication flow.
+
+6. **Error Handling**: Comprehensive exception handling ensures that any initialisation failures are properly logged and displayed to the user.
## Running the Feature Example
### Prerequisites
-- Create an Immutable Hub account and get your client ID from [Immutable Hub](https://hub.immutable.com)
-- Set up the Unity project with the Immutable Passport SDK
-- Configure your project for the appropriate platform
-
-### Steps to Run the Example
-1. Open the Unity project and load the sample scene for Passport Initialisation
-2. Replace the placeholder `clientId` with your own client ID from Immutable Hub
-3. For non-WebGL platforms, you may need to set up custom URL schemes for your application
-4. Run the application in the Unity Editor or build for your target platform
-5. Once the application runs, it will automatically initialize Passport with the appropriate authentication method
-6. If initialization is successful, the application will navigate to the unauthenticated scene, ready for login
+
+Before running the Passport Initialisation example, ensure you have:
+
+- Unity 2022.3 LTS or later installed
+- The Immutable Unity SDK imported into your project
+- A valid client ID from [Immutable Hub](https://hub.immutable.com/) for environment setup
+
+### Step-by-Step Instructions
+
+1. **Open the Sample Project**: Navigate to the `sample` directory in the Unity Immutable SDK and open it in Unity Editor.
+
+2. **Configure Client ID**: In the `PassportInitialisationScript.cs`, ensure the `clientId` variable contains your application's client ID from Immutable Hub.
+
+3. **Set Build Target**:
+ - For testing: Set your build target to your preferred platform (Windows, macOS, or WebGL)
+ - For WebGL: Ensure you have the appropriate callback and logout HTML files in your build output
+
+4. **Run the Scene**:
+ - Open the scene containing the `PassportInitialisationScript` component
+ - Press Play in Unity Editor or build and run the application
+ - Observe the initialisation process in the console and output display
+
+5. **Verify Success**:
+ - Check that "Initialising Passport..." appears in the output
+ - Confirm that the scene transitions to "UnauthenticatedScene" upon successful initialisation
+ - Monitor the console for any error messages
+
+6. **Handle Errors**: If initialisation fails, check:
+ - Network connectivity
+ - Client ID validity
+ - Proper URI configuration for your platform
## Summary
-Properly initializing the Passport SDK is a crucial first step in integrating Immutable's blockchain features into your Unity game. The initialization process sets up the environment, configures authentication methods, and prepares the SDK for subsequent operations like user login, wallet management, and blockchain interactions.
+The Passport Initialisation feature provides the essential foundation for integrating Immutable Passport into Unity games. It demonstrates proper SDK setup with platform-aware configuration, comprehensive error handling, and seamless integration with Unity's scene management system.
+
+**Key takeaways for developers:**
+
+- Always initialise Passport before attempting any authentication or wallet operations
+- Configure platform-specific redirect URIs to ensure proper authentication flow
+- Implement robust error handling to gracefully manage initialisation failures
+- Use appropriate environment settings (SANDBOX for development, PRODUCTION for live applications)
+- Store the Passport instance globally for access throughout your application
-When implementing this feature in your own game:
-- Always store your client ID securely and consider using environment variables for different build configurations
-- Select the appropriate environment (SANDBOX for testing, PRODUCTION for release)
-- Configure platform-specific redirect URIs based on your application's structure
-- Handle exceptions during initialization to provide meaningful feedback to users
-- Consider adjusting log levels based on your build configuration (verbose for debugging, minimal for production)
\ No newline at end of file
+This initialisation pattern ensures a reliable foundation for all subsequent Passport functionality in your Unity game.
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/SetCallTimeout/metadata.json b/sample/Assets/Scripts/Passport/_tutorials~/SetCallTimeout/metadata.json
index bdff4f25..f20b4740 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/SetCallTimeout/metadata.json
+++ b/sample/Assets/Scripts/Passport/_tutorials~/SetCallTimeout/metadata.json
@@ -1,8 +1,9 @@
{
- "title": "Configuring API Call Timeouts in Passport SDK",
- "description": "Learn how to customize network timeout durations for API calls in the Immutable Passport SDK",
- "keywords": ["Immutable", "SDK", "SetCallTimeout", "Network Timeout", "API Timeout", "Unity"],
- "tech_stack": ["Unity", "C#", "Passport SDK"],
+ "title": "Set Call Timeout Configuration",
+ "description": "Learn how to configure timeout duration for Passport SDK operations using the browser communications manager",
+ "keywords": ["Immutable", "SDK", "SetCallTimeout", "Timeout", "Configuration", "Network", "Performance"],
+ "tech_stack": ["Unity", "C#"],
"product": "Passport",
- "programming_language": "C#"
+ "programming_language": "C#",
+ "sidebar_order": 50
}
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/SetCallTimeout/tutorial.md b/sample/Assets/Scripts/Passport/_tutorials~/SetCallTimeout/tutorial.md
index fc498330..161abbba 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/SetCallTimeout/tutorial.md
+++ b/sample/Assets/Scripts/Passport/_tutorials~/SetCallTimeout/tutorial.md
@@ -4,7 +4,7 @@
-The Set Call Timeout feature allows developers to configure the timeout duration for API calls within the Immutable Passport SDK. This enables greater control over network operations, allowing customization of how long the application should wait for responses before timing out.
+The Set Call Timeout feature demonstrates how to configure the timeout duration for Passport SDK operations that use the browser communications manager. This feature allows developers to customize the timeout period based on their application's requirements and network conditions, ensuring optimal performance and reliability for Passport API calls.
@@ -14,80 +14,89 @@ The Set Call Timeout feature allows developers to configure the timeout duration
## Unity SDK Set Call Timeout Implementation
-### Feature: SetCallTimeout
+The Set Call Timeout feature provides a simple interface for configuring the timeout duration for Passport SDK operations. By default, the Passport SDK uses a 60-second timeout for browser communication calls, but this can be adjusted to accommodate different network conditions or application requirements.
-The Set Call Timeout feature provides a simple way to adjust the timeout duration for network calls made through the Passport SDK. When making API calls to blockchain networks or authentication services, network latency can sometimes cause delays. This feature gives developers control over how long their application should wait before considering a request as failed due to timeout.
-
-```csharp title="SetCallTimeoutScript" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/Other/SetCallTimeout/SetCallTimeoutScript.cs"
-using UnityEngine;
-using UnityEngine.UI;
-using UnityEngine.SceneManagement;
-using Immutable.Passport;
-
-public class SetCallTimeoutScript : MonoBehaviour
+```csharp title="Set Call Timeout Implementation" manualLink="https://github.com/immutable/unity-immutable-sdk/blob/main/sample/Assets/Scripts/Passport/Other/SetCallTimeout/SetCallTimeoutScript.cs"
+public void SetTimeout()
{
- [SerializeField] private Text Output;
- [SerializeField] private InputField TimeoutInput;
-
- public void SetTimeout()
+ if (Passport.Instance == null)
+ {
+ ShowOutput("Passport instance is null");
+ return;
+ }
+ if (TimeoutInput == null)
+ {
+ Debug.LogError("[SetCallTimeoutScript] TimeoutInput is not assigned in the Inspector.");
+ ShowOutput("Timeout input field is not assigned.");
+ return;
+ }
+ if (!int.TryParse(TimeoutInput.text, out int timeout))
{
- if (Passport.Instance == null)
- {
- ShowOutput("Passport instance is null");
- return;
- }
- if (TimeoutInput == null)
- {
- Debug.LogError("[SetCallTimeoutScript] TimeoutInput is not assigned in the Inspector.");
- ShowOutput("Timeout input field is not assigned.");
- return;
- }
- if (!int.TryParse(TimeoutInput.text, out int timeout))
- {
- ShowOutput("Invalid timeout value");
- return;
- }
- Passport.Instance.SetCallTimeout(timeout);
- ShowOutput($"Set call timeout to: {timeout}ms");
+ ShowOutput("Invalid timeout value");
+ return;
}
+ Passport.Instance.SetCallTimeout(timeout);
+ ShowOutput($"Set call timeout to: {timeout}ms");
}
```
-The implementation is straightforward:
+The implementation validates user input to ensure a valid timeout value is provided, then calls the Passport SDK's `SetCallTimeout` method. This method configures the timeout for all subsequent Passport operations that use the browser communications manager, including authentication, blockchain transactions, and API calls.
-1. The script takes a timeout value in milliseconds from a UI input field.
-2. After validating the input, it calls `Passport.Instance.SetCallTimeout(timeout)` to set the timeout duration.
-3. The default timeout value in the SDK is 60,000 milliseconds (1 minute).
+The timeout value is specified in milliseconds and affects operations such as:
+- Login and authentication flows
+- IMX and zkEVM blockchain interactions
+- User information retrieval
+- Token and NFT operations
-This timeout applies to functions that use the browser communications manager in the Passport SDK, which includes most network operations like authentication and blockchain transactions.
+Setting an appropriate timeout is crucial for balancing user experience with network reliability. Shorter timeouts provide faster feedback for failed operations, while longer timeouts accommodate slower network conditions or complex operations.
## Running the Feature Example
### Prerequisites
-- Unity Editor installed (2021.3 LTS or newer recommended)
-- Immutable SDK integrated into your project
-- Basic knowledge of Unity UI system
-- Valid API credentials set up on [Immutable Hub](https://hub.immutable.com/)
+Before running the Set Call Timeout example, ensure you have:
+
+- Unity 2021.3 or later installed
+- The Immutable Unity SDK properly configured in your project
+- Access to [Immutable Hub](https://hub.immutable.com/) for environment setup and configuration
+- A properly initialized Passport instance
+
+### Step-by-Step Instructions
+
+1. **Open the Sample Project**
+ - Navigate to the `sample` directory in the Unity Immutable SDK
+ - Open the project in Unity Editor
+
+2. **Initialize Passport**
+ - Ensure Passport is properly initialized before attempting to set the timeout
+ - Run the PassportInitialisation scene if needed
+
+3. **Navigate to Set Call Timeout Scene**
+ - From the AuthenticatedScene, click the "Set Call Timeout" button
+ - This will load the SetCallTimeout scene with the timeout configuration interface
+
+4. **Configure Timeout Value**
+ - Enter a timeout value in milliseconds in the input field (default placeholder shows 60000)
+ - The value should be a positive integer representing milliseconds
+ - Common values: 30000 (30 seconds), 60000 (60 seconds), 120000 (2 minutes)
-### Steps to Run the Example
+5. **Apply the Timeout Setting**
+ - Click the "Set Timeout" button to apply the new timeout value
+ - The system will display a confirmation message showing the applied timeout
+ - The new timeout will affect all subsequent Passport SDK operations
-1. Open the sample project in Unity Editor.
-2. Ensure you have configured your Passport settings with valid client ID and environment in the Passport initialization scene.
-3. Run the project in the Unity Editor.
-4. Log in to Passport if not already authenticated.
-5. Navigate to the Set Call Timeout scene.
-6. Enter a timeout value in milliseconds in the input field (e.g., 30000 for 30 seconds).
-7. Click the "Set Timeout" button to apply the new timeout value.
-8. The output text will confirm that the timeout has been set to the specified value.
+6. **Verify the Setting**
+ - Test other Passport operations to verify the timeout is working as expected
+ - Monitor operation behavior under different network conditions
## Summary
-The Set Call Timeout feature provides developers with the ability to customize network timeout durations in their applications. This is particularly useful when:
+The Set Call Timeout feature provides essential control over Passport SDK operation timeouts, enabling developers to optimize their applications for different network environments and use cases. By allowing customization of the timeout duration, this feature helps ensure reliable operation while maintaining responsive user experiences.
-- Working with networks that have varying latency conditions
-- Developing for different platforms with different network capabilities
-- Fine-tuning application responsiveness and error handling
-- Testing network resilience with different timeout settings
+Key benefits include:
+- **Network Adaptation**: Adjust timeouts based on expected network conditions
+- **User Experience**: Balance responsiveness with operation reliability
+- **Application Control**: Fine-tune timeout behavior for specific use cases
+- **Error Handling**: Provide predictable timeout behavior for better error management
-By implementing appropriate timeout values, developers can create a better user experience by controlling how long the application will wait for network responses before considering the operation failed, allowing for more graceful error handling.
\ No newline at end of file
+When implementing timeout configuration in production applications, consider factors such as target network conditions, operation complexity, and user expectations to determine optimal timeout values.
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/ZkEvm/metadata.json b/sample/Assets/Scripts/Passport/_tutorials~/ZkEvm/metadata.json
index d236d859..822c54fe 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/ZkEvm/metadata.json
+++ b/sample/Assets/Scripts/Passport/_tutorials~/ZkEvm/metadata.json
@@ -1,8 +1,9 @@
{
- "title": "ZkEvm Integration for Unity Games",
- "description": "Learn how to integrate Immutable's ZkEvm blockchain with Unity games, including connecting to the network, sending transactions, checking balances, and more.",
- "keywords": ["Immutable", "SDK", "ZkEvm", "Blockchain", "Unity", "Smart Contracts", "Transactions", "Web3"],
- "tech_stack": ["Unity", "C#", "Immutable ZkEvm", "Passport SDK", "Cysharp UniTask"],
+ "title": "Unity ZkEvm Integration with Passport SDK",
+ "description": "Comprehensive demonstration of zkEVM blockchain functionality including provider connection, transaction management, balance checking, receipt verification, message signing, and account management using Immutable Passport SDK",
+ "keywords": ["Immutable", "SDK", "ZkEvm", "ZkEvmConnect", "ZkEvmSendTransaction", "ZkEvmGetBalance", "ZkEvmGetTransactionReceipt", "ZkEvmSignTypedData", "ZkEvmRequestAccounts", "Blockchain", "Ethereum", "zkEVM", "Unity", "Passport"],
+ "tech_stack": ["Unity", "C#", "UniTask", "Immutable Passport SDK", "zkEVM", "Ethereum", "EIP-712"],
"product": "Passport",
- "programming_language": "C#"
+ "programming_language": "C#",
+ "sidebar_order": 60
}
\ No newline at end of file
diff --git a/sample/Assets/Scripts/Passport/_tutorials~/ZkEvm/tutorial.md b/sample/Assets/Scripts/Passport/_tutorials~/ZkEvm/tutorial.md
index 2d23b433..2347d5ef 100644
--- a/sample/Assets/Scripts/Passport/_tutorials~/ZkEvm/tutorial.md
+++ b/sample/Assets/Scripts/Passport/_tutorials~/ZkEvm/tutorial.md
@@ -1,10 +1,10 @@
-# ZkEvm Integration
+# ZkEvm Features
-The ZkEvm feature group demonstrates how to integrate Immutable's ZkEvm blockchain capabilities into your Unity game. These features allow games to connect to the Immutable ZkEvm blockchain, perform transactions, check balances, and interact with smart contracts.
+The ZkEvm feature group demonstrates how to interact with Immutable's zkEVM blockchain through the Passport SDK. These features enable developers to perform essential blockchain operations including connecting to the zkEVM provider, sending transactions, checking balances, retrieving transaction receipts, signing typed data, and requesting account information.