Wallet Module for Unity

This section will help you get started with the integration effort for now.gg Wallet.

With now.gg Wallet module for Unity, you can integrate now.gg Wallet within your game on Unity.

To start the integration effort for now.gg Wallet:

  1. Download and Import now.gg Wallet Unity module.
  2. Add required dependencies.
  3. Implement now.gg Wallet to your project.

Download and Import the Module

now.gg Wallet Unity module is included as a Unity package file nowgg-wallet.unitypackage.

Add the module to your Unity project:

  1. Download the package containing the latest version of now.gg Wallet module for Unity.
  2. After downloading the module, import it into your Unity project. To do this:
    • Click on Assets > Import Package > Custom Package, as shown below:
    • Select nowgg-wallet.unitypackage that you previously downloaded.
    • Select all the listed files and click on Import.

Once all the module files have been imported, a folder named ‘NowGGSdk’ will be added to your project. You can find this folder within the root of the Assets folder.

Note: Please do not modify the NowGGSdk folder, as that contains all the assets related to now.gg Wallet module.

Add Required Dependencies

This operation will download and add all the required dependencies to the Assets/Plugins/Android directory of your project using the Unity External Dependency Manager.

To add the required dependencies:

    • Click on Assets > External Dependency Manager > Android Resolver > Resolve.

Implement now.gg Wallet

The following sections illustrate the implementation of the now.gg Wallet and the use of related functions, which you can call from your app/game in Unity.

Once the now.gg Wallet Module has been imported, and the dependencies have been added; you can now integrate your app/game with now.gg Wallet.

1. Initialize the Module

Start by creating a class that contains the now.gg Wallet implementation and attach it to a game object that you can use to initialize the module.

To initialize now.gg Wallet module, you should call the Initialize function of the NowGGWalletSdkManager class along with the required params, as illustrated below:

public class Constants
 {

     // your chain namespace as per CAIP 
     public static string ChainNamespace = "eip155"; 
     public static string ChainId = "<your_ChainId>"; //your chain id
     public static string CAIPChainId = ChainNamespace + ":" + ChainId; 
     public static string API_KEY = "<your_API_KEY>"; 
     public static string APP_ID = "<your_APP_ID>";
     public static string CoinContractAddress = "<your ERC20 contract address>";

 }

 public void Start()
 {
      NowGGWalletSdkManager.Instance.Initialize(Constants.API_KEY, Constants.APP_ID, new WalletDelegateHandler(), ()=>{
             
             // Call other methods only after you receive this callback.
             Debug.Log("Wallet module initialised");
         }, (error)=>{
             Debug.Log("Error occurred while initialising SDK");
         });

 }

Important Information

  • You can generate the API_KEY and APP_ID by sending us an email at dev-support@now.gg.
  • You can find the reference to the chain namespace as per CAIP here.
  • For a list of supported blockchains, please click here
  • Detailed references for all NowGGWalletSdkManager methods are listed here.

2. Declaring Wallet Delegate

Once you have initialized the Wallet module, you must declare a wallet delegate to receive the responses using callbacks, as illustrated below:

public class WalletDelegateHandler : NowGGWalletDelegate
 {   
     // Triggered when the connection state changes.
     public void OnConnectionStateChange(bool isAvailable)
     {
     }
    
      // Triggered when there is an error.
     public void OnError(string error)
     {
        if (error == ErrorCodes.SESSION_EXPIRED)
         {
           //Indicates that the earlier established session has failed. This may be because i.) the wallet is not responding or ii.) the wallet is in the killed state.
           //Call Connect again to reestablish the connection with the wallet.
         }

    }
    
     // Triggered when the session request is approved by the wallet.
     public void OnSessionApproved(ApprovedSession approvedSession, User user)
     {
         string topic = approvedSession.topic;
         string walletAddress = approvedSession.accounts[0];
         string userName = user.name;

         // handle the session data
     }
    
     // Triggered when the session is deleted
     public void OnSessionDelete(DeletedSession deletedSession)
     {
     }
    
     // Triggered when the session request is rejected by the wallet.
     public void OnSessionRejected(RejectedSession rejectedSession)
     {
     }
      
     // Triggered when session information is updated.
     public void OnSessionUpdate(UpdatedSession updatedSession)
     {
     }
        
     // Triggered when there is an error while purchasing token
     public void OnTokenPurchaseError(string error, string extra)
     {
         // handle error while purchasing token      
     }

     // Triggered when token purchase is successful.
     public void OnTokenPurchaseSuccess(JsonRpcResponse result, string extra)
     {
         Debug.Log("OnTokenPurchaseResponse : " + result.ToString() + $" extra:{extra}");
        
         // handle token purchase
     }    
    
     // Triggered once a transaction is submitted to the blockchain by Wallet.
     public void OnTransactionSendSuccess(string txnHash, string caipChainId, string extra)
     {    
     }

     // Triggered when there is an error while sending transaction to blockchain.
     public void OnTransactionSendError(string error, string extra)
     {   
     //handle error while sending transaction to blockchain
     }

     // Triggered when transaction was completed successful.
     public void OnTransactionCompletedSuccess(TransactionInfo transaction, string extra)
     {
        // handle successful transaction
     }
   
     // Triggered when a transaction is completed with an error post wallet approval request.
     public void OnTransactionCompletedError(string error, string extra)
     {   
     }
 }

Important Information

  • Please make sure that isAvailable in OnConnectionStateChange callback is true, before calling any now.gg wallet functions.

Reference

  • Detailed references for all NowGGWalletDelegate methods are listed here.

3. Connect to now.gg Wallet

The next step is to connect your game to the now.gg Wallet.

Connecting to the now.gg Wallet is required to carry out various operations, such as:

  • Buy Token.
  • View Token balance.
  • Send Transactions.
  • Get the list of NFTs purchased by the user.

To connect to the now.gg Wallet, you should call the Connect function of the NowGGWalletSdkManager class, as illustrated below:

public void ConnectNowGGWallet()
 {
    try
    {
       NowGGWalletSdkManager.Instance.Connect(Constants.CAIPChainId, OnPairingInvoked, OnConnectError);
    }
    catch (SocketNotConnectedException)
    {
      //This will occur if the connection state is not available. 
      //Please wait for the connection state to be available before calling this function.
      //Add your handling here.
    }
    catch (WalletSdkNotInitialisedException)
    {
      //This will occur if you call Connect before initialization is successful.
      //Add your handling here.
    }  
 }

 void OnPairingInvoked()
  {
     Debug.Log("DemoGame: OnPairingInvoked called");
  }

 void OnConnectError(string error)
  {
     Debug.Log("DemoGame: Failed to connect to wallet. Error: " + error);
  }

Flow Diagram

  • Click here to find the sequence diagram for Connect Wallet flow.

Reference

  • A detailed reference for the Connect function is listed here.

Using Wallet Functions

Once you have connected to the now.gg Wallet, you can use the following functions:

Important Information

  • Please make sure that isAvailable in OnConnectionStateChange callback is true, before calling any now.gg wallet functions.

1. Buy Token (Coming Soon)

You can use the now.gg Wallet to enable the purchase of supported tokens by using the BuyToken function of the NowGGWalletSdkManager class, as illustrated below:

public void BuyToken(int amount)
 {
    try
    {
       NowGGWalletSdkManager.Instance.BuyToken(Constants.CoinContractAddress, amount.ToString(), Constants.CAIPChainId, "BuyToken");
    } 
    catch (SocketNotConnectedException)
    {
      //This will occur if the connection state is not available. 
      //Please wait for the connection state to be available before calling this function.
      //Add your handling here.
    }
    catch (WalletSdkNotInitialisedException)
    {
       //This will occur if you call Connect before initialization is successful.
       //Add your handling here.
    }
 }

Flow Diagram

  • Click here to find the sequence diagram for the Buy Token flow.

Reference

  • A detailed reference for the BuyToken function is listed here.

2. Get Token Balance

You can request the user’s token balance using the GetTokenBalance function of NowGGWalletSdkManager class and receive the token balance as a response, as illustrated below:

public void GetTokenBalance()
 {
   try 
   {
      NowGGWalletSdkManager.Instance.GetTokenBalance(Constants.CoinContractAddress,Constants.CAIPChainId,Utils.GetWalletAddress(), OnTokenRespSuccess, OnTokenRespError);
   }
   catch (WalletSdkNotInitialisedException)
   {
      //This will occur if you call Connect before initialization is successful.
      //Add your handling here.
   }
 }

 private void OnTokenRespSuccess(string tokenBalance)
  {
      Debug.Log("DemoGame: Got token balance: " + tokenBalance);

      // You can update the user about the balance.
      setTokenBalance((int)Convert.ToDouble(tokenBalance));
  }

 private void OnTokenRespError(string message)
  {
      Debug.Log("DemoGame: Got OnTokenRespError: " + message);
  }

Note: Replace “Users_walletAddress_here” with the actual walletAddress received in OnSessionApproved.

Reference

  • A detailed reference for the GetTokenBalance function is listed here.

3. Send Transaction

You can use this function to execute a transaction on the blockchain.

For instance, you can get approval to deduct a certain amount from the user’s wallet to purchase an NFT.

The following illustrates executing a contract on the blockchain using the SendTransaction function:

  • Use the SendTransaction function of the NowGGWalletSdkManager class to get the NFT purchase approval.
public void GetNftPurchaseApproval()
 {
    string toAddress = Constants.CoinContractAddress;
    string nativeTokenValue = "0x0";
   
    //nftData is an encoded method name with parameters of the NFT contract
    string nftData = "0x095ea7b3000000000000000000001111ff9f4c235d1508176cbe99891585e86b8fd3f09100000000000000000000000000000000000000000000001043561a8829300000";
    string extra = nftName;
   
    try
    {
       NowGGWalletSdkManager.Instance.SendTransaction(toAddress, nativeTokenValue, nftData, Constants.CAIPChainId, extra);
    }
    catch (SocketNotConnectedException)
    {
      //This will occur if the connection state is not available. 
      //Please wait for the connection state to be available before calling this function.
      //Add your handling here.
    }
    catch (WalletSdkNotInitialisedException)
    {
        //This will occur if you call Connect before initialisation is successful.
        //Add your handling here.
    }
 }

Important Information

  • nftData is an encoded method name with parameters of the NFT contract.
  • We have passed nftName within the extra parameter, you may pass any additional information here based on your requirement.
  • Depending on your requirement, you may use our implementation or write your logic.

Flow Diagram

Click here to find the sequence diagram for Send Transaction flow.

Reference

A detailed reference for the sendTransaction function is listed here.

4. Get NFTs

You can request the list of NFTs purchased by the user with GetNfts function of the NowGGWalletSdkManager class, as illustrated below:

public void FetchNfts(String walletAddress)
 {
    try 
     {
        NowGGWalletSdkManager.Instance.GetNfts(Constants.CAIPChainId, Utils.GetWalletAddress(), OnNftsReceived, OnGetNftError);
     }    
     catch (WalletSdkNotInitialisedException)
     {
        //This will occur if you call Connect before initialisation is successful.
        //Add your handling here.
     }
 }

 private void OnNftsReceived(List nfts)
  {
      Debug.Log("OnNftsReceived called");
      // handle list of nfts
  }

 private void OnGetNftError(string message)
  {
      Debug.Log("OnGetNftError: " + message);
  }

Note: Replace “Users_walletAddress_here” with the actual walletAddress received in OnSessionApproved.

Reference

  • A detailed reference for the GetNfts function is listed here.

Important Information

×
Text copied to clipboard
Link copied to clipbord
Questions? Please reach out to us at dev-support@now.gg