Ethereum Unity3D Boilerplate Questions

@dgoodrich Iā€™m working on a repo of academic examples showcasing the latest MoralisSDK. In the interest of limited time, I may choose not to cover EVERY topic.

Iā€™m prioritizing showing off the ā€œFundamentalsā€ plus ā€œWhat is the coolest!ā€. :slight_smile:

Iā€™d like your adviceā€¦

  1. Iā€™ve covered the blue-checks here per #1 + storage. Of the categories of #2 - #7, how would you prioritize the importance of each? (Fictional example; 2 is most important then 7 then 3, 4, 5,ā€¦)
  2. Below each of the categories #2 - #7 which (one?) subcategory is the most important? (Fictional example; under #3, GetNFT is most important, under #4 GetPairReserves is the most important).
  3. Are there important things missing from the pic that are suggested priorities? For example, Nethereum ( I donā€™t know what that is yet. Still learning :slight_smile: )
  4. I remember doing the non-unity demo of Moralis and there was a demo of making a contract, putting it on the server, and calling it. Which item in the pic is related to doing that? Pardon my noob-ness :slight_smile:

Maybe there are not easy answers to my questions, thatā€™s ok. Your answers will help will point me in the right direction anywaysā€¦

1 Like

I think what you are doing is very cool. If you have a press release, etc. with links to your courses I would like to post it in our internal forum for the team to see.

I tried to answer your questions, beware, there is a lot expressed here that is opinion :slight_smile:

For Web3Api, Once you know how to use one, you can use them all. #2 Chains is an enum and is used by many of the other calls. I think that #3 Account and #7 Token have the most utility in games. This is a personal opinion and will highly depend on the goals of the game.

From the view point of games, and again this is opinion,
#3 The first three operations could have use in most NFT based games.
#4 I see almost no use for this endpoint in most games. An exception would be a trading game, a long term race to see who can make the best trades, etc. Another exception would be games creatd to teach Defi, similar to my previous examples.
#5 The last two could have some use in gaming depending on the goals of the game. I do not personally see much gaming use for the other operation sin this endpoint.
#6 Could possibly be used, I am not sure but possibly to make it easy for someone to transfer an asset to another account. This would allow the user to enter an address like xactant.crypto instead of the hex address.
#7 I can see that many / most of the operations in this endpoint could be used to enhance token / NFT use in a game.

I put these two together for the simple reason that to create a contract from the game would require Nethereum. Nethereum is the best known (and as far I know) the most reliable .NET Ethereum RPC wrapper currently available. If you have looked at running an Ethereum node, RPC commands are what you use to control and communicate with a node. Nodes (such as the Moralis Speedy Nodes) expose a public API for RPC command calls. This is what wallets use to communicate to a node.

You can use Nethereum to make any RPC supported call to an Ethereum Node.

My opinion and recommendation is to use it only for making calls that write to the chain, what I refer to as state change calls. Most communication with the chain is reading data. In the case of reads, the Moralis Web3Api is faster and more efficient than using Nethereum since it is against an indexed data set and allow data paging and block range searches. (I think Nethereum also supports block ranges searches but need to check that).

Hopefully this helps!

David

Creating a contract from a game is expensive in resources (gas, time, etc.). If someone is minting ERC721 NFTs, creating a contract on the fly could be argued for. Personnaly I like using ERC1155 NFT contracts as this standard was especially written to support using tokens and NFTs in games. For th updated 1.0.3 release I used an 1155 contract and a proxy contract. I minted the demo NFT set via the proxy making the proxy the owner of all (it also enforces the rules of distribution). Since the NFTs are pre-minited the only cost to the user for claiming an NFT is the gas for transfer - on Polygon this is tenths of a cent. Minting an ERC721 NFT for the same asset would cost each user a little of $1.00 on Polygon (on Ethereum Main-net this cost to mint an ERC721 is currently around $40-$50 or more)

1 Like

I cant get the unity boilerplate to run on the rinkeby testnet. I changed the chain ids to 4, Im not sure if theres anything else needed or if this is available to do yet? Please help

1 Like

Hi David, just seeing your message now. No I have not, where do I claim it? Hopefully itā€™s a Moralis Mage haha.

I came across one method for integrating into VR from a channel called FusedVR. Basically he was setting up a way where basically you prompted with a link to WalletConnect via email. So you would sign in via email. Could also work with MetaMask. It looked like a pretty cool way to interface from a headset.

1 Like

Yes
iā€™ll just keep checking github for update

1 Like

This is a non-issue with UPM. Just refer to the package depending on com.unity.textmeshpro and youā€™re golden.

1 Like

Hello, can you be more specific about what is happening with your application? The demo should run out of the box without a chain connection - as long as you authenticate with a wallet.

You would set the chain for Web3API calls and Web3 (Nethereum calls).

Please text copy (screen shot can cut off information) the exception you are receiving and I will take a look.

Regards,

David

Hi! you claim the mug by setting up an account in your wallet to the Polygon / Mumbai chain and use the Polygon faucet to get some test matic, download and run the demo. slay the orcs and bash the chest until it opens. The mug is inside. Click on it and immediately check your wallet. You should have a message asking permission to execute the transfer to your account.

@Ashu-specs, you can also do a search for ā€œUnity3D programmatically load prefabā€ and you will find several examples.

1 Like

Hello @dgoodrich, is there a way to authentificate an unique NFT in Unity ?
I understand that, its possible to read all the NFT of a wallet from Unity, but my question is how to notificate unity that a CERTAIN NFT is in the wallet of the user ?
Big thankā€™s !!

1 Like

I do this in the new demo (released late Friday).

If you know the contract and the TokenId of the NFT, yes you can. Here is the code from the demo (in the AwardableController.cs file):

            try
            {
#if UNITY_WEBGL
                NftOwnerCollection noc =
                    await MoralisInterface.GetClient().Web3Api.Account.GetNFTsForContract(addr.ToLower(),
                    AwardContractAddress,
                    ChainList.mumbai);
#else
                NftOwnerCollection noc =
                    MoralisInterface.GetClient().Web3Api.Account.GetNFTsForContract(addr.ToLower(),
                    AwardContractAddress,
                    ChainList.mumbai);
#endif
                IEnumerable<NftOwner> ownership = from n in noc.Result
                                                  where n.TokenId.Equals(NftTokenId.ToString())
                                                  select n;

                if (ownership != null && ownership.Count() > 0)
                {
                    isOwned = true;
                    // Hide the NFT Game object since it is already owned.
                    transform.gameObject.SetActive(false);
                }
            }
            catch (Exception exp)
            {
                Debug.LogError(exp.Message);
            }
        }

NOTE: After next release, the pre-processor switch here may not be necessary.

Regards,

David

I can connect to my wallet and authenticate just fine but it doesnt display my ETH in the modal dialog in unity. Im trying to connect using the rinkeby test network, it displays my address correctly but not my ETH balance or anything else related to my rinkeby testnet account.

1 Like

Make sure you are pre-setting or programmatically setting chain id in the Wallet Balance Controller This value default to eth Main net.
Here are the chain ids:

public enum ChainList
	{
		eth = 0x1,
		ropsten = 0x3,
		rinkeby = 0x4,
		goerli = 0x5,
		kovan = 0x2a,
		polygon = 0x89,
		mumbai = 0x13881,
		bsc = 0x38,
		bsc_testnet = 0x61,
		avalanche = 0xa86a,
		avalanche_testnet = 0xa869,
		fantom = 0xfa
	};

Hope this helps,

David

1 Like

Ahhh that did it! Thanks!

1 Like

Hi, will u going to release multiplayer webgl? tq

1 Like

Hi David,
Iā€™ve been trying to mint a token and have some questions / feedback:

  1. After I log in using wallet connect, for subsequent logins Moralis will say ā€œUser is already logged inā€. However, wallet connect will connect and call the callback (WalletConnectHandler) and create a signing request to log into moralisā€¦ I assume this is not necessary?

  2. I tried calling my mint function using:

         var cts = new CancellationTokenSource();
         var receipt = await myMintFunction.SendTransactionAndWaitForReceiptAsync(addr, cts, new object[] { });
            //Debug.Log($"Receipt: {receipt}");

But this doesnā€™t seem to workā€¦might be that metamask + walletconnect was just being wonky

  1. When I tried calling my mint function with:
          var receipt = await MoralisInterface.SendTransactionAndWaitForReceiptAsync(
                myContractKey, "polygon", "mint", addr, new HexBigInteger(0), new HexBigInteger(0), null);
            Debug.Log($"Receipt: {receipt}");

The transaction got to my metamask wallet, BUT:

  • It didnā€™t care that I was connected to the wrong network (mainnet instead of polygon)
  • When I rejected it, the code in SendTransactionAndWaitForReceiptAsync just prints out an errorā€¦ it should throw an exception as well so we can handle the error
  • Thereā€™s no API for using a cancellation token when using this method
  • When I switched my metamask wallet to use polygon, the gas estimation would not resolve - could be a problem with recent changes to Polygon / EIP 1559?
  1. The metamask-on-mobile-device flow is really slow! Itā€™s not the greatest user experience. I know that there isinā€™t really anything that can be done about that ( I think you are working on a alternate flow for WebGL builds that uses browser extension wallets?). I was thinking another possible alternative would be to use ā€œmanagedā€ wallets that could be generated for the user, since nethereum has that capability. (I think?)

Anyhow, just some feedback. I will keep trying to find fixes or workarounds for these issues!
Kind Regards

Update: I was able to get my mint transaction to go through after a bunch of attempts!

1 Like

I will probably release a demo at sometime. The current release has the tools you need for multiplayer games. Investigate Live Queries in the docs. Ivan also created a basic demo. Though his is in Javascript, the .NET SDK has the same functionality.

This is a factor of Wallet Connect - W.C. stores a session in the game
s user preferences. If you do not revoke the session it persists so that when you restart, even if you think you are not conencted to your wallet W.C. will try to re-establish. Take a look at the Quit() function the the MainMenuScript.cs file. This demos how to sign out of both Moralis and more importantly, W.C.

The first does not work for a writable call since it is not sending gas (or when needed value). The second does. See the example in the demo in the AwardableController.cs file. I supplied a function that wraps the function call but requires gas.

Not knowing which network the user is attached to is an issue that is universal. I need to re-examine the W.C. response to see if anything indicates which chain the wallet is connected to.
For the wrapped call (the second you made) I do return a tuple that indicates success and contains either the result or the error message. My personal preference is to bubble up exceptions but I received a lot of negative feedback about doing this elsewhere in the code. So, with the wrappers I have tried to include a success indicator with payload and msg.
The Function SendTransactionAndAwaitForReceiptAsync does have an override that accepts Cancellation token, I did not expose this in the wrapper. I will update the wrapper to expose this.

You may be right. I ran into the same issue. I originally wrote the demo to call Function.CalculateGas but it always failed - delayed release of the update over a day because of trying to get past this. Finally for sake of the demo I set gas manually. I will add some notes to the demo about how to do this properly.

I feel your pain and agree. One immediate alternative is to look at the MainMenuScrupt.cs file in the Play() method:

#if UNITY_ANDROID
            // By pass noraml Wallet Connect for now.
            androidMenu.SetActive(true);

            // Use Moralis Connect page for authentication as we work to make the Wallet 
            // Connect experience better.
            //await LoginViaConnectionPage();
#elif UNITY_IOS
            // By pass noraml Wallet Connect for now.
            iosMenu.SetActive(true);

            // Use Moralis Connect page for authentication as we work to make the Wallet 
            // Connect experience better.
            //await LoginViaConnectionPage();
#else

Comment out the Menu.SetActive line and uncomment the await LoginViaConnectionPage(); line. Instead of using the mobile W.C. code this will bring up the MoralisConnect webapp. It is faster - however you cannot use this method with Nethereum (We may change depending on W.C. ).

We had the conversation in house back in October about creating a managed Wallet but consensus was that it would limit users since they would need to transfer funds, paying gas and managing another wallet. Additionally the issues of securely maintaining private keys, across multiple platforms is daunting. Is it possible we will come back to this sometime in the future? Yes, but I do not know when.

Thank you for the feedback.

Regards,

David

Thanks much! Iā€™ll dig into this feedback soon.

1 Like

Hi !

I installed Metamask and I tried to authentificate myself with the QR code in the Unity demo.
For mumbai itā€™s working ! But when I change the RPC url to avalanche testnet network in MoralisSetup component, and switch my Wallet too, i canā€™t authentificate.

Do you have the same issue or itā€™s a problem on my side ?

Thanks a lot!!

1 Like