Using Unity SDK with self-hosted server

In a new Unity project:

1: Add Moralis game kit package and import default scene from Moralis Web3 Unity SDK/Demos/Introduction.

2: Add your self hosted server Dapp URL and Dapp ID e.g. http://127.0.0.1:1337/server and 001

3: Open Moralis Web3 Unity SDK package > Runtime/Kits/AuthenticationKit/Scripts/AuthenticationKit.cs

The Unity SDK relies on getServerTime returning a valid value but the self hosted server needs it to return null for authentication to work.

Edit the getServerTime code at lines 257 and 358 to check if the response is null:

if (serverTimeResponse != null)
{
    Debug.LogError("Failed to retrieve server time from Moralis Server!");
}

4: Above comment // Try to sign and catch the Exception when a user cancels the request, add these new lines:

IDictionary<string, object> requestMessageParams = new Dictionary<string, object>();

requestMessageParams.Add("address", address);
requestMessageParams.Add("chain", session.ChainId);
requestMessageParams.Add("network", "evm");

Dictionary<string, object> authMessage = await Moralis.Cloud.RunAsync<Dictionary<string, object>>("requestMessage", requestMessageParams);

signMessage = authMessage["message"].ToString();

5: Workaround for insufficient auth error with signing in as an existing user, open Moralis Web3 Unity SDK package > Runtime/Core/Platform/Services/ClientServices/MoralisUserService.cs and before await user.SaveAsync() at line 102, add:

user.authData.Clear();
await user.SaveAsync();

6: Test logging in with WalletConnect (click on Game tab in Unity editor first). If it works, there will be an error related to GetNativeBalance but it should show the wallet address on screen.

Error unauthorized when calling API with SDK methods

There is a missing header that is required, workaround is to open Moralis Web3 Unity SDK package > Runtime/Web3Api/Client/ApiClient.cs and under existing default headers, add x-parse-application-id:

_defaultHeaderMap.Add("x-moralis-platform-version", "v1.2.10");
_defaultHeaderMap.Add("x-parse-application-id", Moralis.DappId);

Or add this header from your Parse server (Express) as middleware in src/index.ts:

app.use('/server/functions/:functionName', (req, res, next) => {
  req.headers['x-parse-application-id'] = '001';
  next();
});

app.use(`/server`, parseServer);

Alternatively instead of using the SDK methods you can call the corresponding cloud function for the API method e.g. for GetNativeBalance in CongratulationsController.cs from demo scene:

Replace:

NativeBalance balanceResponse = await Moralis.Web3Api.Account.GetNativeBalance(user.ethAddress, Moralis.CurrentChain.EnumValue);

With:

using System.Collections.Generic; // for Dictionary

IDictionary<string, object> balanceParams = new Dictionary<string, object>();

balanceParams.Add("address", user.ethAddress);
balanceParams.Add("chain", Moralis.CurrentChain.ChainId);
// WebGL requestMessageParams.Add("chain", Web3GL.ChainId());

Dictionary<string, object> balanceResponse = await Moralis.Cloud.RunAsync<Dictionary<string, object>>("getNativeBalance", balanceParams);

// previously balanceResponse.Balance
balanceResponse["balance"].ToString()

For WebGL, follow the same steps in the code above in the same AuthenticationKit.cs file (near the top) and use Web3GL.ChainId() instead of session.ChainId.

Tested only up to basic authentication (WalletConnect and WebGL) and with calling API:

  • Moralis Game Kit version: 1.2.10
  • Unity editor version: 2021.3.4
5 Likes

Thank you @alex so much!

Everything work good. For WebGL I Add

IDictionary<string, object> requestMessageParams = new Dictionary<string, object>();

requestMessageParams.Add("address", address);
requestMessageParams.Add("chain", Web3GL.ChainId());
requestMessageParams.Add("network", "evm");

Dictionary<string, object> authMessage = await Moralis.Cloud.RunAsync<Dictionary<string, object>>("requestMessage", requestMessageParams);

signMessage = authMessage["message"].ToString();

Above line 267 // Try to sign and catch the Exception when a user cancels the request too

Perhaps you @alex meant it, but I was not attentive. At First I add this only in one place - here and webgl didn’d work.

Ok, I’m such an idiot, I can’t figure out how to do this without my changes getting overwritten every time I run Unity. How can I change this in a way that “sticks”?

Ok, I have learned that I had to copy the directory from the Library folder to the Packages folder and modify it there. In this way, it is supposed to supersede the Library version as I understand it.

I have another equally noobish question since it is still not working for me. I have implemented the GCP Cloud Run solution based on the tutorial at: https://docs.moralis.io/docs/using-unity-google-cloud

Would I need to modify the Unity code differently for this? Do I need to add more functions to the GCP server?

Any help is appreciated!

Hi community!

The changes proposed by @alex have been merged into the SDK.

Now using a self-hosted Moralis Server shouldn’t bring you any problem.

Cheers,

David

4 Likes

@dpradell how can i add these changes in my project .IF you have any reference project please help me out

@alex

Hey all,

Our team is facing similar issues when trying to sign a Metamask message using the WebGL Unity v1 SDK on a self hosted server.
Repo used: [https://github.com/MoralisWeb3/unity-web3-game-kit]

So far we have:

  • connected the Metamask wallet to Unity
  • Initialized Moralis successfully

We now need to:

  • sign a message
  • get all NFTs from the connected wallet

Unfortunately, we are facing issues when running the “AuthenticationKit” and trying to sign a message
This is the line that throws and error "Dictionary<string, object> authMessage = await Moralis.Cloud.RunAsync<Dictionary<string, object>>("requestMessage", requestMessageParams);

So far we have tested the solutions explained here: https://forum.moralis.io/t/using-unity-sdk-with-self-hosted-server/20527 and used Web3GL.ChainId() instead of session.ChainId.
Issue is still here even after the latest commit here https://github.com/MoralisWeb3/web3-unity-sdk/commit/393d8d904bf2c7b12f1c1892a270e282066e5c4b

Any idea that could help us?
Thanks!

We rolled back the last changes as they’re not compatible with Moralis-hosted servers. If you’re self-hosting, just follow what @alex says in the first message and it should work.

1 Like