On this week’s Moralis Undertaking we’ll discover ways to work together with a Sensible Contract from Unity! Utilizing Moralis will make this tremendous quick and easy. ?
New Moralis Initiatives drop every Saturday, so be sure to hitch the Moralis Discord server with a view to participate within the challenges! Take part every week to construct a killer Web3 portfolio, and bag your self an unique builder’s NFT too.
Let’s get began!
First, we’ll take a common look by way of the venture so you’ll be able to see the large image, then dive into the specifics – deploying the sensible contract utilizing Hardhat, and calling a operate of that contract from Unity. We’ll additionally discover ways to hearken to the contract occasion in Unity.
Lastly, we’ll construct the venture for WebGL. Get pleasure from!
PRE-REQUISITES
GETTING STARTED
Clone the youtube-tutorials GitHub Repository:
git clone https://github.com/MoralisWeb3/youtube-tutorials.git
As soon as downloaded, navigate to the unity folder and also you’ll discover all of the unity tutorials. Open unity-web3-smart-contracts with Unity Hub, and also you’re able to go!
VIDEO STRUCTURE
Alright! Let’s summarize the video construction:
- First, we’re gonna arrange a Moralis Dapp and get the credentials we have to log into Web3
- Second, I’m gonna present you ways the venture is structured so you could have an excellent overview earlier than going into the particular options
- Then, utilizing Hardhat we’ll deploy the sensible contract which is able to include the “openGates” operate
- After that, we’ll discover ways to work together with the contract from Unity and hearken to the occasions
- Lastly, we’ll discover ways to construct the venture for WebGL
1. Setup Moralis Dapp
If you happen to open the Unity venture, the very first thing that you just’ll discover is the Moralis Web3 Setup panel:
First up, let’s comply with the directions under the enter fields. Go to https://admin.moralis.io/login and log in (join if you happen to’re not already registered), then click on on Create a brand new Server:
Subsequent, click on on Testnet Server.
Set your server title and your closest area. Now, select Polygon (Mumbai), as we’re going to be deploying the sensible contract to this chain. Lastly, click on on Add Occasion:
The server (Dapp) will now be created!
If you happen to click on on View Particulars, you’ll find the Server URL and the Utility ID. Copy the Server URL, then the Utility ID:
Now paste them to the Moralis Web3 Setup panel enter fields:
If you happen to shut the panel by chance, don’t panic. Yow will discover it within the high toolbar beneath Window → Moralis → Web3 Unity SDK → Open Web3 Setup.
Now hit Executed. Your Moralis Server is about up. Good!
Lastly, we have to add the server (Dapp) data: within the Belongings venture tab go to Moralis Web3 Unity SDK → Sources and choose MoralisServerSettings:
2. Undertaking construction overview
Begin off by heading to Belongings → _Project.
Right here, you’ll discover all of the belongings I created for this specific venture, together with the scripts and Foremost Scene. Go to the Foremost Scene (if you happen to’re not already there), and check out the Hierarchy:
As you’ll be able to see, we’re utilizing the brand new AuthenticationKit that’s now accessible due to my colleague Sam and the Moralis Unity SDK workforce (superb work guys!).
Yow will discover a particular scene displaying its performance beneath Samples → Moralis Web3 Unity SDK → Present model → AuthenticationKit:
The AuthenticationKit is a brilliant highly effective instrument. It may deal with the authentication on any platform that we select to construct on with Unity. Yow will discover out precisely the way it works by trying out Sam’s video:
For now, all it’s worthwhile to know is that the AuthenticationKit has some occasions you’ll be able to subscribe to. When it connects or disconnects, for instance, we’re going to execute this:
We’ll go deeper into this later, however as you’ll be able to see we’re principally calling GameManager capabilities. That is the principle script of this venture. It takes care of speaking with the sensible contract and prompts or deactivates these panels relying on the state.
For now, let’s hit Play and see if we will log in. Be sure to have the Mumbai Testnet chosen in your MetaMask cell, topped up with some take a look at Matic. You will get free Testnet MATIC tokens by following this information.
Click on on CONNECT, scan the QR code and try to be logged in:
3. Deploy Sensible Contract
Earlier than going deeper into the GameManager, let’s deploy the sensible contract that we’ll be interacting with.
Bear in mind, it’s worthwhile to have MetaMask put in in your browser too, with the Mumbai Testnet imported and with some take a look at MATIC in it. Right here’s the information on methods to get free testnet MATIC once more.
Subsequent, it’s worthwhile to be sure Node.js is put in earlier than persevering with:
https://nodejs.org/en/obtain/
Alright, now let’s get into it!
Create a folder in your desktop. I’m going to call mine “MoriaGates-Hardhat”, however you’ll be able to name it no matter you want. Open Visible Studio Code, then open the folder that we simply created:
Now we’re going to execute some hardhat instructions! Don’t fear, I’ve acquired some directions prepared so that you can make it simple.
Begin by going to Unity. Below _Project → SmartContract you’ll discover the directions, together with another recordsdata we’ll want later.
The INSTRUCTIONS.txt are there so that you can refer again to everytime you want. Let’s comply with them now.
Open the terminal in VS Code, and be sure you’re beneath the Moria-Hardhat folder. If not, you’ll be able to transfer to the specified folder by way of the cd command.
Now let’s set up hardhat by executing these two instructions, one after the opposite:
npm i -D hardhat
npx hardhat
When executing the second command, you’ll want to pick out Create a fundamental pattern venture and hit enter a number of instances:
Congrats, you’ve now put in Hardhat and created a fundamental pattern venture:
Nice! Now it’s time to put in the dependencies. Execute all these instructions one after one other:
npm i -D dotenv
npm i -D @nomiclabs/hardhat-etherscan
npm i -D @nomiclabs/hardhat-waffle
npm set up keccak256
As soon as the dependencies are put in, we have to substitute a few of the newly created recordsdata with the recordsdata from the Unity folder beneath Belongings → _Project → SmartContract.
Let’s begin by changing the Greeter.sol, which is the pattern sensible contract that comes with the essential Hardhat venture for the MoriaGates.sol.
You possibly can substitute the code from MoriaGates.sol to Greeter.sol after which rename it as MoriaGates.sol (or simply substitute the entire file). Below contracts, simply delete Greeter.sol and add the MoriaGates.sol file:
As you’ll be able to see, MoriaGates.sol has an occasion known as CorrectPassword, a bytes subject known as magicPassword and an proprietor deal with.
Within the constructor, we will see that after we deploy the contract, it would want a bytes32 parameter that shall be saved because the magicPassword and the proprietor would be the pockets that deploys it:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract MoriaGates {
occasion CorrectPassword(bool end result);
bytes32 personal _magicPassword;
deal with proprietor;
constructor(bytes32 magicPassword) {
_magicPassword = magicPassword;
proprietor = msg.sender;
}
Now let’s discover the OpenGates operate, which is the one we’ll name from Unity.
It wants a string parameter, and we’ll make it public with out requiring being an proprietor. It’s because we need to name this operate from our cell MetaMask pockets, which gained’t be the one deploying the contract. This additionally means it’s NOT a production-ready contract, so preserve that in thoughts!
Right here’s how we do it:
operate openGates(string reminiscence password) public {
//DISCLAIMER -- NOT PRODUCTION READY CONTRACT
//require(msg.sender == proprietor);
if (hash(password) == _magicPassword)
{
emit CorrectPassword(true);
}
else
{
emit CorrectPassword(false);
}
}
operate hash(string reminiscence stringValue) inner pure returns(bytes32) {
return keccak256(abi.encodePacked(stringValue));
}
}
Okay! This operate converts the string parameter that may come from Unity to a hash utilizing the hash operate and examine it to the magic password. We’ll then set off the CorrectPassword occasion passing a real or false worth relying on if the password is appropriate or not.
Now it’s time to interchange the sample-script.js beneath scripts for the deploy.js beneath the Unity folder beneath Belongings → _Project → SmartContract:
That is the script that we’ll execute by way of a command later to deploy the MoriaGates.sol contract, in order that’s precisely what it does. First, we’re hashing a string parameter that would be the magicPassword when the contract is constructed. On this case, I used “Mellon” which is the elvish phrase for “Pal”:
const hre = require("hardhat");
async operate important() {
const hashing = require('keccak256');
var hashedPassword = hashing('Mellon');
Then we deploy the contract passing this hashed password:
const MoriaGates = await hre.ethers.getContractFactory("MoriaGates");
const moriaGates = await MoriaGates.deploy(hashedPassword);
After that, we look ahead to the contract to be deployed so we will lastly confirm it, and see the entire code and occasions on PolygonScan:
await moriaGates.deployed();
console.log("Contract deal with: ", moriaGates.deal with);
console.log("Hashed password: ", hashedPassword);
await moriaGates.deployTransaction.wait(5);
// We confirm the contract
await hre.run("confirm:confirm", {
deal with: moriaGates.deal with,
constructorArguments: [
hashedPassword,
],
});
}
// We suggest this sample to have the ability to use async/await all over the place
// and correctly deal with errors.
important()
.then(() => course of.exit(0))
.catch((error) => {
console.error(error);
course of.exit(1);
});
Nice! Now it’s time to create a .env file, so we will fill it with some credentials that we have to deploy and confirm the contract. You can create the file, however for now, you’ll be able to simply copy it from the Unity folder Belongings → _Project → SmartContract. Copy it to the basis of MoriaGates-Hardhat:
We’ll begin by filling POLYGON_MUMBAI which must be the RPC Node URL of the Mumbai Testnet. Head to the Moralis Admin Panel (https://admin.moralis.io/servers), the place we created the server, then go to Speedy Nodes → Polygon Community Endpoints and duplicate the Mumbai one:
Paste it on POLYGON_MUMBAI beneath .env and it ought to appear like this:
Subsequent, let’s enter the API_KEY.
This must be the PolygonScan API key, so go to PolygonScan and create an account if you happen to don’t have one. Then, beneath “YourAccountName” → API Keys you’ll be able to create the API Key you want.
When you’ve acquired the API Key, copy it to the .env file:
Lastly, we have to add the PRIVATE_KEY, which is the personal key of your browser MetaMask pockets.
REMEMBER: By no means give your personal key to anyone!!
Try this weblog on methods to get your personal key. Upon getting it, paste it into the .env file:
Alright! The very last thing we have to do earlier than deploying the contract is to interchange the hardhat.config.js file with the one beneath our Unity folder. Do this, and also you’ll see it within the module.exports part we use the fields that we simply crammed on the .env file:
Now it’s time to deploy the contract! We simply must run these instructions one after one other:
npm hardhat clear
npm hardhat compile
npx hardhat run scripts/deploy.js –community mumbai
And voilà! After a minute or so, we’ve got our MoriaGates.sol contract deployed and verified! If we copy the contract deal with that seems as a log within the terminal and paste it on PolygonScan we should always see the contract there:
4. Unity & Sensible Contract interplay
As talked about earlier, GameManager.cs is the principle script on this venture.
It takes care of the interplay with the contract. Open it, and also you’ll see that it wants the contract deal with and the contract ABI, so let’s add that in:
Take the deployed contract deal with and paste it beneath ContractAddress. For the ContractAbi, go to PolygonScan, seek for your contract deal with and beneath Contract → Code you will see that the ABI, which seems like this:
Now, earlier than pasting the worth in GameManager.cs, we have to format it.
Head to https://jsonformatter.org/. Paste the ABI on the left aspect, then click on on Minify/Compact:
Subsequent, click on on the correct aspect, press Ctrl + F and sort “
We have to substitute “ for ”
Click on on All to interchange it in all of the textual content:
Okay, now copy the formatted ABI, return to GameManager.cs, and paste it into ContractAbi:
Nice job!
Earlier than persevering with with the GameManager, we have to arrange one thing essential within the Moralis Admin Panel, which is listening in to the CorrectPassword occasion of the contract.
Go to the Admin Panel → View Particulars → Sync → Add New Sync → Sync and Watch Contract Occasions
Right here’s a full information on methods to sync and index sensible contract occasions, however principally these are the values it’s worthwhile to fill in for our contract:
- ChainId → Choose Mumbai
- Description → Any description you need
- Sync_historical → False
- Matter → CorrectPassword(bool)
- Abi → {“nameless”:false,”inputs”:[{“indexed”:false,”internalType”:”bool”,”name”:”result”,”type”:”bool”}],”title”:”CorrectPassword”,”sort”:”occasion”}
- Handle → Your contract deal with
- Filter → Nothing (depart it empty)
- TableName → MoriaGatesEvent
Click on on affirm once you’re prepared, and your database shall be up to date with a brand new MoriaGatesEvent object, created each time the contract emits the CorrectPassword occasion:
Now go to the start of GameManager.cs, and also you’ll see we’ve got a MoralisObject known as MoralisGatesEvent.
We’ll get notified in Unity each time a brand new MoriaGatesEvent will get created within the database, due to the SubscribeToDatabaseEvents() operate:
personal async void SubscribeToDatabaseEvents()
{
_getEventsQuery = await Moralis.GetClient().Question<MoriaGatesEvent>();
_queryCallbacks = new MoralisLiveQueryCallbacks<MoriaGatesEvent>();
_queryCallbacks.OnUpdateEvent += HandleContractEventResponse;
MoralisLiveQueryController.AddSubscription<MoriaGatesEvent>("MoriaGatesEvent", _getEventsQuery, _queryCallbacks);
}
We try this by subscribing to the onUpdateEvent of the queryCallbacks and we name HandleContractEventResponse() which principally prompts the correct UI panel primarily based on if we guessed the right password:
personal void HandleContractEventResponse(MoriaGatesEvent newEvent, int requestId)
{
if (!_listening) return;
if (newEvent.end result)
{
correctPanel.SetActive(true);
Debug.Log("Right password");
}
else
{
incorrectPanel.SetActive(true);
Debug.Log("Incorrect password");
}
statusLabel.textual content = string.Empty;
_listening = false;
StartCoroutine(DoSomething(newEvent.end result));
}
Do not forget that the occasion CorrectPassword within the sensible contract passes a bool, so the MoriaGatesEvent object we obtain in Unity, by being subscribed to the onUpdateEvent, additionally carries this bool worth.
Now for an important a part of this tutorial!
How will we ship the password that we sort within the recreation to the contract, so it will possibly test if it’s appropriate or not?
Like this: Go to Unity, hit Play and log in.
You’ll see that the passwordPanel will get activated. This occurs as a result of AuthenticationKit calls the StartGame() operate in GameManager.cs each time it connects efficiently. StartGame() then prompts the passwordPanel:
Then, after we click on the ENTER button, we name a GameManager.cs operate known as OpenGates():
OpenGates() calls CallContractFunction() and passes the enter subject textual content (the password that we enter) as a parameter:
public async void OpenGates()
{
statusLabel.textual content = "Please affirm transaction in your pockets";
var response = await CallContractFunction(passwordPanel.passwordInput.textual content);
if (response == null)
{
statusLabel.textual content = "Contract name failed";
return;
}
statusLabel.textual content = "Ready for contract occasion...";
passwordPanel.gameObject.SetActive(false);
_listening = true;
}
And right here’s the place the Moralis magic comes!
In CallContractFunction(), we create a parameters object with the password entered, a default gasoline estimate, and we name ExecuteContractFunction() passing the ContractAddress, the ContractAbi, the title of the contract operate that we need to name (openGates on this case), the parameters object, and the gasoline estimate values:
personal async UniTask<string> CallContractFunction(string inputPassword)
{
object[] parameters = {
inputPassword
};
// Set gasoline estimate
HexBigInteger worth = new HexBigInteger(0);
HexBigInteger gasoline = new HexBigInteger(0);
HexBigInteger gasPrice = new HexBigInteger(0);
string resp = await Moralis.ExecuteContractFunction(ContractAddress, ContractAbi, "openGates", parameters, worth, gasoline, gasPrice);
return resp;
}
And similar to that, we shall be calling the openGates() operate in our deployed contract. The contract will emit the CorrectPassword occasion which we’ll hearken to in Unity, and we’ve got the power to do no matter we wish relying on that. Good!
5. Construct the venture in WebGL
Now it’s time to check this on WebGL. On the highest toolbar go to File → Construct Settings and change to WebGL platform:
After that, be sure you have the Foremost scene added to Scenes In Construct and click on on Construct And Run. Choose a folder and look ahead to the construct course of to finish:
Take note constructing a Unity venture to WebGL takes a while, particularly the primary time you construct it. After about 5 to 10 minutes you must have it within the browser like so:
Now you can attempt logging in with totally different passwords and see what you get as a response. Do not forget that the right password is Mellon, so sort that and look ahead to the occasion to emit. Utilizing Mellon try to be getting the CORRECT response:
Congratulations!
You will have accomplished the Unity & Sensible Contracts tutorial. Effectively completed! ?