Code Monkey home page Code Monkey logo

moralisweb3 / unity-web3-game-kit Goto Github PK

View Code? Open in Web Editor NEW
519.0 21.0 216.0 379.46 MB

Unity Web3 Game Kit is the fastest way to connect and build games for Web3. It provides a single workflow for building high performance dapps. Fully compatible with your favourite platform.

License: MIT License

C# 39.46% CSS 4.14% HTML 12.86% JavaScript 20.21% Shell 17.71% XSLT 5.62%
moralis web3 unity3d avalanche binance blockchain crypto dapps defi ethereum

unity-web3-game-kit's Introduction

Unity Web3 Game Kit

Web3 Game Kit is the fastest way to connect and build games for Web3. It provides a single workflow for building high performance dapps. Fully compatible with your favourite platform.

This kit is built on Moralis Web3 Unity SDK and Moralis.

Please check the official documentation of Moralis for all the functionalities of Moralis.

Demo

⭐️ Star us

If this kit helps you build dapps faster - please star this project, every star makes us very happy!

🌇 Community

The best thing about Moralis is the super active community ready to help at any time! We help each other.

🤝 Need help?

If you need help with setting up the kit or have other questions - don't hesitate to write in our community forum and we will check asap. Forum link.

Discord

Become a Moralis Mage - join the Moralis DAO Discord

Feedback

To give feedback, ask a question or make a feature request, you can either use the Forum or the game-dev Discord thread.

Bugs are logged using the github issue system. To report a bug, simply open a new issue.

🚀 Quick Start

⚠️ Please read this before updating your project

The 1.2.0 release represents a major reworking of the project and includes namespace and structural changes in addition to functionality changes. Please be cautious when migrating from previous versions to 1.2.0. See the CHANGELOG for more information.

💿 Install all dependencies:

  1. Using Unity 2020.3 or higher, create a new game project.
  2. Download and install the latest package. Add Package
  3. Enter your Moralis Server information in the Setup Wizard. insertvalues
  4. Open and run the demo scene.

This kit has been tested with the following Unity3D Releases:

  1. 2020.3.34f1
  2. 2021.3.3f1

🧭 Table of contents

🏗 Moralis Web3 Unity SDK

The Moralis Web3 Unity SDK provides easy to use methods that make integrating your application with Moralis a snap. You will find that the.NET SDK works much the same as in JavaScript. For use in Unity3D, we have added additional quick start objects for integrating the Moralis Web3 Unity SDK in a Unity3D application. For the examples that follow we provide examples of how to use the Moralis Web3 Unity SDK using the provided Moralis Unity3D quick start tools.

Client

The Moralis Web3 Unity SDK Client provides a way to easily interact with Moralis database and the Web3API. For Unity3D we have provided a singleton wrapper named Moralis that makes it easy to initialize the MoralisClient and then access it from anywhere in your Unity3D application.

SDK Client Initialization

We have provided the AuthenticationKit prefab to make authenticating to Moralis with your crypto wallet a snap.

Just drag the prefab from Packages\io.moralis.web3-unity-sdk\Runtime\Kits\AuthenticationKit\Prefabs into your authentication screen. That is all you need to do to get started. The AuthenticationKit.prefab is not needed anywhere else in your game.

Initialize Client You do not have to use the AuthenticationKit. You can create a completely custom authentication process if you wish and initialize Moralis at the place and time of your choosing.

MoralisClient moralis = new MoralisClient(new ServerConnectionData() { ApplicationID = "YOUR_APPLICATION_ID_HERE", ServerURI = "YOUR_SERER_URL_HERE"}, new Web3ApiClient());

note: The new Web3ApiClient() parameter is optional and should be included only when you will be using functionality from the Moralis Web3API REST service.

Unity3D Client Initialization

Initialize Client

Moralis.Initialize(MoralisApplicationId, MoralisServerURI, hostManifestData);

note: For the hostManifestData parameter see HostManifestData. This is required for Unity3D applications. note: See User Object for information about initializing the Moralis Client for a custom User Object.

Authentication

Authentication is handled in a similar manner in both the SDK and the Unity3d. There is no direct manner to interact securely with a wallet in a .NET application so the Moralis Web3 Unity SDK interacts with wallets in a loosely coupled manner. For the Unity3D boilerplate application, and the other examples we provide, we use Wallet Connect to facilitate interaction with wallets.

Basic Moralis Authentication

MoralisUser user = await Moralis.LogInAsync(authentication-Data);

note: See Authentication Data for information about the authenticationData parameter.

Wallet Connect Authentication Example

public async void WalletConnect_OnConnectedEventSession(WCSessionData wcSessionData)
{
     // Extract wallet address from the Wallet Connect Session data object.
    string address = wcSessionData.accounts[0].ToLower();
    string appId = Moralis.DappId;
    long serverTime = 0;

    // Retrieve server time from Moralis Server for message signature
    Dictionary<string, object> serverTimeResponse = await Moralis.Cloud
        .RunAsync<Dictionary<string, object>>("getServerTime", new Dictionary<string, object>());

    if (serverTimeResponse == null || !serverTimeResponse.ContainsKey("dateTime") ||
        !long.TryParse(serverTimeResponse["dateTime"].ToString(), out serverTime))
    {
        Debug.LogError("Failed to retrieve server time from Moralis Server!");
    }

    string signMessage = $"Moralis Authentication\n\nId: {appId}:{serverTime}";

    string signature = null;

    signature = await _walletConnect.Session.EthPersonalSign(address, signMessage);

    // Create Moralis auth data from message signing response.
    Dictionary<string, object> authData = new Dictionary<string, object>
    {
        { "id", address }, { "signature", signature }, { "data", signMessage }
    };

    // Attempt to login user.
    MoralisUser user = await Moralis.LogInAsync(authData, wcSessionData.chainId.Value);
}

WebGL Authentication Example

string address = Web3GL.Account().ToLower();
string appId = Moralis.DappId;
long serverTime = 0;

// Retrieve server time from Moralis Server for message signature
Dictionary<string, object> serverTimeResponse =
    await Moralis.Cloud.RunAsync<Dictionary<string, object>>("getServerTime", new Dictionary<string, object>());

if (serverTimeResponse == null || !serverTimeResponse.ContainsKey("dateTime") ||
    !long.TryParse(serverTimeResponse["dateTime"].ToString(), out serverTime))
{
    Debug.LogError("Failed to retrieve server time from Moralis Server!");
}

string signMessage = $"Moralis Authentication\n\nId: {appId}:{serverTime}";
                
string signature = null;
                
signature = await Web3GL.Sign(signMessage);
                
// Create Moralis auth data from message signing response.
Dictionary<string, object> authData = new Dictionary<string, object>
{
    { "id", address }, { "signature", signature }, { "data", signMessage }
};

// Get chain Id
int chainId = Web3GL.ChainId();

// Attempt to login user.
MoralisUser user = await Moralis.LogInAsync(authData, chainId);

Queries

Queries provide a way to retrieve information from your Moralis database.

The following example will return all Hero records where 'Level' is equal to 3.

Query Example

MoralisQuery<Hero> q = await Moralis.Query<Hero>();
q = q.WhereEqualTo("Level", 3);
IEnumerable<Hero> result = await q.FindAsync();

The Moralis Web3 for Unity SDK supports the same query methods as the JS SDK. For example creating 'OR', 'AND', and 'NOR' queries. For this example we will take a base query and construct an 'OR' query that returns records where Level is greater or equal to '3' OR the hero's name is 'Zuko'. Furthermore we will sort (order) the result set by the hero's strength, descending.

Compound Query Example

MoralisQuery<PlayerData> q = await Moralis.Query<PlayerData>();
MoralisQuery<PlayerData> q1 = q.WhereGreaterThanOrEqualTo("Level", 2);
MoralisQuery<PlayerData> q2 = q.WhereEqualTo("Name", "Zuko");
MoralisQuery<PlayerData> q3 = Moralis.BuildOrQuery<PlayerData>(new MoralisQuery<PlayerData>[] { q1, q2 }).OrderByDescending("Strength");
IEnumerable<PlayerData> result = await q3.FindAsync();

Live Queries

Live Queries are queries that include a subscription that provide updates whenever the data targeted by the query are updated. A Live Query subscription emits events that indicate the state of the client and changes to the data. For more information please see the docs.

The following examples use the query example from above

Live Query Example

Since Unity3d is mainly used to create games, Unity3D apps generaly have life cycle events you do not usually need to worray about in a normal program. We have created a special Live Query wrapper object that automatically handles your subscriptions for pause, unpause, close, etc. This example shows how to create your subscription using this wrapper class.

MoralisQuery<Hero> q = Moralis.Query<Hero>();
MoralisLiveQueryController.AddSubscription<Hero>("Hero", q, callbacks);

_note: the callbacks parameter is optional. Please see Callbacks Explained bellow.

The MoralisLiveQueryController is a singleton object and so is available anywhere within your application. The first parameter ("Hero" above") is a key that you can use to retrieve a subscription (to check its status for example) or to remove a subscription.

By using the The MoralisLiveQueryController object you do not need to worry about properly closing or disposing of your subscriptions as this wrapper object handles all of that for you.

Live Query Callbacks Explained.

Callbacks are used to handle the events emitted by a subscription. You can set the callbacks directly against a subscription. However it is usually cleaner to separate these from the main code. To facilitate this we have included the MoralisLiveQueryCallbacks object. This optional object can be passed to the subscription.

Example MoralisLiveQueryCallbacks Use

MoralisLiveQueryCallbacks<Hero> callbacks = new MoralisLiveQueryCallbacks<Hero>();
callbacks.OnConnectedEvent += (() => { Debug.Log("Connection Established."); });
callbacks.OnSubscribedEvent += ((requestId) => { Debug.Log($"Subscription {requestId} created."); });
callbacks.OnUnsubscribedEvent += ((requestId) => { Debug.Log($"Unsubscribed from {requestId}."); });
callbacks.OnErrorEvent += ((ErrorMessage em) =>
{
    Debug.Log($"ERROR: code: {em.code}, msg: {em.error}, requestId: {em.requestId}");
});
callbacks.OnCreateEvent += ((item, requestId) =>
{
    Debug.Log($"Created hero: name: {item.Name}, level: {item.Level}, strength: {item.Strength} warcry: {item.Warcry}");
});
callbacks.OnUpdateEvent += ((item, requestId) =>
{
    Debug.Log($"Updated hero: name: {item.Name}, level: {item.Level}, strength: {item.Strength} warcry: {item.Warcry}");
});
callbacks.OnDeleteEvent += ((item, requestId) =>
{
    Debug.Log($"Hero {item.Name} has been defeated and removed from the roll!");
});
callbacks.OnGeneralMessageEvent += ((text) =>
{
    Debug.Log($"Websocket message: {text}");
});

Custom Object

Creating your own objects to support NPCs, characters, and game objects is as simple as creating a Plain Old C# Object (POCO). The only stipulation is that your custom object must be a child of Moralis Object and when you create an instance of the object it should be made via moralis.Create method. This associates some extensions to your object that enable you to perform Moralis functions such as Save directly on the object. Note: Inclusion of _base([OBJECT NAME]) is important for proper database handling.

Sample Object

public class Hero : MoralisObject
{
    public int Strength { get; set; }
    public int Level { get; set; }
    public string Name { get; set; }
    public string Warcry { get; set; }
    public List<string> Bag { get; set; }

    public Hero() : base("Hero") 
    {
        Bag = new List<string>();
    }
}

Create and Save Instance of Object

Hero h = Moralis.Create<Hero>();
h.Name = "Zuko";
h.Strength = 50;
h.Level = 15;
h.Warcry = "Honor!!!";
h.Bag.Add("Leather Armor");
h.Bag.Add("Crown Prince Hair clip.");

await h.SaveAsync();

User Object

The user object contains information about the currently logged in user. Upon successful login, the user is stored in local storage until logout. This allows a user to log in once and not login again until their session expires or they logout.

If you need to create an instance of MoralisUser for any reason (example: to SignUp with username and password) you should do so in this manner:

MoralisUser user = Moralis.Create<MoralisUser>();

Using this method instead of the default constructor of MoralisUser ensures that the MoralisUser object created is associated with the Moralis instance. This means that several methods of the object will not work problerly (such as SaveAsync, SignUpAsync, etc.).

If you create a custom user object it must inherit from MoralisUser.

Since C# is a typed language the compiler must know what types are used at compile time. Due to this, since the MoralisUser is integral to internal functions in the Moralis Web3 Unity SDK, when you create a custom User Object you must initialize the Moralis client using your custom User Object. After this step you can use the Moralis Client as usual.

Initialize Moralis Client with Custom User Object

MoralisClient<YourUserObject> moralis = new MoralisClient<YourUserObject>(new ServerConnectionData() { ApplicationID = "YOUR_APPLICATION_ID_HERE", ServerURI = "YOUR_SERER_URL_HERE"}, new Web3ApiClient());

note: for Unity3D you will need to make the above change in the Moralis.Initialize object. You will also need to replace the MoralisUser object elsewhere in the Boilerplate code. WARNING do not make any replacements to any files under the MoralisDtoNet folder

Authentication Data

Authentication data is a Dictionary<string, string> object that contains the information required by Moralis to authenticate a user. As a minimum the authentication data dictionary must contain the following entries:

  1. id The wallet address of the wallet used to sign the message.
  2. signature The signature data returned by the Sign request sent to the wallet.
  3. data The message that was sent to the wallet to be signed.

Example

Dictionary<string, object> authData = new Dictionary<string, object> { { "id", "ADDRESS_HERE".ToLower() }, { "signature", "SIGNATURE_DATA_HERE" }, { "data", "MESSAGE_HERE" } };

HostManifestData

In Unity3D applications the HostManifestData object is used to pass information to Moralis that is usually autogenerated from Windows system variables. Since Unity3D supports multiple platforms this information is not always available.

ServerConnectionData

Description here

Web3

The Web3 object is used for executing Evm RPC calls, meaning transactions directly against the chain. While the Web3Api is more efficient for most Web3 calls, the Web3Api does not support state changes or transactions. The Web3 object does allow state change and transactions against the change.

For Web3 support, an Nethereum Web3 object is exposed in the Moralis. Developers can use the Web3 object directly.

IMPORTANT Before it can be used, the Web3 object must be initialized, unfortunetly this cannot be done until a connection to the wallet is established.

    private void InitializeWeb3()
    {
        Moralis.SetupWeb3();
    } 

    /// <summary>
    /// Must be referenced by the WalletConnect Game object
    /// </summary>
    /// <param name="session"></param>
    public void WalletConnectSessionEstablished(WalletConnectUnitySession session)
    {
        InitializeWeb3();
    }

To make Web3 calls easier we have included a few tools.

First, a EvmContractManager object (currently not available for WebGL) provides an easy way to set up contracts that are reflected across several chains. The Contract andits functions can be easily retrieved from any where in your code via Moralis.

To setup a contract instance use InsertContractInstance:

Moralis.InsertContractInstance("Rewards", GameAwardContractAbi(), "mumbai", "0x05af21b57d2E378F90106B229E717DC96c7Bb5e2");

In this example a contract with key "Rewards" is created using the contract ABI (as json), the main chain the contract is on, and the address of the contract on that chain. For a live example please see the MainMenuScript.cs file.

By calling Moralis.AddContractChainAddress([CONTRACT KEY], [CHAIN ID], [CONTRACT ADDRESS]) you can create multiple chain specific instances of the same contract using the ABI originally added with [CONTRACT KEY].

To retrieve an Nethereum contract instance call:

Contract c = Moralis.EvmContractInstance([CONTRACT KEY], [CHAIN ID]);

Retrieve an Nethereum contract function instance:

Function f = Moralis.EvmContractFunctionInstance([CONTRACT KEY], [CHAIN ID], [FUNCTION NAME]);

Call function with no parameters

// No parameters
object[] pars = new object[0];
string jsonResult = await f.CallAsync(pars);

Call function with parameters

object[] pars = {"My string", 2};
string jsonResult = await f.CallAsync(pars);

Call function with parameters, specify from, gas, and value.

string playerAddress = "0x37bd48252f4dcE15C7147eA82b31978a00750f81";
object[] pars = {"My string", 2};
Nethereum.Hex.HexTypes.HexBigInteger g = new Nethereum.Hex.HexTypes.HexBigInteger(80);
Nethereum.Hex.HexTypes.HexBigInteger wei = new Nethereum.Hex.HexTypes.HexBigInteger(1000);
string jsonResult = await func.CallAsync(playerAddress, new Nethereum.Hex.HexTypes.HexBigInteger(80), new Nethereum.Hex.HexTypes.HexBigInteger(1000), pars);

For other call function varients see the Nethereum documentation.

To execute a transaction you can also call Moralis.SendEvmTransactionAsync or Moralis.SendTransactionAndWaitForReceiptAsync. These functions represent only a couple of the variants available from the Nethereum.Contracts.Function object.

WebGL

Due to the way WebGL works, for security reasons, it does not support outbound calls or multi-threading. The Moralis Web3 Unity SDK depends heavily on both. For most functionality the switch between other build types and WebGL should be seemless.

  • IMPORTANT In Player Settings change the WebGL template to the Moralis WebGL Template

When you have a file that is used for both WebGL and non-WebGL builds use the UNITY_WEBGL pre-processor statement to seperate the code that will be used for each type of build. As example here is part of the using statement from the TokenListController.cs file from the Boilerplate Example:

#if UNITY_WEBGL
// WebGL specific code here
#else
// Non WebGL code here
#endif

Loading External Resources

Under the hood, WebGL loads external resources similar to javascript using AJAX. This means that you can run into CORs issues in the client browser when loading external resources. The prescribed method to solve this issue (as settings for CORS are on the server side) is to create a proxy service.

As part of the WebGL solution example, the TokenListController.cs file shows how to use a Moralis Cloud function as a proxy for loading external resources. To successfully display the images of tokens in the wallet example you will need to create the following cloud function in your Moralis server.

  1. Log into Moralis, select and expand your Server instance.
  2. Click on the "Cloud Functions" button.
  3. Copy the following code into your Cloud Functions
Moralis.Cloud.define("loadResource", async (request) => {
  const logger = Moralis.Cloud.getLogger();
  
  return await Moralis.Cloud.httpRequest({
    url: request.params.url
  }).then(function(httpResponse) {
    let resp = {status: httpResponse.status, headers: httpResponse.headers, data: JSON.stringify(httpResponse.buffer)};
    return resp;
  },function(httpResponse) {
    // Error occurred
    logger.error('Request failed with response code ' + httpResponse.status);
    return httpResponse;
  });
}, {
	fields : ["url"]
});
  1. Click on the "Save" button.

🏗 Ethereum Web3Api Methods

Web3Api Notes

The complete Moralis Web3API schema including endpoints, operations and models, can be found by logging in to your Moralis Server and selecting Web3 API*

For use with either Moralis Web3 Unity SDK or in Unity3d, the following using statements are required:

Chains

Use the code snippet below to retrieve a list of EVM chains supported in the Moralis Web3API. This list can be used for populating dropdown lists etc.

Example

List<ChainEntry> chains = Moralis.SupportedChains;

Account

Code examples demonstrating how to use the Moralis Web3API Account endpoint and operations.

GetNativeBalance

Gets native balance for a specific address

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • providerUrl string OPTIONAL web3 provider url to user when using local dev chain
  • toBlock string OPTIONAL The maximum block number from where to get the logs.

Example

NativeBalance balance = await Moralis.Web3Api.Account.GetNativeBalance(address.ToLower(), ChainList.eth);
Debug.Log($"GetNativeBalance Balance: {balance.Balance}");

GetNFTs

Gets NFTs owned by the given address

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • format string OPTIONAL The format of the token id
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit
  • order string OPTIONAL The field(s) to order on and if it should be ordered in ascending or descending order. Specified by: fieldName1.order,fieldName2.order. Example 1: "name", "name.ASC", "name.DESC", Example 2: "Name and Symbol", "name.ASC,symbol.DESC"

Example

NftOwnerCollection nftCollection = await Moralis.Web3Api.Account.GetNFTs(userAddress, chainId);

if (nftCollection.Total < 1)
{
    Debug.Log($"User {userAddress} does not have any NFTs on chain {chainId.ToString()}");
}
else
{
    Debug.Log($"Nfts for User {userAddress}");

    foreach (NftOwner nft in nftCollection.Result)
    {
        Debug.Log($"TokenId: {nft.TokenId}, Name: {nft.Name}, Balance: {nft.Amount}");
    }
}

GetNFTsForContract

Gets NFTs owned by the given address

  • address string REQUIRED Target address
  • tokenAddress string REQUIRED Address of the contract
  • chain ChainList REQUIRED The chain to query
  • format string OPTIONAL The format of the token id
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit
  • order string OPTIONAL The field(s) to order on and if it should be ordered in ascending or descending order. Specified by: fieldName1.order,fieldName2.order. Example 1: "name", "name.ASC", "name.DESC", Example 2: "Name and Symbol", "name.ASC,symbol.DESC"

Example

NftOwnerCollection resp = await Moralis.Web3Api.Account.GetNFTsForContract(address.ToLower(), "0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", ChainList.eth);
Debug.Log($"GetNFTsForContract Count: {resp.Total}");

GetNFTTransfers

Gets the transfers of the tokens matching the given parameters

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • format string OPTIONAL The format of the token id
  • direction string OPTIONAL The transfer direction
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit
  • order string OPTIONAL The field(s) to order on and if it should be ordered in ascending or descending order. Specified by: fieldName1.order,fieldName2.order. Example 1: "name", "name.ASC", "name.DESC", Example 2: "Name and Symbol", "name.ASC,symbol.DESC"

Example

NftTransferCollection balance = await Moralis.Web3Api.Account.GetNFTTransfers(address.ToLower(), ChainList.eth);
Debug.Log($"GetNFTTransfers Matches: {balance.Total}");

GetTokenBalances

Gets token balances for a specific address

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)
  • toBlock string OPTIONAL The maximum block number from where to get the logs.

Example

List<Erc20TokenBalance> balance = await Moralis.Web3Api.Account.GetTokenBalances(address.ToLower(), ChainList.eth);
Debug.Log($"GetTokenBalances Count: {balance.Count}");

GetTokenTransfers

Gets ERC20 token transactions in descending order based on block number

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)
  • fromBlock string OPTIONAL The minimum block number from where to get the logs.
  • toBlock string OPTIONAL The maximum block number from where to get the logs.
  • fromDate string OPTIONAL The date from where to get the logs (any format that is accepted by momentjs).
  • toDate string OPTIONAL Get the logs to this date (any format that is accepted by momentjs)
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit

Example

Erc20TransactionCollection balance = await Moralis.Web3Api.Account.GetTokenTransfers(address.ToLower(), ChainList.eth);
Debug.Log($"GetTokenTransfers Count: {balance.Total}");

GetTransactions

Gets native transactions in descending order based on block number

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)
  • fromBlock string OPTIONAL The minimum block number from where to get the logs.
  • toBlock string OPTIONAL The maximum block number from where to get the logs.
  • fromDate string OPTIONAL The date from where to get the logs (any format that is accepted by momentjs).
  • toDate string OPTIONAL Get the logs to this date (any format that is accepted by momentjs)
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit

Example

TransactionCollection balance = await Moralis.Web3Api.Account.GetTransactions(address.ToLower(), ChainList.eth);
Debug.Log($"GetTransactions Count: {balance.Total}");

Defi

Code examples demonstrating how to use the Moralis Web3API Defi endpoint and operations.

GetPairAddress

Fetches and returns pair data of the provided token0+token1 combination. The token0 and token1 options are interchangable (ie. there is no different outcome in "token0=WETH and token1=USDT" or "token0=USDT and token1=WETH")

  • exchange string REQUIRED The factory name or address of the token exchange
  • token0Address string REQUIRED Token0 address
  • token1Address string REQUIRED Token1 address
  • chain ChainList REQUIRED The chain to query
  • toBlock string OPTIONAL The maximum block number from where to get the logs.
  • toDate string OPTIONAL Get the logs to this date (any format that is accepted by momentjs)

Example

ReservesCollection nftTransers = Moralis.Web3Api.Defi.GetPairAddress(exchange, token0Address, token1Address, ChainList.eth);

GetPairReserves

Get the liquidity reserves for a given pair address

  • pairAddress string REQUIRED Liquidity pair address
  • chain ChainList REQUIRED The chain to query
  • toBlock string OPTIONAL The maximum block number from where to get the logs.
  • toDate string OPTIONAL Get the logs to this date (any format that is accepted by momentjs)
  • providerUrl string OPTIONAL web3 provider url to user when using local dev chain

Example

ReservesCollection nftTransers = Moralis.Web3Api.Defi.GetPairReserves(pairAddress, ChainList.eth);

Native

Code examples demonstrating how to use the Moralis Web3API Native endpoint and operations.

GetBlock

Gets the contents of a block by block hash

  • blockNumberOrHash string REQUIRED The block hash or block number
  • chain ChainList REQUIRED The chain to query
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)

Example

Block block = Moralis.Web3Api.Native.GetBlock(blockNumberOrHash, ChainList.eth);

GetContractEvents

Gets events in descending order based on block number

  • address string REQUIRED Target address
  • topic string REQUIRED The topic of the event. This is the hash of the function
  • abi object REQUIRED ABI of the event being searched for. See example below for object format.
  • chain ChainList REQUIRED The chain to query
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)
  • providerUrl string OPTIONAL web3 provider url to user when using local dev chain
  • fromBlock string OPTIONAL The minimum block number from where to get the logs.
  • toBlock string OPTIONAL The maximum block number from where to get the logs.
  • fromDate string OPTIONAL The date from where to get the logs (any format that is accepted by momentjs).
  • toDate string OPTIONAL Get the logs to this date (any format that is accepted by momentjs)
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit

Example

    // Event ABI input parameters
    object[] inputParams = new object[3];
    inputParams[0] = new { indexed = true, internalType = "bytes32", name = "role", type = "bytes32" };
    inputParams[1] = new { indexed = true, internalType = "address", name = "account", type = "address" };
    inputParams[2] = new { indexed = true, internalType = "address", name = "sender", type = "address" };
    // Event ABI
    object abi = new { anonymous = false, inputs = inputParams, name = "RoleGranted", type = "event" };

    List<LogEvent> logEvents = await Moralis.Web3Api.Native.GetContractEvents("0x698d7D745B7F5d8EF4fdB59CeB660050b3599AC3", "0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d", abi, ChainList.mumbai);

    Debug.Log($"Contract Function returned {logEvents.Count} events");

GetDateToBlock

Gets the closest block of the provided date

  • data string REQUIRED Unix date in miliseconds or a datestring (any format that is accepted by momentjs)
  • chain ChainList REQUIRED The chain to query
  • providerUrl string OPTIONAL web3 provider url to user when using local dev chain

Example

string blockNumberOrHash = "25509457";
Block block = await Moralis.Web3Api.Native.GetBlock(blockNumberOrHash, chainId);
Debug.Log($"GetBlock BlockNumber: {block.Number}, Transaction Count: {block.TransactionCount}");

GetLogsByAddress

Gets the logs from an address

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)
  • blockNumber string OPTIONAL The block number.
  • fromBlock string OPTIONAL The minimum block number from where to get the logs.
  • toBlock string OPTIONAL The maximum block number from where to get the logs.
  • fromDate string OPTIONAL The date from where to get the logs (any format that is accepted by momentjs).
  • toDate string OPTIONAL Get the logs to this date (any format that is accepted by momentjs)
  • topic0 string OPTIONAL
  • topic1 string OPTIONAL
  • topic2 string OPTIONAL
  • topic3 string OPTIONAL

Example

LogEventByAddress logEvents = await Moralis.Web3Api.Native.GetLogsByAddress(userAddress, chainId);
Debug.Log($"GetLogsByAddress BlockNumber: {logEvents.BlockNumber}, Transaction Count: {logEvents.Data}");

GetNFTTransfersByBlock

Gets NFT transfers by block number or block hash

  • blockNumberOrHash string REQUIRED The block hash or block number
  • chain ChainList REQUIRED The chain to query
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)

Example

NftTransferCollection nftTransfers = await Moralis.Web3Api.Native.GetNFTTransfersByBlock("500000", chainId);
Debug.Log($"GetNFTTransfersByBlock Nfts returned: {nftTransfers.Result.Count}");

GetTransaction

Gets the contents of a block transaction by hash

  • transactionHash string REQUIRED The transaction hash
  • chain ChainList REQUIRED The chain to query
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)

Example

string transactionHash = "0xe1ec2dd9964f4dc59b53dce083917abfb5ab5191a37cb1e21566969caa614fcd";
BlockTransaction blockTransaction = await Moralis.Web3Api.Native.GetTransaction(transactionHash, ChainList.mumbai);
Debug.Log($"Block transaction BlackNumber: {blockTransaction.BlockNumber}, from Address: {blockTransaction.FromAddress}");

RunContractFunction

Runs a given function of a contract abi and returns readonly data

  • address string REQUIRED Target address
  • abi object REQUIRED Abi of the Function being called - see example for format.
  • chain ChainList REQUIRED The chain to query
  • functionName string REQUIRED Function name of the target function.
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)
  • providerUrl string OPTIONAL web3 provider url to user when using local dev chain

Example

// Function ABI input parameters
object[] inputParams = new object[1];
inputParams[0] = new { internalType = "uint256", name = "id", type = "uint256" };
// Function ABI Output parameters
object[] outputParams = new object[1];
outputParams[0] = new { internalType = "string", name = "", type = "string" };
// Function ABI
object[] abi = new object[1];
abi[0] = new { inputs = inputParams, name = "uri", outputs = outputParams, stateMutability = "view", type = "function" };

// Define request object
RunContractDto rcd = new RunContractDto()
{
    Abi = abi,
    Params = new { id = "15310200874782" }
};

string resp = await Moralis.Web3Api.Native.RunContractFunction("0x698d7D745B7F5d8EF4fdB59CeB660050b3599AC3", "uri", rcd, ChainList.mumbai);

Debug.Log($"Contract Function returned: {resp}");

Resolve

Code examples demonstrating how to use the Moralis Web3API Resolve endpoint and operations.

ResolveDomain

Resolves an Unstoppable domain and returns the address

  • domain string REQUIRED Domain to be resolved
  • currency string OPTIONAL The currency to query.

Example

Resolve resp = await Moralis.Web3Api.Resolve.ResolveDomain("brad.crypto");
Debug.Log($"ResolveDomain Address: {resp.Address}");

ResolveAddress

Resolves an ETH address and find the ENS name

  • address string REQUIRED The wallet address to perform reverse lookup on.

Example

Ens resp = await Moralis.Web3Api.Resolve.ResolveAddress("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");
Debug.Log($"ResolveAddress Name: {resp.Name}");

Storage

Code examples demonstrating how to use the Moralis Web3API Storage endpoint and operations.

UploadFolder

Resolves an ETH address and find the ENS name

  • request List REQUIRED Upload Data

Example

// Define file information.
IpfsFileRequest req = new IpfsFileRequest()
{
	Path = "moralis/logo.jpg",
	Content = "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAApgAAAKYB3X3"
};

// Multiple requests can be sent via a List so define the request list.
List<IpfsFileRequest> reqs = new List<IpfsFileRequest>();

// Add requests to request list.
reqs.Add(req);

List<IpfsFile> resp = web3Api.Storage.UploadFolder(reqs);

Token

Code examples demonstrating how to use the Moralis Web3API Token endpoint and operations.

GetAllTokenIds

Gets data, including metadata (where available), for all token ids for the given contract address.

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • foramt string OPTIONAL The format of the token id
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit
  • order string OPTIONAL If the order should be Ascending or Descending based on the blocknumber on which the NFT was minted. Allowed values: "ASC", "DESC"

Example

NftCollection resp = await Moralis.Web3Api.Token.GetAllTokenIds("0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", ChainList.eth, null, 0, 10);
Debug.Log($"GetAllTokenIds returned {resp.Total} Nfts");

GetContractNFTTransfers

Gets the transfers of the tokens matching the given parameters

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • foramt string OPTIONAL The format of the token id
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit
  • order string OPTIONAL If the order should be Ascending or Descending based on the blocknumber on which the NFT was minted. Allowed values: "ASC", "DESC"

Example

NftTransferCollection resp = await Moralis.Web3Api.Token.GetContractNFTTransfers("0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", ChainList.eth, null, 0, 10);
Debug.Log($"GetContractNFTTransfers returned {resp.Total} Nft transfer entries");

GetNFTLowestPrice

Get the lowest price found for a nft token contract for the last x days (only trades paid in ETH)

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • days integer OPTIONAL Offset
  • providerUrl string OPTIONAL web3 provider url to user when using local dev chain
  • marketplace string OPTIONAL web3 marketplace from where to get the trades (only opensea is supported at the moment)

Example

Trade resp = await Moralis.Web3Api.Token.GetNFTLowestPrice("0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", ChainList.eth, 2000);
Debug.Log($"GetNFTLowestPrice Price: {resp.Price}");

GetNFTMetadata

Gets the contract level metadata (name, symbol, base token uri) for the given contract

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query

Example

NftContractMetadata resp = await Moralis.Web3Api.Token.GetNFTMetadata("0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", ChainList.eth);
Debug.Log($"GetNFTMetadata Name: {resp.Name}, TokenAddress: {resp.TokenAddress}");

GetNFTOwners

Gets all owners of NFT items within a given contract collection

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • format string OPTIONAL The format of the token id
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit
  • order string OPTIONAL If the order should be Ascending or Descending based on the blocknumber on which the NFT was minted. Allowed values: "ASC", "DESC"

Example

NftOwnerCollection resp = await Moralis.Web3Api.Token.GetNFTOwners("0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", ChainList.eth, null, 0, 10);
Debug.Log($"GetNFTOwners returned {resp.Total} Nft Owner records");

GetNFTTrades

Get the nft trades for a given contracts and marketplace

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • fromBlock string OPTIONAL The minimum block number from where to get the logs.
  • toBlock string OPTIONAL The maximum block number from where to get the logs.
  • fromDate string OPTIONAL The date from where to get the logs (any format that is accepted by momentjs).
  • toDate string OPTIONAL Get the logs to this date (any format that is accepted by momentjs)
  • providerUrl string OPTIONAL web3 provider url to user when using local dev chain
  • marketplace string OPTIONAL web3 marketplace from where to get the trades (only opensea is supported at the moment)
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit

Example

TradeCollection resp = await Moralis.Web3Api.Token.GetNFTTrades("0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", ChainList.eth, null, null, null, null, null, null, 0, 10);
Debug.Log($"GetNFTTrades returned {resp.Total} Nft trades");

GetNftTransfersFromToBlock

Gets the transfers of the tokens from a block number to a block number

  • chain ChainList REQUIRED The chain to query
  • fromBlock string OPTIONAL The minimum block number from where to get the logs.
  • toBlock string OPTIONAL The maximum block number from where to get the logs.
  • fromDate string OPTIONAL The date from where to get the logs (any format that is accepted by momentjs).
  • toDate string OPTIONAL Get the logs to this date (any format that is accepted by momentjs)
  • format string OPTIONAL The format of the token id
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit
  • order string OPTIONAL If the order should be Ascending or Descending based on the blocknumber on which the NFT was minted. Allowed values: "ASC", "DESC"

Example

NftTransferCollection resp = await Moralis.Web3Api.Token.GetNftTransfersFromToBlock(ChainList.eth, 99999, 25999999, null, null, null, 0, 10);
Debug.Log($"GetNftTransfersFromToBlock returned {resp.Total} Nft Transfers");

GetTokenAddressTransfers

Gets ERC20 token contract transactions in descending order based on block number

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)
  • fromBlock string OPTIONAL The minimum block number from where to get the logs.
  • toBlock string OPTIONAL The maximum block number from where to get the logs.
  • fromDate string OPTIONAL The date from where to get the logs (any format that is accepted by momentjs).
  • toDate string OPTIONAL Get the logs to this date (any format that is accepted by momentjs)
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit

Example

Erc20TransactionCollection resp = await Moralis.Web3Api.Token.GetTokenAddressTransfers("0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", ChainList.eth, null, null, null, null, null, 0, 10);
Debug.Log($"GetTokenAddressTransfers returned {resp.Total} transfer entries");

GetTokenAllowance

Gets the amount which the spender is allowed to withdraw from the spender

  • address string REQUIRED Target address
  • ownerAddress string REQUIRED Target address
  • spenderAddress string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • providerUrl string OPTIONAL web3 provider url to user when using local dev chain

Example

Erc20Allowance allowance = Moralis.Web3Api.Token.GetTokenAllowance(address, ownerAddress, spenderAddress, ChainList.eth);

GetTokenIdMetadata

Gets data, including metadata (where available), for the given token id of the given contract address.

  • address string REQUIRED Target address
  • tokenId string REQUIRED The id of the token
  • chain ChainList REQUIRED The chain to query
  • foramt string OPTIONAL The format of the token id

Example

Nft resp = await Moralis.Web3Api.Token.GetTokenIdMetadata("0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", "10", ChainList.eth);
Debug.Log($"GetTokenIdMetadata Name: {resp.Name}, Amount: {resp.Amount}");

GetTokenIdOwners

Gets all owners of NFT items within a given contract collection

  • address string REQUIRED Target address
  • tokenId string REQUIRED The id of the token
  • chain ChainList REQUIRED The chain to query
  • foramt string OPTIONAL The format of the token id
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit
  • order string OPTIONAL If the order should be Ascending or Descending based on the blocknumber on which the NFT was minted. Allowed values: "ASC", "DESC"

Example

NftOwnerCollection resp = await Moralis.Web3Api.Token.GetTokenIdOwners("0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", "10", ChainList.eth, null, 0, 10);
Debug.Log($"GetTokenIdOwners returned {resp.Total} Nfts");

GetTokenMetadata

Returns metadata (name, symbol, decimals, logo) for a given token contract address.

  • address List REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)
  • providerUrl string OPTIONAL web3 provider url to user when using local dev chain

Example

List<string> addresses = new List<string>();
addresses.Add("0x6b175474e89094c44da98b954eedeac495271d0f");
List<Erc20Metadata> resp = await Moralis.Web3Api.Token.GetTokenMetadata(addresses, ChainList.eth);
Debug.Log($"GetTokenMetadata returned {resp.Count} entries.");

GetTokenMetadataBySymbol

Returns metadata (name, symbol, decimals, logo) for a given token contract address.

  • symbols List REQUIRED Target address
  • chain ChainList REQUIRED The symbols to get metadata for
  • subdomain string OPTIONAL The subdomain of the moralis server to use (Only use when selecting local devchain as chain)

Example

List<string> symbols = new List<string>();
symbols.Add("DAI");
List<Erc20Metadata> resp = await Moralis.Web3Api.Token.GetTokenMetadataBySymbol(symbols, ChainList.eth);
Debug.Log($"GetTokenMetadataBySymbol returned {resp.Count} entries.");

GetTokenPrice

Returns the price nominated in the native token and usd for a given token contract address.

  • address string REQUIRED Target address
  • chain ChainList REQUIRED The chain to query
  • providerUrl string OPTIONAL web3 provider url to user when using local dev chain
  • exchange string OPTIONAL The factory name or address of the token exchange
  • toBlock string OPTIONAL The maximum block number from where to get the logs.

Example

Erc20Price resp = await Moralis.Web3Api.Token.GetTokenPrice("0x6b175474e89094c44da98b954eedeac495271d0f", ChainList.eth);
Debug.Log($"GetTokenPrice Price: {resp.UsdPrice} USD");

GetWalletTokenIdTransfers

Gets the transfers of the tokens matching the given parameters

  • address string REQUIRED Target address
  • tokenId string REQUIRED The id of the token
  • chain ChainList REQUIRED The chain to query
  • foramt string OPTIONAL The format of the token id
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit
  • order string OPTIONAL If the order should be Ascending or Descending based on the blocknumber on which the NFT was minted. Allowed values: "ASC", "DESC"

Example

NftTransferCollection resp = await Moralis.Web3Api.Token.GetWalletTokenIdTransfers("0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", "10", ChainList.eth, null, 0, 10);
Debug.Log($"GetWalletTokenIdTransfers returned {resp.Total} Nfts");

SearchNFTs

Gets NFTs that match a given metadata search.

  • q string REQUIRED The search string
  • chain ChainList REQUIRED The chain to query
  • foramt string OPTIONAL The format of the token id
  • filter string OPTIONAL What fields the search should match on. To look into the entire metadata set the value to 'global'. To have a better response time you can look into a specific field like name. Available values : name, description, attributes, global, name,description, name,attributes, description,attributes, name,description,attributes
  • fromBlock string OPTIONAL The minimum block number from where to get the logs.
  • toBlock string OPTIONAL The maximum block number from where to get the logs.
  • fromDate string OPTIONAL The date from where to get the logs (any format that is accepted by momentjs).
  • toDate string OPTIONAL Get the logs to this date (any format that is accepted by momentjs)
  • offset integer OPTIONAL Offset
  • limit integer OPTIONAL Limit

Example

NftMetadataCollection resp = await Moralis.Web3Api.Token.SearchNFTs("Apes", ChainList.eth, null, null, null, null, null, null, 0, 10);
Debug.Log($"SearchNFTs returned {resp.Total} Nfts");

🏗 Solana Api Methods

Solana Account

Solana Balance

NativeBalance bal = await Moralis.SolanaApi.Account.Balance(NetworkTypes.mainnet, "6XU36wCxWobLx5Rtsb58kmgAJKVYmMVqy4SHXxENAyAe");

Solana GetNFTs

List<SplNft> bal = await Moralis.SolanaApi.Account.GetNFTs(NetworkTypes.mainnet, "6XU36wCxWobLx5Rtsb58kmgAJKVYmMVqy4SHXxENAyAe");

Solana GetPortfolio

Portfolio bal = await Moralis.SolanaApi.Account.GetPortfolio(NetworkTypes.mainnet, "6XU36wCxWobLx5Rtsb58kmgAJKVYmMVqy4SHXxENAyAe");

Solana GetSplTokens

List<SplTokenBalanace> bal = await Moralis.SolanaApi.Account.GetSplTokens(NetworkTypes.mainnet, "6XU36wCxWobLx5Rtsb58kmgAJKVYmMVqy4SHXxENAyAe");

Solana NFT

Solana GetNFTMetadata

NftMetadata bal = await Moralis.SolanaApi.Nft.GetNFTMetadata(NetworkTypes.mainnet, "6XU36wCxWobLx5Rtsb58kmgAJKVYmMVqy4SHXxENAyAe");

Helpful Tools

  1. Unity3d Assets The best place to find Unity3d Assets for a range of budgets.
  2. The Gimp Open source image editing tool
  3. Blender Open source tool for creating 3D models, animations, textures, and everything else you need for game characters and objects.
  4. Maximo Free to use (with registration) Animations for humanoid rigged models.

unity-web3-game-kit's People

Contributors

bmateus avatar dpradell-dev avatar ivan-liljeqvist avatar koenrijpstra avatar shanghai-bill avatar xactant avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unity-web3-game-kit's Issues

iOS XCODE Update Causes Build Error

The Moralis Network object created to replace Websockets for WebGL are causing build errors after a recent XCode update. As this code is only used for WebGL, this code should be isolated to only build for WebGL.

As a test this was done on a Mac build and the exception no longer occurred.

Moralis Client Delete Method not Implemented.

Underlying service method:

ServiceHub.ObjectService.DeleteAsync([OBJECT], [SESSION_TOKEN])

Is not exposed via the Moralis Client forcing user's to search code for the needed method.

Modify Client so that DeleteAsync is exposed.

WEBGL: Websocket.instance.ws.onopen

I’m testing the demo scene and when I run the game in my browser, I get this error:

An error ocurred running the unity context on this page. See your browser JavaScript console for mora info.
The error whas: ReferenceError: Runtime is not defined at WebSocket.instance.ws.onopen(https://********/build/Build.framework.js.br:3:58138)

capture-2122022

Can't collect Mug

Unity 2020.3.24f1
sdk v1_0_5
metamask

Whenever I click the mug It it throws:
'Web3 has not been setup yet'
I've added server uri, app id and rpc node url

On Object Create ACL not instantiated

When an object is created using MorlaisInterface.GetClient().Create the ACL of the object is not automatically instantiated. This forces the user to instantiate the ACL before setting access.

Update MoralisObject so that ACL is instantiated in the constructor.

The format of the URI could not be determined.

On the demo scene , I am Having this issue when connecting with wallet connect with trust wallet:

UriFormatException: Invalid URI: The format of the URI could not be determined. System.Uri.CreateThis (System.String uri, System.Boolean dontEscape

This shows on the consol after I authentify with the app. But the QR still apears !

unity Moralis problem

I have a problem from unity Moralis template. Why is the contract method not called through the contract address? Why? I cant use it, Please sir, I have not idea.

Unity Issues

Below errors propped up, using Unity 2020,03.26f1, kindly help.

image

BUG: Cannot set ACL to Public

Every time I create a Class and set the ACL to Public, It always defaults to "Master Key Only". As a result, I cannot query the Class data.

image

GetAsync returns first object instead of requested object

GetAsync accepts the parameter string objectId.

Expected

The returned object is the object that coincides with the objectId provided as a string.

Result

The returned object is the first object (chronologically by createdAt) in the Moralis Class, no matter what objectId is supplied.

Test

Code:

public async void TestGetObject()
{
    const string OBJECT_ID = "TuNotA2E4qZkyhWMIaBonDWf";

    var r_getAsync  = await MoralisInterface.GetClient().Query<MyMoralisObject>().GetAsync(OBJECT_ID);

    var q_findAsync = MoralisInterface.GetClient().Query<MyMoralisObject>().WhereEqualTo("objectId", OBJECT_ID);
    var r_findAsync = await q_findAsync.FindAsync();
    var v_findAsync = r_findAsync.FirstOrDefault();

    var r = await MoralisInterface.GetClient().Query<MyMoralisObject>().WhereEqualTo("objectId", OBJECT_ID).FirstAsync();

    Debug.Log($"TEST GetAsync Result ({  ( r_getAsync.objectId == OBJECT_ID ? "correct" : "incorrect")}): " + r_getAsync.objectId, this);
    Debug.Log($"TEST FirstAsync Result ({(          r.objectId == OBJECT_ID ? "correct" : "incorrect")}): " + r.objectId, this);
    Debug.Log($"TEST FindAsync Result ({ (v_findAsync.objectId == OBJECT_ID ? "correct" : "incorrect")}): " + v_findAsync.objectId, this);
}

Results:

TEST GetAsync Result (incorrect): dYfuLGXWXZug6zQZDKUbTNJP

TEST FirstAsync Result (correct): TuNotA2E4qZkyhWMIaBonDWf

TEST FindAsync Result (correct): TuNotA2E4qZkyhWMIaBonDWf

GetAsync

Provided as reference

public Task<T> GetAsync(string objectId) => GetAsync(objectId, CancellationToken.None);
public Task<T> GetAsync(string objectId, CancellationToken cancellationToken)
{
    MoralisQuery<T> singleItemQuery = new MoralisQuery<T>(QueryService, InstallationService, ServerConnectionData, JsonSerializer, SessionToken, ClassName).WhereEqualTo(nameof(objectId), objectId);
    singleItemQuery = new MoralisQuery<T>(singleItemQuery, includes: Includes, selectedKeys: KeySelections, limit: 1);
    return singleItemQuery.FindAsync(cancellationToken).OnSuccess(t => t.Result.FirstOrDefault() ?? throw new MoralisFailureException(MoralisFailureException.ErrorCode.ObjectNotFound, "Object with the given objectId not found."));
}

Please release this as a UPM-compatible package

Reference: https://forum.moralis.io/t/ethereum-unity3d-boilerplate-questions/4553/307?u=vivraan

This is a request to consider making this a UPM package, which makes updates and dependencies more streamlined, instead of having copies of dependencies which may not be desirable, such as TextMeshPro.

The following is a weak argument: I already maintain my project code as defined with separate Assembly Definition files, which makes working with this package painful since I have to set it up manually each time I want to use it. I've also created a project which contains this project's contents in a UPM compatible package which I use in multiple projects, making it easy to manage.

URP Issue

MainMenuScript not loading in project using URP.

Moralis Object DeleteAsync not Implemented

Currently the DeleteAsync method is not exposed as a direct method of the base MoralisObject object.

Expose the method:

ServiceHub.ObjectService.DeleteAsync([OBJECT], [SESSION_TOKEN])

as

MoralisObject.DeleteAsync()

This will allow user to call await myObjectInstance.DeleteAsync() directly to delete a single instance.

Speedy Nodes

Another question, sir, I don't know. How can I set “SPeedy Nodes” in the unity template? Can you teach me?

Big Problem

public Object CallApi(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, String[] authSettings)

Like this... ,Why use synchronous call Web3 API,When I have a lot of NFT assets, they will jam the whole unity page. block

Moralis User and Moralis Object both have a session token property

The MoralisUser object and the MoralisObject object both have a property for Session Token but different spellings.

While both are populated properly when user is authenticated or re-created from server data, local storage retrieval of User object does not re-populate the the base.SesssionToken property. This causes any commands (such as cloud function calls) to send an empty SessionToken which can cause backend process to fail on validation.

SessionToken should be a property the base MoralisObject object.

HttpUtility does not exist in current context

Hi

The demo scene seems to run perfectly in it's own project. I have imported the Oculus plugin asset along with BNG framework for some VR stuff, and I am constantly getting the error "Assets\MoralisWeb3ApiSdk\Moralis\Moralis.Web3Api\Client\ApiClient.cs(120,20): error CS0103: The name 'HttpUtility' does not exist in the current context".

The specific line Unity seems to be taking issue with, is the return statement in this method

    public string EscapeString(string str)
    {
        return HttpUtility.UrlEncode(str); 
        //return RestSharp.Contrib.HttpUtility.UrlEncode(str);
    }

I'm not entirely sure how fragile this method is, so I replaced the return statement with return System.Uri.EscapeDataString(str)

This removed the error, but seems to break the code, as after going through authentication now my wallet address does no show up in the game scene.

What can I do to get this working? Thanks

WebSocket Conflicts

In the MoralisClientWebSocket script, there are references to WebSocket. This can collide with other classes named the same. In my case I also use Photon which has its own implementation of WebSocket. To resolve I just directly defined the namespace in the script.

    public class MoralisClientWebSocket : IClientWebSocket
    {
        private Moralis.Network.Client.WebSocket webSocket = null;
        public object Mutex = '\0';
        public Queue<byte[]> MessageQueue;

        public MoralisClientWebSocket(string uri, Dictionary<string, string> headers = null)
        {
            webSocket = new Moralis.Network.Client.WebSocket(uri, headers);
            MessageQueue = new Queue<byte[]>();
            webSocket.OnMessage += OnReceiveMessage;
        }

This also occurs in the WalletConnectSharp NativeWebSocketTransport script. The solution was the same.

    public class NativeWebSocketTransport : MonoBehaviour, ITransport
    {
        private bool opened = false;
        private bool closed = false;

        private NativeWebSocket.WebSocket nextClient;
        private NativeWebSocket.WebSocket client;

I got the message "The associated script can not be loaded..." when I clicked MoralisSetup of DemoScene. -> resolved

I imported the package moralisweb3sdk_v1_0_6.unitypackage and followed the tutorial but met the error below when I clicked MoralisSetup of DemoScene :
"The associated script can not be loaded. Please fix any complie errors and open Prefab Mode and assign a valid script to the Prefab Asset."
I use the Unity 2021.2.11f1 and Visual Studio for Mac[8.10.10].
How can I fix this issue? Please help me!

Moralis Web3Api (non WebGl) API Clients are not Asynchronous.

Currently the non-Web3GL Web3Api clients are synchronous which causes calls to block. These should be updated to be asynchronous as was done to the WebGL version of Web3Api.
Update the Web3Api generator application so that when generated, the Web3Api Clients are asynchronous.

Unusable data found

Hi, I'm fairly new to game dev let alone crypto.
I'm trying to add this feature in a school project (nft game) .
First i'm testing this feature however as soon as I scan the QR code, it says, no usable data found.
AM I missing a step or is this how it is supposed to be ?

Thank you,

Unsafe Code error

Assets\MoralisWeb3ApiSdk\Nethereum\Nethereum.Signer\Crypto\ECKey.cs(217,27): error CS0227: Unsafe code may only appear if compiling with /unsafe. Enable "Allow 'unsafe' code" in Player Settings to fix this error.

The error above is displayed when I imported the package. Should I allow unsafe code, or there is an alternative for this.

Error on quit

Hi, reporting an error after exit, this is log

Repro

  1. Play in Editor
  2. Press Authenticate. :Scan QR Code to Connect shows up
  3. Stop Play.
PLAY
UnityEngine.Debug:Log (object)
MainMenuScript/<Play>d__10:MoveNext () (at Assets/MoralisWeb3ApiSdk/Example/Scripts/MainMenuScript.cs:119)
System.Runtime.CompilerServices.AsyncVoidMethodBuilder:Start<MainMenuScript/<Play>d__10> (MainMenuScript/<Play>d__10&)
MainMenuScript:Play ()
UnityEngine.EventSystems.EventSystem:Update () (at Library/PackageCache/[email protected]/Runtime/EventSystem/EventSystem.cs:501)

User is not logged in.
UnityEngine.Debug:Log (object)
MainMenuScript/<Play>d__10:MoveNext () (at Assets/MoralisWeb3ApiSdk/Example/Scripts/MainMenuScript.cs:134)
System.Runtime.CompilerServices.AsyncVoidMethodBuilder:Start<MainMenuScript/<Play>d__10> (MainMenuScript/<Play>d__10&)
MainMenuScript:Play ()
UnityEngine.EventSystems.EventSystem:Update () (at Library/PackageCache/[email protected]/Runtime/EventSystem/EventSystem.cs:501)

MissingReferenceException: The object of type 'PlayerController' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
PlayerController.Move () (at Assets/MoralisWeb3ApiSdk/Example/Scripts/PlayerController.cs:126)
PlayerController.Update () (at Assets/MoralisWeb3ApiSdk/Example/Scripts/PlayerController.cs:90)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) (at <7b935204f5ff4bcab44b3b0ebca330bf>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <ab7de6937a4448b0a6ccd59e9820599a>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <ab7de6937a4448b0a6ccd59e9820599a>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <ab7de6937a4448b0a6ccd59e9820599a>:0)

Scene object references to scripts are missing

In Unity IDE, Visual Studio must be setup as script editor prior to importing the Moralis Web3API SDK Package.

Steps to Re-Create:

  1. Open a new copy of Unity3D
  2. Import Moralis Web3Api SDK Package
  3. Note that scene object references to scripts are missing.

Solution

Add a step to the setup instructions in README that instruct the user to setup Unity so that Visual Studio is the script editor.
Preferences->External Tools "Script Editor"

iOS: Choose Wallet Screen script Missing Reference

Platform: iOS only
Release: v1.0.0

Steps to Re-produce:

  1. Switch platform to iOS and build
  2. An error is returned that indicates missing reference.

Solution:
Related to W.C. upgrade, re-add the Wallet List to Wallet Connect code.

Short term - comment out the conditional block with the error.

WebGL Error with Unity 2021.2.11f1

Build Benchmark.loader.js:70 exception thrown: RuntimeError: unreachable,RuntimeError: unreachable at il2cpp::vm::Exception::Raise(Il2CppException*, MethodInfo*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[2270]:0x19ef03) at il2cpp_codegen_raise_exception(Exception_t*, MethodInfo*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[2594]:0x1aaebd) at Uri_CreateThis_m522F36D576D9A8803410439127DB32837331BA3A (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[82415]:0x13afe26) at Uri__ctor_m6CA436E6AD2768A121FA851CBEEFA3623E849D3A (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[82414]:0x13afceb) at Conversion_WebUriToWsURi_m6E98DF69EF4EEAA7C671669EC7244C4F69382183 (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[82794]:0x13ccd62) at MoralisService_1__ctor_m7835197D0FC3D5BF182DDA6E92858756AEFA92D7_gshared (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[20616]:0x5959f8) at MoralisService_1__ctor_m050DC98E983E8ACF0E5E6037366A2A83CEA9AD1F_gshared (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[20615]:0x595781) at MoralisClient__ctor_m4F0AA3563928C5F865FF7BB73533F25112610E36 (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[82784]:0x13cc7d5) at dynCall_viiiiii (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[190123]:0x2f8a3d0) at http://localhost:1090/Build/Build%20Benchmark.framework.js:1055:20 at invoke_viiiiii (http://localhost:1090/Build/Build%20Benchmark.framework.js:16797:3) at U3CInitializeU3Ed__14_MoveNext_mA551FD18F0C30BDE69A595A37BB0A47C8B924FD7 (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[57490]:0xe57391) at InterfaceActionInvoker0::Invoke(unsigned short, Il2CppClass*, Il2CppObject*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[128461]:0x1c51c03) at AsyncUniTaskMethodBuilder_Start_TisU3CTransferAsyncU3Ed__44_tE1EC3CFE689D715ACB9A03FE16F97FBCC9B889EE_m60A6D5A843E971E0DDD4DB1AD4FC23F49BA8BD45_inline(AsyncUniTaskMethodBuilder_t490751EC621C472E098B12103AF16BC549912BB0*, U3CTransferAsyncU3Ed__44_tE1EC3CFE689D715ACB9A03FE16F97FBCC9B889EE**, MethodInfo const*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[8200]:0x2e3743) at MoralisInterface_Initialize_m9A5ACBCB2BA5E9377CE02A3C14F575E6BA831958 (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[57469]:0xe5585a) at dynCall_viiiiiiii (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[190157]:0x2f8a636) at http://localhost:1090/Build/Build%20Benchmark.framework.js:1055:20 at invoke_viiiiiiii (http://localhost:1090/Build/Build%20Benchmark.framework.js:16973:3) at U3CInitializeU3Ed__9_MoveNext_m08C7C710BEE6AE7FB39A68C28DDF4F16902C3577 (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[57468]:0xe55386) at InterfaceActionInvoker0::Invoke(unsigned short, Il2CppClass*, Il2CppObject*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[128461]:0x1c51c03) at AsyncUniTaskMethodBuilder_Start_TisU3CTransferAsyncU3Ed__44_tE1EC3CFE689D715ACB9A03FE16F97FBCC9B889EE_m60A6D5A843E971E0DDD4DB1AD4FC23F49BA8BD45_inline(AsyncUniTaskMethodBuilder_t490751EC621C472E098B12103AF16BC549912BB0*, U3CTransferAsyncU3Ed__44_tE1EC3CFE689D715ACB9A03FE16F97FBCC9B889EE**, MethodInfo const*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[8200]:0x2e3743) at MoralisController_Initialize_mE34C1576D8FF0EE694FA8A20A8D58EF90FC557CF (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[57467]:0xe550a9) at dynCall_viii (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[190126]:0x2f8a400) at http://localhost:1090/Build/Build%20Benchmark.framework.js:1055:20 at invoke_viii (http://localhost:1090/Build/Build%20Benchmark.framework.js:16665:3) at U3CStartU3Ed__9_MoveNext_m1C1D7CB4810F671C1D26959815F9108AE2148AEB (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[59333]:0xeceda6) at InterfaceActionInvoker0::Invoke(unsigned short, Il2CppClass*, Il2CppObject*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[128461]:0x1c51c03) at dynCall_viii (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[190126]:0x2f8a400) at http://localhost:1090/Build/Build%20Benchmark.framework.js:1055:20 at invoke_viii (http://localhost:1090/Build/Build%20Benchmark.framework.js:16665:3) at AsyncVoidMethodBuilder_Start_TisRuntimeObject_m3CA145CBB6CFE8B4ADD6148BF98E85899F95DCEA_gshared (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[74678]:0x11f2edf) at AsyncVoidMethodBuilder_Start_TisU3CCompleteOpenU3Ed__24_t4E8DD01DC9B1058D072BBAC6EAD09F2B9E8A0DC3_m7E5D77D3538F885CD11D731DBCC76C02EB14CAF4(AsyncVoidMethodBuilder_t253E37B63E7E7B504878AE6563347C147F98EF2D*, U3CCompleteOpenU3Ed__24_t4E8DD01DC9B1058D072BBAC6EAD09F2B9E8A0DC3**, MethodInfo const*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[10628]:0x34ef41) at MainMenuScript_Start_mC1D05E15D183A59D0A7AB8AB22E0AA1BBFD1F78F (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[59322]:0xece292) at RuntimeInvoker_TrueVoid_t4861ACF8F4594C3437BB48B6E56783494B843915(void (*)(), MethodInfo const*, void*, void**, void*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[166028]:0x243412d) at il2cpp::vm::Runtime::InvokeWithThrow(MethodInfo const*, void*, void**) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[169479]:0x247c720) at dynCall_iiii (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[190119]:0x2f8a39a) at http://localhost:1090/Build/Build%20Benchmark.framework.js:1055:20 at invoke_iiii (http://localhost:1090/Build/Build%20Benchmark.framework.js:16687:10) at il2cpp::vm::Runtime::Invoke(MethodInfo const*, void*, void**, Il2CppException**) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[169451]:0x247bad1) at il2cpp_runtime_invoke (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[169528]:0x247def6) at ScriptingInvocation::Invoke(ScriptingExceptionPtr*, bool) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[187249]:0x2ea4743) at MonoBehaviour::InvokeMethodOrCoroutineChecked(ScriptingMethodPtr, ScriptingObjectPtr) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[187188]:0x2e9f4da) at MonoBehaviour::DelayedStartCall(Object*, void*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[187202]:0x2ea0c24) at DelayedCallManager::Update(int) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[172355]:0x2522cbb) at InitPlayerLoopCallbacks()::EarlyUpdateScriptRunDelayedStartupFrameRegistrator::Forward() (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[186945]:0x2e7baef) at ExecutePlayerLoop(NativePlayerLoopSystem*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[172192]:0x251304c) at ExecutePlayerLoop(NativePlayerLoopSystem*) (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[172192]:0x25130e8) at MainLoop() (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[184761]:0x2d2fbf9) at dynCall_v (http://localhost:1090/Build/Build%20Benchmark.wasm:wasm-function[190115]:0x2f8a35f) at http://localhost:1090/Build/Build%20Benchmark.framework.js:1055:20 printErr @ Build Benchmark.loader.js:70

Uncaught RuntimeError: unreachable at il2cpp::vm::Exception::Raise(Il2CppException*, MethodInfo*) (:1090/Build/Build%20Benchmark.wasm) at il2cpp_codegen_raise_exception(Exception_t*, MethodInfo*) (:1090/Build/Build%20Benchmark.wasm) at Uri_CreateThis_m522F36D576D9A8803410439127DB32837331BA3A (:1090/Build/Build%20Benchmark.wasm) at Uri__ctor_m6CA436E6AD2768A121FA851CBEEFA3623E849D3A (:1090/Build/Build%20Benchmark.wasm) at Conversion_WebUriToWsURi_m6E98DF69EF4EEAA7C671669EC7244C4F69382183 (:1090/Build/Build%20Benchmark.wasm) at MoralisService_1__ctor_m7835197D0FC3D5BF182DDA6E92858756AEFA92D7_gshared (:1090/Build/Build%20Benchmark.wasm) at MoralisService_1__ctor_m050DC98E983E8ACF0E5E6037366A2A83CEA9AD1F_gshared (:1090/Build/Build%20Benchmark.wasm) at MoralisClient__ctor_m4F0AA3563928C5F865FF7BB73533F25112610E36 (:1090/Build/Build%20Benchmark.wasm) at dynCall_viiiiii (:1090/Build/Build%20Benchmark.wasm) at :1090/Build/Build%20Benchmark.framework.js:1055:20 at invoke_viiiiii (:1090/Build/Build%20Benchmark.framework.js:16797:3) at U3CInitializeU3Ed__14_MoveNext_mA551FD18F0C30BDE69A595A37BB0A47C8B924FD7 (:1090/Build/Build%20Benchmark.wasm) at InterfaceActionInvoker0::Invoke(unsigned short, Il2CppClass*, Il2CppObject*) (:1090/Build/Build%20Benchmark.wasm) at AsyncUniTaskMethodBuilder_Start_TisU3CTransferAsyncU3Ed__44_tE1EC3CFE689D715ACB9A03FE16F97FBCC9B889EE_m60A6D5A843E971E0DDD4DB1AD4FC23F49BA8BD45_inline(AsyncUniTaskMethodBuilder_t490751EC621C472E098B12103AF16BC549912BB0*, U3CTransferAsyncU3Ed__44_tE1EC3CFE689D715ACB9A03FE16F97FBCC9B889EE**, MethodInfo const*) (:1090/Build/Build%20Benchmark.wasm) at MoralisInterface_Initialize_m9A5ACBCB2BA5E9377CE02A3C14F575E6BA831958 (:1090/Build/Build%20Benchmark.wasm) at dynCall_viiiiiiii (:1090/Build/Build%20Benchmark.wasm) at :1090/Build/Build%20Benchmark.framework.js:1055:20 at invoke_viiiiiiii (:1090/Build/Build%20Benchmark.framework.js:16973:3) at U3CInitializeU3Ed__9_MoveNext_m08C7C710BEE6AE7FB39A68C28DDF4F16902C3577 (:1090/Build/Build%20Benchmark.wasm) at InterfaceActionInvoker0::Invoke(unsigned short, Il2CppClass*, Il2CppObject*) (:1090/Build/Build%20Benchmark.wasm) at AsyncUniTaskMethodBuilder_Start_TisU3CTransferAsyncU3Ed__44_tE1EC3CFE689D715ACB9A03FE16F97FBCC9B889EE_m60A6D5A843E971E0DDD4DB1AD4FC23F49BA8BD45_inline(AsyncUniTaskMethodBuilder_t490751EC621C472E098B12103AF16BC549912BB0*, U3CTransferAsyncU3Ed__44_tE1EC3CFE689D715ACB9A03FE16F97FBCC9B889EE**, MethodInfo const*) (:1090/Build/Build%20Benchmark.wasm) at MoralisController_Initialize_mE34C1576D8FF0EE694FA8A20A8D58EF90FC557CF (:1090/Build/Build%20Benchmark.wasm) at dynCall_viii (:1090/Build/Build%20Benchmark.wasm) at :1090/Build/Build%20Benchmark.framework.js:1055:20 at invoke_viii (:1090/Build/Build%20Benchmark.framework.js:16665:3) at U3CStartU3Ed__9_MoveNext_m1C1D7CB4810F671C1D26959815F9108AE2148AEB (:1090/Build/Build%20Benchmark.wasm) at InterfaceActionInvoker0::Invoke(unsigned short, Il2CppClass*, Il2CppObject*) (:1090/Build/Build%20Benchmark.wasm) at dynCall_viii (:1090/Build/Build%20Benchmark.wasm) at :1090/Build/Build%20Benchmark.framework.js:1055:20 at invoke_viii (:1090/Build/Build%20Benchmark.framework.js:16665:3) at AsyncVoidMethodBuilder_Start_TisRuntimeObject_m3CA145CBB6CFE8B4ADD6148BF98E85899F95DCEA_gshared (:1090/Build/Build%20Benchmark.wasm) at AsyncVoidMethodBuilder_Start_TisU3CCompleteOpenU3Ed__24_t4E8DD01DC9B1058D072BBAC6EAD09F2B9E8A0DC3_m7E5D77D3538F885CD11D731DBCC76C02EB14CAF4(AsyncVoidMethodBuilder_t253E37B63E7E7B504878AE6563347C147F98EF2D*, U3CCompleteOpenU3Ed__24_t4E8DD01DC9B1058D072BBAC6EAD09F2B9E8A0DC3**, MethodInfo const*) (:1090/Build/Build%20Benchmark.wasm) at MainMenuScript_Start_mC1D05E15D183A59D0A7AB8AB22E0AA1BBFD1F78F (:1090/Build/Build%20Benchmark.wasm) at RuntimeInvoker_TrueVoid_t4861ACF8F4594C3437BB48B6E56783494B843915(void (*)(), MethodInfo const*, void*, void**, void*) (:1090/Build/Build%20Benchmark.wasm) at il2cpp::vm::Runtime::InvokeWithThrow(MethodInfo const*, void*, void**) (:1090/Build/Build%20Benchmark.wasm) at dynCall_iiii (:1090/Build/Build%20Benchmark.wasm) at :1090/Build/Build%20Benchmark.framework.js:1055:20 at invoke_iiii (:1090/Build/Build%20Benchmark.framework.js:16687:10) at il2cpp::vm::Runtime::Invoke(MethodInfo const*, void*, void**, Il2CppException**) (:1090/Build/Build%20Benchmark.wasm) at il2cpp_runtime_invoke (:1090/Build/Build%20Benchmark.wasm) at ScriptingInvocation::Invoke(ScriptingExceptionPtr*, bool) (:1090/Build/Build%20Benchmark.wasm) at MonoBehaviour::InvokeMethodOrCoroutineChecked(ScriptingMethodPtr, ScriptingObjectPtr) (:1090/Build/Build%20Benchmark.wasm) at MonoBehaviour::DelayedStartCall(Object*, void*) (:1090/Build/Build%20Benchmark.wasm) at DelayedCallManager::Update(int) (:1090/Build/Build%20Benchmark.wasm) at InitPlayerLoopCallbacks()::EarlyUpdateScriptRunDelayedStartupFrameRegistrator::Forward() (:1090/Build/Build%20Benchmark.wasm) at ExecutePlayerLoop(NativePlayerLoopSystem*) (:1090/Build/Build%20Benchmark.wasm) at ExecutePlayerLoop(NativePlayerLoopSystem*) (:1090/Build/Build%20Benchmark.wasm) at MainLoop() (:1090/Build/Build%20Benchmark.wasm) at dynCall_v (:1090/Build/Build%20Benchmark.wasm) at :1090/Build/Build%20Benchmark.framework.js:1055:20

`An abnormal situation has occurred: the PlayerLoop internal function has been called recursively. Please contact Customer Support with a sample project so that we can reproduce the problem and troubleshoot it.`

Unity3d v2021.2.5 WebGL Fails on Build

Reported by a user. Runs in the IDE but during build fails. Error is not clear. A Search shows that a lot of people have run into this same issue. Several solutions offered.

I was able to reproduce on a MAC. None of the solutions I found online solved the issue. Further research is needed.

image

Nethereum Package -> unsafe code

Unity version: Unity 2021 (latest)
Release of ethereum-unity-boilerplate: 1.0.4

Error: Around 11 unsafe code errors:
Assets/MoralisWeb3ApiSdk/Nethereum/Nethereum.KeyStore/Crypto/SCrypt.cs(290,36): error CS0227: Unsafe code may only appear if compiling with /unsafe. Enable "Allow 'unsafe' code" in Player Settings to fix this error.

This can be fixed by going into "Player Settings" and allowing "unsafe code", however I didn't notice this on previous releases and this is not a good solution for a production environment.

ACL is always set to "Master Key Only"

Every time I created a Class, the ACL was always set to "Master Key Only". Even after making sure that my ACL is set to PublicReadAccess and PublicWriteAccess to true, it was always set to "Master Key Only".

MoralisAcl acl = new MoralisAcl()
{
PublicReadAccess = true,
PublicWriteAccess = true
};
room.ACL = acl;
try
{
await room.SaveAsync();
}
catch(Exception e)
{
Debug.Log("Cannot Save Room to database " + e);
}

image

Wallet connection error

Editor: 2020.3.24f1
sdk: v1_0_5

Whenever I use wallet connect(metamask or trust wallet) I get:
UriFormatException: invalid URI: the format ot the URI could not be determined.

Controllerno

image

Though when I double click, it open in VS Code

image

Create Object Does Not Set ClassName

The MoralisInterface is calling the default Create for create object which does not set the class name.

since the class name is empty, the call to save fails at the server.

Update MoralisObject so that MoralisObject defaults are set in the default namespace so that some defaults are always set instead of relying on the Create method to do this.

UserServiceExtensions : Object reference not set to an instance of an object

Hi there, thanks for the amazing work!
I am having an issue when I try to authenticate with the QR code:
When I use Trust Wallet or Iam Token to capture the QR, it sends the request correctly, then receive back the confimation message inside the wallet.
However when accepting the request, the loggin fails, and this shows in Unity's consol, related to UserServiceExtensions.cs :

NullReferenceException: Object reference not set to an instance of an object
Moralis.Platform.Services.ClientServices.UserServiceExtensions+<>c__DisplayClass18_01[TUser].<LogInWithAsync>b__0 (System.Threading.Tasks.Task1[TResult] task) (at Assets/MoralisWeb3ApiSdk/Moralis/MoralisDotNet/Platform/Services/ClientServices/UserServiceExtensions.cs:191)
Moralis.Platform.Utilities.InternalExtensions+<>c__DisplayClass5_02[TIn,TResult].<OnSuccess>b__0 (System.Threading.Tasks.Task t) (at Assets/MoralisWeb3ApiSdk/Moralis/MoralisDotNet/Platform/Utilities/InternalExtensions.cs:45) Moralis.Platform.Utilities.InternalExtensions+<>c__DisplayClass7_01[TResult].b__0 (System.Threading.Tasks.Task t) (at Assets/MoralisWeb3ApiSdk/Moralis/MoralisDotNet/Platform/Utilities/InternalExtensions.cs:72)
System.Threading.Tasks.ContinuationResultTaskFromTask1[TResult].InnerInvoke () (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Threading.Tasks.Task.Execute () (at <695d1cc93cca45069c528c15c9fdd749>:0) --- End of stack trace from previous location where exception was thrown --- System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0) Moralis.Platform.Utilities.InternalExtensions+<>c__DisplayClass7_01[TResult].b__0 (System.Threading.Tasks.Task t) (at Assets/MoralisWeb3ApiSdk/Moralis/MoralisDotNet/Platform/Utilities/InternalExtensions.cs:59)
System.Threading.Tasks.ContinuationResultTaskFromTask1[TResult].InnerInvoke () (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Threading.Tasks.Task.Execute () (at <695d1cc93cca45069c528c15c9fdd749>:0) --- End of stack trace from previous location where exception was thrown --- System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter1[TResult].GetResult () (at <695d1cc93cca45069c528c15c9fdd749>:0)
MainMenuScript+d__11.MoveNext () (at Assets/MoralisWeb3ApiSdk/Example/Scripts/MainMenuScript.cs:199)
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_0 (System.Object state) (at <695d1cc93cca45069c528c15c9fdd749>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at /Users/bokken/buildslave/unity/build/Runtime/Export/Scripting/UnitySynchronizationContext.cs:153)
UnityEngine.UnitySynchronizationContext:ExecuteTasks() (at /Users/bokken/buildslave/unity/build/Runtime/Export/Scripting/UnitySynchronizationContext.cs:107)

What am I missing ?

thanks !

Updating Version Control in Package Manager causes errors

I recently updated the Version Control package from the Unity Registry in the Package Manager to the latest version (1.15.12) which caused a bunch of errors along the lines of

Assets\MoralisWeb3ApiSdk\Moralis\MobileLogin.cs(29,7): error CS0246: The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)

Reverting the Version Control package back to 1.15.7 removes these errors. I gathered the following from the changelog for the Version Control package:

  • Fixed Newtonsoft.Json.dll conflicts with other external packages

I believe this could be the source of the errors when updating to the newest Version Control package.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.