How to connect to a Wallet

CoreSamples/Scripts/SimpleLoginScreen.cs

Connecting to a web3 wallet is a crucial step in enabling users to interact with blockchain-based applications. While the EmergenceSDK provides an overlay for handling wallet connections, you might want to bypass the default overlay and integrate the QR code directly into your custom user interface. This example demonstrates how to connect to a web3 wallet using the EmergenceSDK in Unity, giving you more control over the wallet connection process and allowing for a more seamless integration with your application's UI.

The example provided at the path above demonstrates how to connect to a web3 wallet using the EmergenceSDK. The following code communicates with the Emergence LoginManager to detail Login settings and espond to events handled by our Login services This is done using Event Listeners.

First, import the necessary namespaces:

using EmergenceSDK.Runtime;
using EmergenceSDK.Runtime.Services;
using EmergenceSDK.Runtime.Types;

These namespaces contain various utilities and services that we will need to interact with the EmergenceSDK in Unity.

Next, define a new class called ConnectingToWallet, which inherits from MonoBehaviour. This allows you to attach this script to a GameObject in Unity.

public class SimpleLoginScreen : MonoBehaviour
{
    public LoginManager loginManager;
    public LoginSettings loginSettings;

    ...
}

Declare two private variables: loginManager of type LoginManager and loginSettings of type LoginSettings. This is our Login management singleton and the settings we will use for login flow.

In the Awake method, we must first initialise the emergence service provider. This is a class that manages a variety of emergence related services.

private void Awake()
{
    // We need to load a service provider profile
    EmergenceServiceProvider.Load(ServiceProfile.Default);
    ...
    

We then tie a variety of behaviours to various login Events triggered by the login manager. There are a variety of additional methods that can be subscribed to and are demonstrated within the full sample.

    // Add a listener to the loginStepUpdatedEvent. This is triggered as a log in progresses
    loginManager.loginStepUpdatedEvent.AddListener(OnLoginStepUpdated);
    
    // Handle successful login by simply hiding the gameObject and setting the first-login flag to true
    loginManager.loginSuccessfulEvent.AddListener(OnLoginSuccessful);
    
    loginManager.loginStartedEvent.AddListener(OnLoginStarted);
    loginManager.qrCodeTickEvent.AddListener(OnQrCodeTick);
    loginManager.loginCancelledEvent.AddListener(OnLoginCancelled);

For now we're largely interested in loginStepUpdatedEvent and loginSuccessfulEvent

    private void OnLoginStepUpdated(LoginManager _, LoginStep loginStep, StepPhase stepPhase)
    {
        if (stepPhase != StepPhase.Success) return;

        switch (loginStep)
        {
            case LoginStep.QrCodeRequest: 
            Texture2D qrCodeTexture2D = loginManager.CurrentQrCode.Texture;
                //Display QR code to User
                break;
        }
    }

    private void OnLoginSuccessful(LoginManager _,string walletAddress)
    {
        LoginManager.SetFirstLoginFlag();
    }

As you can see, when the LoginManager triggers the LoginStepUpdated event it tells it's listeners what its new step is. We want to know when the Loginmanager enters the QrCodeRequest step.

When the login manager enters this step it makes a Texture2D QR code available for us to use for login. You should present the QR code to the user for scanning. After the user scans the QR code and connects to the wallet, the login manager will perform a handshake and signign request before calling the LoginSuccessful Event

The OnLoginSuccessfulmethod is called when the login is successful. It receives the wallet address as a parameter. You can now use the wallet address for any necessary operations. The example logs the wallet address to the console.

    private void OnLoginSuccessful(LoginManager _,string walletAddress)
    {
        LoginManager.SetFirstLoginFlag();
        Debug.Log($"Wallet address: {walletAddress}");
    }

Now to execute the login flow we simply call the appropriate method on teh login manager, where we pass our "LoginSettings" this flag instructs the login manager which login flow it should execute. By default we'll use wallet connect.

    [SerializeField]
    private LoginSettings loginSettings;
    
    private void StartLogin()
    {
        UniTask.Void(async () =>
        {
            await loginManager.WaitUntilAvailable(); // Wait until the login manager is available
            await loginManager.StartLogin(loginSettings); // Start login
        });
    }

By following this example, you can connect to a web3 wallet in your Unity project using the EmergenceSDK. Generating a QR code, presenting it to the user for scanning, and completing the handshake to establish a connection with the wallet.

Full Code:

using System;
using Cysharp.Threading.Tasks;
using EmergenceSDK.Runtime;
using EmergenceSDK.Runtime.Internal.Services;
using EmergenceSDK.Runtime.Services;
using EmergenceSDK.Runtime.Types;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace EmergenceSDK.Samples.CoreSamples
{
    /// <summary>
    /// A minimalist implementation of a login widget to go with the <see cref="LoginManager"/><para/>
    /// </summary>
    public class SimpleLoginScreen : MonoBehaviour
    {
        [SerializeField]
        private LoginManager loginManager;
        
        [SerializeField]
        private LoginSettings loginSettings;
        
        private void Awake()
        {
            // We need to load a service provider profile
            EmergenceServiceProvider.Load(ServiceProfile.Default);
            
            // Add a listener to the loginStepUpdatedEvent. This is triggered as a log in progresses
            loginManager.loginStepUpdatedEvent.AddListener(OnLoginStepUpdated);
            
            // Handle successful login by simply hiding the gameObject and setting the first-login flag to true
            loginManager.loginSuccessfulEvent.AddListener(OnLoginSuccessful);
            
            loginManager.loginStartedEvent.AddListener(OnLoginStarted);
            loginManager.qrCodeTickEvent.AddListener(OnQrCodeTick);
            loginManager.loginCancelledEvent.AddListener(OnLoginCancelled);
        }

        private void StartLogin()
        {
            UniTask.Void(async () =>
            {
                await loginManager.WaitUntilAvailable(); // Wait until the login manager is available
                await loginManager.StartLogin(loginSettings); // Start login
            });
        }

        private void OnLoginStepUpdated(LoginManager _, LoginStep loginStep, StepPhase stepPhase)
        {
            if (stepPhase != StepPhase.Success) return;

            switch (loginStep)
            {
                case LoginStep.QrCodeRequest: 
                    Texture2D qrCodeTexture2D = loginManager.CurrentQrCode.Texture;
                    //Display QR code to User
                    break;
            }
        }

        private void OnLoginSuccessful(LoginManager _,string walletAddress)
        {
            LoginManager.SetFirstLoginFlag();
            Debug.Log($"Wallet address: {walletAddress}");
        }

        private void OnLoginStarted(LoginManager _)
        {

        }

        private void OnLoginCancelled(LoginManager _)
        {
            
        }

        private void OnQrCodeTick(LoginManager _, EmergenceQrCode qrCode)
        {
            
        }
        
    }
}

Last updated