<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Rocky Essel - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Rocky Essel - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 15 May 2026 22:29:35 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/rockyessel/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Build and Deploy a Smart Contract With Rust and the Gear Protocol ]]>
                </title>
                <description>
                    <![CDATA[ Smart contracts are like digital agreements that run on blockchain technology, making transactions automatic and secure. While many people use Ethereum and Solidity to create these contracts, there are other options that can be just as powerful.  One... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-and-deploy-smart-contract-rust-gear-protocol/</link>
                <guid isPermaLink="false">66bb89c32108ff2ab9af1673</guid>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web3 ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rocky Essel ]]>
                </dc:creator>
                <pubDate>Tue, 04 Jun 2024 10:36:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/How-to-Build-and-Deploy-a-Smart-Contract-With-Rust-and-the-Gear-Protocol-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Smart contracts are like digital agreements that run on blockchain technology, making transactions automatic and secure. While many people use Ethereum and Solidity to create these contracts, there are other options that can be just as powerful. </p>
<p>One great combination is using Rust with the Gear Protocol. In this guide, I'll show you how to build and deploy a smart contract using Rust and the Gear Protocol. Whether you're new to this or have some experience, this article will help you get started with clear and easy-to-follow steps.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ol>
<li>Have basic Rust knowledge.</li>
<li>Having a basic understanding of decentralization. </li>
</ol>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-introduction-to-vara-network-amp-gear-protocol">Introduction to Vara Network &amp; Gear Protocol.</a></li>
<li><a class="post-section-overview" href="#heading-why-use-the-web2-analogy">Why Use the Web2 Analogy</a>? </li>
<li><a class="post-section-overview" href="#heading-message-based-communication">Message-based Communication</a>.</li>
<li><a class="post-section-overview" href="#heading-illustration">Illustration</a></li>
<li><a class="post-section-overview" href="#heading-vara-networks-role">Vara Network's Role</a>.</li>
<li><a class="post-section-overview" href="#heading-first-project-reading-a-joke">First Project – Reading a Joke</a></li>
<li><a class="post-section-overview" href="#heading-next-project-input-msg">Next Project – <code>input-msg</code></a></li>
<li><a class="post-section-overview" href="#heading-metadata-amp-state">Metadata &amp; State</a></li>
<li><a class="post-section-overview" href="#heading-third-project-building-messages">Third Project – Building Messages</a></li>
<li><a class="post-section-overview" href="#heading-final-project">Final Project – Battle Showdown</a></li>
<li><a class="post-section-overview" href="#conclusion-1">Conclusion.</a></li>
</ol>
<h2 id="heading-introduction-to-vara-network-amp-gear-protocol">Introduction to Vara Network &amp; Gear Protocol.</h2>
<h3 id="heading-vara-network">Vara Network</h3>
<p>Think of Vara as the sturdy foundation of blockchain technology. It's a layer-1 blockchain, meaning that it's at the core of transactions, ensuring that they are secure and decentralized. Vara uses Nominated Proof-of-Stake (NPoS) for agreement, making it reliable and efficient.</p>
<p>Furthermore, Vara Network distinguishes itself through its novel Actor Model, an architecture characterized by isolation and asynchronous messaging. This paradigm shift in smart contract execution imbues Vara Network with unparalleled security and scalability, setting it apart from conventional blockchain platforms.</p>
<h3 id="heading-gear-protocol">Gear Protocol</h3>
<p>Gear Protocol is like a toolbox for developers. It's a smart contract engine that makes building decentralized apps (dApps) faster, safer, and cheaper. By using substrate technology and WebAssembly (Wasm), Gear makes it easy for developers to create dApps that run smoothly and securely.</p>
<p>Gear's utilization of the Wasm virtual machine serves as a cornerstone of its efficiency. By harnessing the power of Wasm, developers can transcend language barriers, seamlessly integrating existing codebases and accelerating the development lifecycle. This fusion of familiarity and performance paves the way for a new era of dApp creation, where speed, security, and scalability converge harmoniously.</p>
<p>In simpler terms, Vara Network and Gear Protocol work together to make blockchain technology more user-friendly and secure for building and using decentralized apps.</p>
<h2 id="heading-why-use-the-web2-analogy">Why Use the Web2 Analogy?</h2>
<p>Understanding message-based communication, particularly within the context of Gear Protocol, can be quite challenging. To gain a clearer understanding, I delved into the documentation and conducted additional research. Eventually, I stumbled upon an analogy that made it all click: the analogy of web HTTP requests, specifically the POST method.</p>
<p>Let's dissect this analogy step by step. Consider the familiar scenario of a user visiting a website like google.com and interacting with the search bar. When the user enters a search query and hits enter, what's happening behind the scenes is akin to a POST HTTP request being sent.</p>
<h3 id="heading-heres-how-it-unfolds">Here's how it unfolds:</h3>
<ol>
<li><strong>User Interaction:</strong> The user initiates the action by typing a search query into the search bar and hitting enter. This action triggers a request for information.</li>
<li><strong>Client Acknowledgment:</strong> Google's website, acting as the client-side user interface (UI), acknowledges the user's input and prepares to send a request to the server for processing.</li>
<li><strong>Request Sent:</strong> Just like when you hit enter after typing a query, Google's website sends a POST request to its server, conveying the user's search query.</li>
<li><strong>Server Processing:</strong> Upon receiving the POST request, Google's server processes the query, searching its vast index for relevant information.</li>
<li><strong>Response Generation:</strong> After processing the query, Google's server generates a response containing the search results.</li>
<li><strong>Response Sent:</strong> Finally, Google's server sends the response back to the client (the user's web browser), completing the communication cycle.</li>
</ol>
<p>In this analogy, the user represents the initiator of the communication, the client (UI) serves as the intermediary between the user and the server, and the server acts as the responder, processing requests and generating responses.</p>
<p>By drawing parallels between message-based communication in Gear Protocol and the familiar concept of web HTTP requests, we can better grasp the dynamics at play. Just as understanding how web requests facilitate communication between users and servers is essential for navigating the internet, comprehending message-based communication in Gear Protocol is crucial for building and interacting with decentralized applications effectively.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/image-114.png" alt="Image" width="600" height="400" loading="lazy">
<em>how the POST method works</em></p>
<h2 id="heading-message-based-communication">Message-based Communication</h2>
<p>Similarly, the Gear Protocol operates based on user or program interactions.<br><strong>Note</strong>: Programs on Gear can also interact with each other.<br>So here is a detailed explanation to the whole communication flow in Gear.</p>
<h3 id="heading-user-interaction-and-gear-jsapi">User Interaction and @gear-js/api</h3>
<p>When a user (actor) interacts with the dApp's UI elements (like buttons or forms), <code>_@gear-js/api_</code> (which is integrated into the UI) captures these interactions. Based on the interactions, it extracts information and potentially pre-defined message formats, and then contracts a message object containing the user's intent or request.</p>
<h3 id="heading-how-to-send-messages">How to Send Messages</h3>
<p>The constructed message object encapsulates the user's input and becomes the data <code>@gear-js/api</code> transmits across the Vara Network to the Gear crate within the program.</p>
<h3 id="heading-how-the-program-receives-and-processes-messages">How the Program Receives and Processes Messages</h3>
<p>Gear (<code>crate</code>) delivers the message object to the appropriate program deployed on the Vara Network based on the location the user initiated the action. The Gear crate within the program utilizes functions like <code>msg::load()</code> and access the delivered message object, which the program extracts information (such as <code>payload</code>, <code>source</code>, <code>messsageId</code>) from, and process it according to how it's designed by the developer.</p>
<h3 id="heading-how-to-generate-a-reply">How to Generate a Reply</h3>
<p>Based on the processed input, the program creates a new message object containing a reply (<code>response</code> in <code>web2</code>) to the user's action or interaction (called <code>reply</code>) to or for the user. </p>
<p>Note, the program typically doesn't send the original message object back, it generates a new one based message received, which a reply is sent back to be received by <code>@gear-js/api</code> using the <code>gstd</code> crate from the program utilizing functions like the <code>msg::reply</code> or <code>msg::reply_bytes</code>.</p>
<h3 id="heading-ui-update">UI Update</h3>
<p><code>@gear-js/api</code>, within the dApp, receives the reply message object delivered by the <code>gstd</code> crate from the program across the Vara Network and extracts the response data from the reply object, and finally updates the UI reflecting the program's response to the user's interaction.  </p>
<p>And that's pretty much the communication between the Users, Client(dApp), Gear Protocol(<code>gstd</code>), and finally Vara Network.</p>
<h2 id="heading-illustration">Illustration</h2>
<p>Let's discuss more about the diagrams below, and how they each interact with each other.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/image-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>UI Update</em></p>
<p>This illustration above is just a bird's eye view of how communication flows from the user to the program<strong>.</strong> I'll provide a complete illustration for more clarity. But before that, let's break the overview illustration into three stages.</p>
<h3 id="heading-initial-interaction-stage">Initial Interaction Stage</h3>
<p>As said earlier, this is when the user interacts with the program, both <code>@gear-js/api</code> and <code>gstd</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/image-124.png" alt="Image" width="600" height="400" loading="lazy">
<em>Initial Interaction Stage</em></p>
<h3 id="heading-businessprogram-logic">Business/Program Logic</h3>
<p>This section depicts the communication between the program and Gear within Vara Network. The <code>gstd</code> is used by the program to access the transmitted message (<code>msg::load()</code>) from the initial stage to perform business logic.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/image-126.png" alt="Image" width="600" height="400" loading="lazy">
<em>Business/Program Logic</em></p>
<h3 id="heading-reply-response">Reply (Response)</h3>
<p>This final stage shows how user feedback is delivered to the user or program. <code>@gear-js/api</code> translates it if necessary, and then updates the dApp's UI with the results. This allows the user to see the outcome of their action within the dApp.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/image-127.png" alt="Image" width="600" height="400" loading="lazy">
<em>Reply(Response)</em></p>
<p>That's great, right? This should help you understand how messages are passed from the client to the program. But what does Vara Network role mean here? Earlier I said that, the message object get transmitted across the Vara Network, but I didn't say how. Let's explain that.</p>
<h2 id="heading-vara-networks-role">Vara Network's Role</h2>
<p>In Vara, all participants, including user interfaces (through <code>@gear-js/api</code>) and smart contracts (programs &amp; <code>gstd</code>), are considered as actors. Another point to know is that, actors don't directly call functions within other actors (as in, programs interacting with other programs or even users). </p>
<p>Instead, they send messages containing data or instructions. So in our explanation of the message-based communication, Vara serves as the underlying decentralized network infrastructure for communication of our system (dApps). It provides a secure and reliable platform for message transmission across distributed network of nodes. And since Vara utilize a consensus mechanism NPoS (Nominated Proof-of-Stake), it ensures network security and transaction validation.</p>
<h2 id="heading-getting-our-hands-dirty">Getting Our Hands Dirty</h2>
<p>In order to build upon the above information I provided, you and I need to get our hands dirty by building and deploying programs with additional explanation for a clearer understanding. </p>
<p>Let's get started.</p>
<h3 id="heading-first-project-reading-a-joke">First Project - Reading a Joke</h3>
<p>In this project, you're going to interact with and deploy your smart contract on Vara Network, and receive a reply message back.</p>
<p>This is just a simple project, and nothing too complex. I chose this example project because it aligns with the analogy I gave earlier.</p>
<p>Currently, this project should be fine when running it on your Windows system. In case you get an error, scroll to the part of this article with a guide for setting up a Windows Subsystem for Linux (WSL), since it would allow you to run a Linux environment, including command-line tools and applications, directly on Windows, without the overhead of a traditional virtual machine or dual boot setup.</p>
<p>To get started, create a directory named <code>freecodecamp-gear-protocol</code>. Since you'll be building about fours projects, and I think it is important on how you can setup your projects for Gear Protocol.</p>
<p>So in your <code>freecodecamp-gear-protocol</code> directory, create a <code>Cargo.toml</code> file with the following code:</p>
<pre><code class="lang-toml"><span class="hljs-section">[workspace]</span>
<span class="hljs-attr">resolver</span> = <span class="hljs-string">"2"</span>
<span class="hljs-attr">members</span> = []


<span class="hljs-section">[workspace.package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"freecodecamp-gear-protocol"</span>
<span class="hljs-attr">version</span> = <span class="hljs-string">"0.1.0"</span>
<span class="hljs-attr">edition</span> = <span class="hljs-string">"2021"</span>
<span class="hljs-attr">authors</span> = [<span class="hljs-string">"Rocky Essel"</span>]
<span class="hljs-attr">license</span> = <span class="hljs-string">"MIT"</span>
<span class="hljs-attr">publish</span> = <span class="hljs-literal">false</span>

<span class="hljs-section">[workspace.dependencies]</span>
<span class="hljs-comment"># Internal Crates</span>
<span class="hljs-comment"># External Crates</span>
</code></pre>
<p>For someone new to Rust or used to creating single projects, I'll guide you through understanding and setting up a workspace in Rust, making it easy to grasp.</p>
<h3 id="heading-understanding-your-workspace">Understanding Your Workspace</h3>
<p>A workspace in Rust is a set of packages (crates) that are managed together. Let's break down the key sections: <code>[workspace]</code>, <code>members</code>, <code>[workspace.package]</code>, and <code>[workspace.dependencies]</code>. So think of this like a cabin for your shoes, where each pair of shoes is a crate (package) that you want to keep organized.</p>
<h4 id="heading-workspace-section"><code>[workspace]</code> Section</h4>
<p>The <code>[workspace]</code> section defines the overall workspace. It typically contains multiple members.</p>
<p><strong><code>resolver = "2"</code></strong>: Specifies the version of Cargo's feature resolver to use, improving how dependencies are managed across the workspace.</p>
<p><strong><code>members</code></strong>: Lists the crates that are part of the workspace. When you add a project with <code>cargo new --lib sneakers</code> or <code>boots</code>, the <code>members</code> section of the <code>Cargo.toml</code> is populated with the name of the project you created.</p>
<blockquote>
<p>If not added automatically, you can add them yourself.</p>
</blockquote>
<p>  For example:</p>
<pre><code class="lang-toml"><span class="hljs-attr">members</span> = [<span class="hljs-string">"sneakers"</span>, <span class="hljs-string">"boots"</span>]
</code></pre>
<h4 id="heading-workspacepackage-section"><code>[workspace.package]</code> Section</h4>
<p>This section provides metadata for the entire workspace as if it were a single package.</p>
<ul>
<li><strong><code>name</code></strong>: The name of the workspace package.</li>
<li><strong><code>version</code></strong>: The version of the workspace package.</li>
<li><strong><code>edition</code></strong>: The Rust edition being used (e.g., "2021").</li>
<li><strong><code>authors</code></strong>: List of authors.</li>
<li><strong><code>license</code></strong>: The license for the workspace package.</li>
<li><strong><code>publish</code></strong>: Indicates whether the workspace package should be published to crates.io.</li>
</ul>
<p>Example:</p>
<pre><code class="lang-toml"><span class="hljs-section">[workspace.package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"my-shoe-collection"</span>
<span class="hljs-attr">version</span> = <span class="hljs-string">"0.1.0"</span>
<span class="hljs-attr">edition</span> = <span class="hljs-string">"2021"</span>
<span class="hljs-attr">authors</span> = [<span class="hljs-string">"Your Name"</span>]
<span class="hljs-attr">license</span> = <span class="hljs-string">"MIT"</span>
<span class="hljs-attr">publish</span> = <span class="hljs-literal">false</span>
</code></pre>
<h4 id="heading-workspacedependencies-section"><code>[workspace.dependencies]</code> Section</h4>
<p>Lists dependencies that apply to the entire workspace. Meaning that every crate whether external or internal added to the <code>[workspace.dependencies]</code> is accessible to every project you create under project workspace. So below is how both external and internal crate are made accessible to other project.</p>
<p><strong>Note</strong>: For internal crate, you need to add them yourself.</p>
<p><strong><code>Internal Crates</code></strong>: Add internal crates like this:</p>
<pre><code class="lang-toml"><span class="hljs-attr">sneakers</span> = { path = <span class="hljs-string">"sneakers"</span> }
<span class="hljs-attr">boots</span> = { path = <span class="hljs-string">"boots"</span> }
</code></pre>
<p><strong><code>External Crates</code></strong>: Add external crates like this:</p>
<pre><code class="lang-toml"><span class="hljs-attr">polish</span> = <span class="hljs-string">"1.0"</span>
</code></pre>
<h3 id="heading-example-cargotoml">Example <code>Cargo.toml</code></h3>
<p>Here's an example combining these sections:</p>
<pre><code class="lang-toml"><span class="hljs-section">[workspace]</span>
<span class="hljs-attr">resolver</span> = <span class="hljs-string">"2"</span>
<span class="hljs-attr">members</span> = [<span class="hljs-string">"sneakers"</span>, <span class="hljs-string">"boots"</span>]

<span class="hljs-section">[workspace.package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"my-shoe-collection"</span>
<span class="hljs-attr">version</span> = <span class="hljs-string">"0.1.0"</span>
<span class="hljs-attr">edition</span> = <span class="hljs-string">"2021"</span>
<span class="hljs-attr">authors</span> = [<span class="hljs-string">"Your Name"</span>]
<span class="hljs-attr">license</span> = <span class="hljs-string">"MIT"</span>
<span class="hljs-attr">publish</span> = <span class="hljs-literal">false</span>

<span class="hljs-section">[workspace.dependencies]</span>
<span class="hljs-comment"># Internal crate</span>
<span class="hljs-attr">sneakers</span> = { path = <span class="hljs-string">"sneakers"</span> } 
<span class="hljs-attr">boots</span> = { path = <span class="hljs-string">"boots"</span> } 

<span class="hljs-comment"># External crate</span>
<span class="hljs-attr">polish</span> = <span class="hljs-string">"1.0"</span>
</code></pre>
<p>So, here's how you set up a workspace for your project to manage multiple crates (sub-projects) and share dependencies and configuration settings across them. I spent quite some time understanding this, so I thought I'd share it with you all to make it easier.</p>
<p>To build your first smart contract, run the command below in your parent directory (<code>freecodecamp-gear-protocol</code>) on your terminal.</p>
<pre><code class="lang-bash">cargo new --lib receive-joke
</code></pre>
<pre><code class="lang-bash">.freecodecamp-gear-protocol
├── Cargo.toml
└── receive-joke
    ├── Cargo.toml
    └── src
        └── lib.rs

2 directories, 3 files
</code></pre>
<p>Head over to your <code>freecodecamp-gear-protocol/receive-joke/Cargo.toml</code>, and this is how you access crates, and configuration from the workspace directory(main) using <code>.workspace=true</code>, like below;</p>
<pre><code class="lang-toml"><span class="hljs-section">[package]</span>
<span class="hljs-attr">name</span> =<span class="hljs-string">"receive-joke"</span>
<span class="hljs-attr">version.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">edition.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">authors.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">license.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">publish.workspace</span> = <span class="hljs-literal">true</span>

<span class="hljs-comment"># See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html</span>

<span class="hljs-section">[dependencies]</span>
</code></pre>
<p>Next, create a <code>build</code> file in your <code>receive-joke</code> directory with path like<code>receive-joke/build.rs</code>, and paste the code below. Now, the <code>build.rs</code> helps you to build your project into <code>.wasm</code> file, that is used to deploy your smart contract.</p>
<p><strong>build.rs:</strong></p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    gear_wasm_builder::build();
}
</code></pre>
<p>Currently, you have't install the nesscessary crate to help create your smart contract. Therefore, add the following crate to your workspace dependency.</p>
<p><strong>Cargo.toml:</strong></p>
<pre><code class="lang-toml"><span class="hljs-section">[workspace]</span>
<span class="hljs-attr">resolver</span> = <span class="hljs-string">"2"</span>
<span class="hljs-attr">members</span> = [<span class="hljs-string">"receive-joke"</span>]


<span class="hljs-section">[workspace.package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"freecodecamp-gear-protocol"</span>
<span class="hljs-attr">version</span> = <span class="hljs-string">"0.1.0"</span>
<span class="hljs-attr">edition</span> = <span class="hljs-string">"2021"</span>
<span class="hljs-attr">authors</span> = [<span class="hljs-string">"Rocky Essel"</span>]
<span class="hljs-attr">license</span> = <span class="hljs-string">"MIT"</span>
<span class="hljs-attr">publish</span> = <span class="hljs-literal">false</span>

<span class="hljs-section">[workspace.dependencies]</span>
<span class="hljs-comment"># Internal Crates</span>

<span class="hljs-comment"># External Crates</span>
<span class="hljs-attr">gstd</span> = <span class="hljs-string">"1.4.1"</span>
<span class="hljs-attr">gmeta</span> = <span class="hljs-string">"1.4.1"</span>
<span class="hljs-attr">gtest</span>  = <span class="hljs-string">"1.4.1"</span>
<span class="hljs-attr">gear-wasm-builder</span> = <span class="hljs-string">"1.4.1"</span>
<span class="hljs-attr">parity-scale-codec</span> = { version = <span class="hljs-string">"3.6.12"</span>, default-features = <span class="hljs-literal">false</span> }
<span class="hljs-attr">scale-info</span> = { version = <span class="hljs-string">"2.11.3"</span>, default-features = <span class="hljs-literal">false</span> }
</code></pre>
<p>For your first project, only <code>gstd</code> would be used, so like add that external crate to your <code>receive-joke</code>'s <code>Cargo.toml</code>. Like below:</p>
<pre><code class="lang-toml"><span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">gstd.workspace</span> = <span class="hljs-literal">true</span>


<span class="hljs-section">[build-dependencies]</span>
<span class="hljs-attr">gear-wasm-builder.workspace</span> = <span class="hljs-literal">true</span>
</code></pre>
<p>If you reached here without any errors, well done my friend. Next, is to clear any code in <code>freecodecamp-gear-protocol/receive-joke/src/lib.rs</code>. Let's move on to the next step.</p>
<p>In Gear Protocol, there are entry points. An entry point serves as a gateway or door to your code. Gear has a few entry points, namely:</p>
<pre><code class="lang-rust">state(),
handle(),
handle_reply(),
init(),
handle_signal(),
</code></pre>
<p>Each entry point plays a significant role. For example, <code>init()</code> is called when the smart contract(<code>.wasm</code>) is deployed, allowing you to set certain conditions or variables or even other functions  that need to be executed for smooth sailing of your smart contract or program.</p>
<p>However, it's optional, meaning that you can choose to include or exclude it depending on your project, but it still gets executed, and it is the first message you'll see once you deploy your smart contract.</p>
<p>The <code>handle()</code> method is crucial as it contains most of the business logic. It's mandatory to include your program. More light will be shared on the entry points as you move forward.</p>
<p>Now, paste the following code into your <code>receive-joke/src/lib.rs</code>:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#![no_std]</span>

<span class="hljs-keyword">use</span> gstd::msg;

<span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">handle</span></span>() {
    <span class="hljs-comment">// Send a reply(in HTTP GET Request, you'd use "response").</span>
    msg::reply_bytes(
        <span class="hljs-string">"What did the dirt say to the rain? If you keep this up, my name will be mud!"</span>,
        <span class="hljs-number">0</span>,
    )
    .expect(<span class="hljs-string">"Unable to reply"</span>);
}
</code></pre>
<p>The code above defines a function <code>handle</code> that, when called, sends a message you've defined as a response using the <code>gstd::msg</code> functionality. This <code>gstd</code> is a crate provided by Gear Protocol<strong>,</strong> to send and receive messages, and this is crucial for programs running on Vara Network to communicate with each other and external systems. And the <code>reply_bytes</code> send a new message as a reply to the message that is currently being processed.</p>
<p>Time to deploy and send your first message and recieve your joke reply. In your terminal, run the following command to build your program into <strong><code>.wasm</code></strong>.</p>
<p>Usually, I use <code>cargo check</code> for check for errors first, before using the <code>build</code> command below, either way is fine.</p>
<pre><code class="lang-bash">cargo build --release
</code></pre>
<p>After the build is completed, follow the structure below to locate your <strong><code>.wasm</code></strong> file in the path below:</p>
<pre><code class="lang-bash">.freecodecamp-gear-protocol
├── Cargo.lock
├── Cargo.toml
├── receive-joke
│   └── ...
└── target
    ├── ...
    └── wasm32-unknown-unknown
        ├── ...
        └── release
            ├── receive_joke.opt.wasm &lt;--- Optimized <span class="hljs-keyword">for</span> deployment.
            └── receive_joke.wasm
</code></pre>
<h3 id="heading-how-to-deploy-your-smart-contract">How to Deploy Your Smart Contract</h3>
<p>Just like in other blockchain tools, that help you deploy your smart contract from the terminal, IDEA is where you deploy your smart contract and interact with it. We'll be exploring the interface in a bit. So finally, head over to <a target="_blank" href="https://idea.gear-tech.io/">IDEA</a> so start familiarizing yourself with your deployment environment. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Screenshot-2024-03-30-135927.png" alt="Image" width="600" height="400" loading="lazy">
<em>Smart Contract Deplyment Web App- IDEA</em></p>
<ol>
<li>Step one, click on <strong>Upload program</strong>, then select or drag your <strong><code>.opt.wasm</code></strong> inside the modal. This takes you to the upload page, where you can change names, enter values for the payload, or change the payload type. For now, let's leave everything as it is, and click on the <strong>Calculate,</strong> which will enter a <code>0.00015</code> gas fee value for uploading your program.</li>
</ol>
<p><strong>Note</strong>: You can either set the gas limit yourself, or click on <strong>Calculate</strong> to allow the program to generate one for you.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Screenshot-2024-03-30-144729.png" alt="Image" width="600" height="400" loading="lazy">
<em>Upload Page Details</em></p>
<p>At this point, click on the <strong>Upload Program</strong>, and click on the <strong>Submit</strong> button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Screenshot-2024-03-30-144825.png" alt="Image" width="600" height="400" loading="lazy">
<em>Transaction Details- PopUp</em></p>
<p>When you submit, you'll be prompted you sign into a your wallet, and approve.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/image-128.png" alt="Image" width="600" height="400" loading="lazy">
<em>Wallet - SubWallet</em></p>
<p>After the approval, a toast message should be displayed at the right-hand corner your computer/laptop screen for you to see the status of your program, whether it failed or succeeded.</p>
<p>Assuming it's a success, click on the <strong>Programs</strong> on the sidebar, then BOOM!, there's your program. Click on it, and let's explore.</p>
<p>Upon deploying, the first thing you see is the program ID, but after a few seconds, the name of your program would be shown.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Screenshot-2024-03-30-150230.png" alt="Image" width="600" height="400" loading="lazy">
<em>Smart Contract Block - Page</em></p>
<p>Earlier, I said that when you deploy a program, the <code>init()</code> function is executed regardless of whether you defined it in your project or not, and that's what you see in the <strong>Messages</strong> section. Below is a simple illustration for you to familiarize and understand the information about your program.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/image-129.png" alt="Image" width="600" height="400" loading="lazy">
<em>Page Illustration</em></p>
<p>Now, it's time to send a message to your program and receive a reply back, which is our joke. Remember, you're not inputting any values, you're just performing a simple action to receive a reply from the program. So click on <strong>Calculate</strong> and press the <strong>Send Message</strong> (that's the action or interaction) button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Screenshot-2024-03-30-152529.png" alt="Image" width="600" height="400" loading="lazy">
<em>Performing an action - Initial Stage</em></p>
<p>After the message has been sent, a <code>success</code> toast will popup. Then head back to your program by clicking on the <strong>Cancel</strong> button, and you'll see two additional messages. </p>
<p>Remember, the blue color with the arrow represent the message you sent, and the green represents the reply you've received. So click on the replied message to see the joke, which says: <code>What did the dirt say to the rain? If you keep this up, my name will be mud!</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/image-130.png" alt="Image" width="600" height="400" loading="lazy">
<em>Receiving Reply &amp; More Illustration</em></p>
<p>Now, you're finally done with this project. In the next project, you'll be sending data or information to your program, and having it return a reply with your entered value attached to it. <a target="_blank" href="https://idea.gear-tech.io/programs/0x79e6c86aa1ab2026ef3bbc0ccbe801ce085ca2614b36f9e5be04d2354ad56396">Here is the program deployed on the <strong>Vara Network</strong></a>.</p>
<h3 id="heading-important-information">Important Information</h3>
<p>Though I've provided some context to the picture above, I want to expand on it. Both the <code>Source</code> and <code>Destination</code> takes an address that can be either a user (actor) and a program (actor), or even a message object.</p>
<h2 id="heading-next-project-input-msg">Next Project – <code>input-msg</code></h2>
<p>Just like the illustration earlier, you're going to interact with your program by sending an input value to your smart contract deployed on <strong><code>[IDEA](https://idea.gear-tech.io/programs?node=wss%3A%2F%2Ftestnet.vara.network)</code></strong>. <a target="_blank" href="https://idea.gear-tech.io/programs?node=wss%3A%2F%2Ftestnet.vara.network"><strong>IDEA</strong> </a> is your deployment environment where you deploy your smart contract on the Vara Network.<br> The point here is for you to load input values from your user, and process it by concatenating a string to the user's input value: "We've received your query. {user's-input}".</p>
<p>This is the reply you'll send back to the user that sends a message (input value).</p>
<p>So in your <code>freecodecamp-gear-protocol</code> directory, run the command below to add another member to your <code>freecodecamp-gear-protocol/Cargo.toml</code>.</p>
<pre><code class="lang-bash">cargo new --lib input-msg
</code></pre>
<p>After adding another member or project in the <code>freecodecamp-gear-protocol</code>, your path should be <code>freecodecamp-gear-protocol/input-msg</code>.</p>
<p>Earlier, I made mention of how to access input values into the smart contract or program by using <code>gstd</code>, which has a function or method called <code>load()</code>. For the next step, clear your <code>freecodecamp-gear-protocol/input-msg/src/lib.rs</code>, and paste the following code and run <code>cargo check</code>.</p>
<pre><code class="lang-bash"><span class="hljs-comment">#![no_std]</span>

use gstd::{msg, prelude::*};

<span class="hljs-comment">#[no_mangle]</span>
extern <span class="hljs-string">"C"</span> fn <span class="hljs-function"><span class="hljs-title">handle</span></span>() {
    <span class="hljs-built_in">let</span> new_msg = msg::load().expect(<span class="hljs-string">"Unable to create string"</span>);
    <span class="hljs-built_in">let</span> reply_msg = format!(<span class="hljs-string">"We've received your query {}"</span>, new_msg);
    msg::reply_bytes(reply_msg, 0).expect(<span class="hljs-string">"Unable to reply."</span>);
}
</code></pre>
<p>The check fails, but why? Well, the <code>load()</code> function has a type of <code>unknown</code>. And since Rust is a strongly typed language, it has to always know the type before hand, which wasn't the case, so it failed to build the project.</p>
<p>This should tell you that the <code>load()</code> doesn't have a type, and it is up to you to set the right data type, and failure to do so would result in some frustrating errors like below.</p>
<h3 id="heading-debugging">Debugging</h3>
<p>Now if you were to use a single project and not a workspace, then debugging the error might have easy like below.</p>
<pre><code class="lang-bash">
  error[E0282]: <span class="hljs-built_in">type</span> annotations needed
   --&gt; C:\Users\user\Desktop\2024\web3\re-gear\input-msg\src\lib.rs:7:9
    |
  7 |     <span class="hljs-built_in">let</span> new_msg = msg::load().expect(<span class="hljs-string">"Unable to create string"</span>);
    |         ^^^^^^^
    |
  <span class="hljs-built_in">help</span>: consider giving `new_msg` an explicit <span class="hljs-built_in">type</span>
    |
  7 |     <span class="hljs-built_in">let</span> new_msg: /* Type */ = msg::load().expect(<span class="hljs-string">"Unable to create string"</span>);
    |                ++++++++++++
</code></pre>
<p>But since you and I are using a workspace, it makes debugging a little difficult. This is my error message i got, when dubgging this error.</p>
<pre><code class="lang-bash">  error[E0275]: overflow evaluating the requirement `gstd::parity_scale_codec::Compact&lt;_&gt;: gstd::Decode`
    |
    = <span class="hljs-built_in">help</span>: consider increasing the recursion <span class="hljs-built_in">limit</span> by adding a `<span class="hljs-comment">#![recursion_limit = "256"]` attribute to your crate (`input_msg`)</span>
    = note: required <span class="hljs-keyword">for</span> `gstd::parity_scale_codec::Compact&lt;_&gt;` to implement `gstd::Decode`
    = note: 125 redundant requirements hidden
    = note: required <span class="hljs-keyword">for</span> `gstd::parity_scale_codec::Compact&lt;&lt;_ as CompactAs&gt;::As&gt;` to implement `gstd::Decode`

  For more information about this error, try `rustc --explain E0275`.
  error: could not compile `input-msg` (lib) due to 1 previous error
  warning: build failed, waiting <span class="hljs-keyword">for</span> other <span class="hljs-built_in">jobs</span> to finish...
  error: cargo <span class="hljs-built_in">command</span> run failed: <span class="hljs-built_in">exit</span> status: 101
warning: build failed, waiting <span class="hljs-keyword">for</span> other <span class="hljs-built_in">jobs</span> to finish...
</code></pre>
<p>And  if you look closely, you can tell that the <code>input-msg</code> is what creating the error. In this case, run <code>rustc --explain E0275</code>, which output an suggestion like this</p>
<pre><code class="lang-bash">An evaluation of a trait requirement overflowed.

Erroneous code example:

trait Foo {}

struct Bar&lt;T&gt;(T);

impl&lt;T&gt; Foo <span class="hljs-keyword">for</span> T <span class="hljs-built_in">where</span> Bar&lt;T&gt;: Foo {}

This error occurs when there was a recursive trait requirement that overflowed before it could be
evaluated. This often means that there is an unbounded recursion <span class="hljs-keyword">in</span> resolving some <span class="hljs-built_in">type</span> bounds.

To determine <span class="hljs-keyword">if</span> a T is Foo, we need to check <span class="hljs-keyword">if</span> Bar&lt;T&gt; is Foo. However, to <span class="hljs-keyword">do</span> this check, we need to
determine that Bar&lt;Bar&lt;T&gt;&gt; is Foo. To determine this, we check <span class="hljs-keyword">if</span> Bar&lt;Bar&lt;Bar&lt;T&gt;&gt;&gt; is Foo, and so on. This
is clearly a recursive requirement that can<span class="hljs-string">'t be resolved directly.

Consider changing your trait bounds so that they'</span>re less self-referential.
</code></pre>
<p>Now, though, compared to the first error message, this message doesn't provide a direct solution, it does tells you that, there's a type error in your code. And the reason is that, the <code>load()</code> can load any data type, so you should always defined a type for it.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#![no_std]</span>

<span class="hljs-keyword">use</span> gstd::{msg, prelude::*};

<span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">handle</span></span>() {
    <span class="hljs-keyword">let</span> new_msg: <span class="hljs-built_in">String</span> = msg::load().expect(<span class="hljs-string">"Unable to create string"</span>);
    <span class="hljs-keyword">let</span> reply_msg = <span class="hljs-built_in">format!</span>(<span class="hljs-string">"We've received your query {}"</span>, new_msg);
    msg::reply_bytes(reply_msg, <span class="hljs-number">0</span>).expect(<span class="hljs-string">"Unable to reply."</span>);
}
</code></pre>
<p>In the above code, you've added a type <code>String</code> to the <code>new_msg</code> because that's the <code>type</code> you're expecting. Now run the build command, and deploy the file <strong><code>.opt.wasm</code></strong> to <code>IDEA</code>. </p>
<pre><code class="lang-bash">.freecodecamp-gear-protocol
├── receive-joke
├── Cargo.toml
├── input-msg
│   └── ...
└── target
    ├── ...
    └── wasm32-unknown-unknown
        ├── ...
        └── release
            ├── input_msg.opt.wasm &lt;--- Optimized <span class="hljs-keyword">for</span> deployment.         
            ├── input_msg.wasm
            ├── receive_joke.opt.wasm
            └── receive_joke.wasm
</code></pre>
<p>When you're done, go to your program and click on the <strong>Send Messages</strong>. Type any value into the <code>payload</code> field, and it should be a <code>type</code> of <code>String</code>. </p>
<p>Submit and approve and head back to your program, then select your <code>reply_message</code> box and you should see your <code>reply message</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Screenshot-2024-04-06-080437.png" alt="Image" width="600" height="400" loading="lazy">
<em>Smart Contract - Reply Message</em></p>
<p><a target="_blank" href="https://idea.gear-tech.io/programs/0x25629eaa3c7a51ec407f89bbaae7ccb4f58c6026283758d0fccb50e3bb042bdd">You can find the program here on the Vara Network</a>.</p>
<h2 id="heading-metadata-amp-state">Metadata &amp; State</h2>
<p>Metadata and state goes hand in hand with each other. In order for your client application to allow users to interact or request data(state) from your smart contract, you need to define both the metadata and state, and even if the state is defined, and the metadata was not provided, you cannot access the any data.</p>
<p>So let's take each step by step.</p>
<h3 id="heading-metadata">Metadata</h3>
<p>In the Gear Protocol world, metadata is like a blueprint for defining how different parts of a decentralized app (dApp) talk to each other. It's similar to how interfaces or types work in TypeScript. These blueprints describe how things like initial data type to expect, handling messages, and swapping data happen in the dApp, whether <code>In</code>, <code>Out</code>, and <code>InOut</code>.</p>
<p>When we make clear blueprints, it helps developers make sure that all the different parts of the dApp understand each other's data formats. This makes it easy for the smart contract (program-actor) and the client side app to share data smoothly.</p>
<p>To create these blueprints for your program, we use the <code>gmeta</code> tool. It helps us define these blueprints by outlining how different interactions work and what kinds of data they involve.</p>
<p>So, think of metadata in your program as similar to how interfaces/types work in TypeScript. They help organize how the different parts of your dApp communicate and understand each other's data.</p>
<h3 id="heading-example-of-a-metadata">Example Of A Metadata</h3>
<pre><code class="lang-bash">use gmeta::{InOut, Metadata, Out};

pub struct ProgramMetadata;

// Be sure to describe all the types.
// But <span class="hljs-keyword">if</span> any of the endpoints is missing <span class="hljs-keyword">in</span> your program, you can use ();
// as indicated <span class="hljs-keyword">in</span> the <span class="hljs-keyword">case</span> of `<span class="hljs-built_in">type</span> Signal`.

impl Metadata <span class="hljs-keyword">for</span> ProgramMetadata {
    <span class="hljs-built_in">type</span> Init = InOut&lt;MessageInitIn, MessageInitOut&gt;;
    <span class="hljs-built_in">type</span> Handle = InOut&lt;MessageIn, MessageOut&gt;;
    <span class="hljs-built_in">type</span> Others = InOut&lt;MessageAsyncIn, Option&lt;u8&gt;&gt;;
    <span class="hljs-built_in">type</span> Reply = String;
    <span class="hljs-built_in">type</span> Signal = ();
    <span class="hljs-built_in">type</span> State = Out&lt;Vec&lt;Wallet&gt;&gt;;
}
</code></pre>
<p>The above is an example of how it is defined. Don't worry if you don't understand it now, I'll cover more into details later. Now let's talk about the state.</p>
<h3 id="heading-state">State</h3>
<p>In Gear Protocol, the <code>state</code> function serves as a dedicated storage space within a program. This storage allows us to store and retrieve data as needed. Since this data is stored in persistent memory, it remains accessible even after the contract stops running. What's fascinating is that anyone with access to the blockchain can view this stored data. The <code>state</code> function doesn't alter or modify the blockchain itself. Instead, it simply provides a way to access stored data within the program.</p>
<p>Here is an example of a <code>state</code> function:</p>
<pre><code class="lang-bash">// Describe state structure
<span class="hljs-comment">#[derive(TypeInfo, Decode, Encode, Clone)]</span>
pub struct Messages {
    pub id: ActorId,
    pub content: String,
}

// Declare and initialize the state
static mut MESSAGES: Vec&lt;Messages&gt; = Vec::new();

<span class="hljs-comment">#[no_mangle]</span>
extern <span class="hljs-string">"C"</span> fn <span class="hljs-function"><span class="hljs-title">state</span></span>() {
    msg::reply(unsafe { MESSAGES.clone() }, 0).expect(<span class="hljs-string">"Failed to share state"</span>);
}
</code></pre>
<p>When the <code>state</code> function is called, it returns a list of <code>wallets</code> data stored within the program. This means that once a program is deployed on the blockchain, anyone can read its state.</p>
<p>Additionally, developers have the flexibility to create custom programs that can read the state. This empowers you and I to tailor our data access methods according to the specific needs for our dApp, even if the primary program undergoes changes.</p>
<p>The key takeaway is that, the <code>state</code> function facilitates access to data stored in smart contracts. It's worth noting that both users and other programs can access the state of a program, providing a versatile means of interacting with stored data.</p>
<h2 id="heading-third-project-building-messages">Third Project - Building Messages</h2>
<p>In our last project <code>input-msg</code>, we didn't keep track of the messages that got sent. So in this project, we'll cover the metadata and state.</p>
<p>Run the command below to create your project in <strong>/freecodecamp-gear-protocol/</strong>:</p>
<pre><code class="lang-bash">cargo new --lib messages
</code></pre>
<p>Next, add your <strong>build.rs</strong> file, and make the workspace dependencies available to the <code>/freecodecamp-gear-protocol/messages</code>.</p>
<h3 id="heading-adding-metadata-to-messages">Adding Metadata to Messages</h3>
<p>To setup a metadata for your project, you need to create an additional crate to manage that, so <code>cd</code> into <strong>messages</strong>, and run the command below.</p>
<pre><code class="lang-bash">cargo new --lib io
</code></pre>
<p>In your <strong>freecodecamp-gear-protocol/messages/io/Cargo.toml</strong>, copy and paste the following code:</p>
<pre><code class="lang-toml"><span class="hljs-section">[package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"messages-io"</span>
<span class="hljs-attr">version.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">edition.workspace</span> = <span class="hljs-literal">true</span>


<span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">gstd.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">gmeta.workspace</span> = <span class="hljs-literal">true</span>
</code></pre>
<p>Here, I changed the name from <code>io</code> to <code>messages-io</code>, and the reason is for me to identify, and separate it for other <code>io</code>'s in the workspace. And add the dependencies.</p>
<p>In order to use the <code>io</code> in your workspace, you need to go the <strong>freecodecamp-gear-protocol/Cargo.toml</strong>, and add a path from your <code>io</code> to your workspace, which you can then use in any of the projects that need <code>struct</code>, <code>enum</code>, and <code>method</code>.</p>
<p>In <strong>freecodecamp-gear-protocol/Cargo.toml</strong>:</p>
<pre><code class="lang-bash">[workspace]
resolver = <span class="hljs-string">"2"</span>
members = [<span class="hljs-string">"receive-joke"</span>,<span class="hljs-string">"input-msg"</span>]


[workspace.package]
name = <span class="hljs-string">"freecodecamp-gear-protocol"</span>
version = <span class="hljs-string">"0.1.0"</span>
edition = <span class="hljs-string">"2021"</span>
authors = [<span class="hljs-string">"Rocky Essel"</span>]
license = <span class="hljs-string">"MIT"</span>
publish = <span class="hljs-literal">false</span>

[workspace.dependencies]
<span class="hljs-comment"># Internal Crates</span>
messages-io={path = <span class="hljs-string">"messages/io"</span>} &lt; ---- Here

<span class="hljs-comment"># External Crates</span>
gstd = <span class="hljs-string">"1.4.1"</span>
gmeta = <span class="hljs-string">"1.4.1"</span>
gtest  = <span class="hljs-string">"1.4.1"</span>
gear-wasm-builder = <span class="hljs-string">"1.4.1"</span>
parity-scale-codec = { version = <span class="hljs-string">"3.6.12"</span>, default-features = <span class="hljs-literal">false</span> }
scale-info = { version = <span class="hljs-string">"2.11.3"</span>, default-features = <span class="hljs-literal">false</span> }
</code></pre>
<p>And that's the <code>Internal Crate</code> I talked about earlier. Next, you need to include the <code>messages-io</code> in your <code>messages</code> project, like below:</p>
<pre><code class="lang-toml"><span class="hljs-section">[package]</span>
<span class="hljs-attr">name</span>=<span class="hljs-string">"messages"</span>
<span class="hljs-attr">version.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">edition.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">authors.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">license.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">publish.workspace</span> = <span class="hljs-literal">true</span>


<span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">gstd.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">messages-io.workspace</span> = <span class="hljs-literal">true</span> &lt;---

<span class="hljs-section">[build-dependencies]</span>
<span class="hljs-attr">gear-wasm-builder.workspace</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">messages-io.workspace</span> = <span class="hljs-literal">true</span> &lt; ---
</code></pre>
<p>The reason for adding <code>messages-io.workspace</code> to both the <code>[dependencies]</code> and <code>[build-dependencies]</code> is to make the <code>struct</code>, <code>enums</code>, <code>pub variables</code> and <code>methods</code> accessible to <code>messages/src/lib.rs</code>, and <code>messages/build.rs</code> using <code>messages-io.workspace</code>.</p>
<h3 id="heading-metadata-in-iosrclibrs">Metadata in <code>io/src/lib.rs</code></h3>
<pre><code class="lang-rust"><span class="hljs-meta">#![no_std]</span>

<span class="hljs-keyword">use</span> gmeta::{InOut, Metadata, Out};
<span class="hljs-keyword">use</span> gstd::{prelude::*, ActorId, <span class="hljs-built_in">Vec</span>};

<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MessageMetadata</span></span>;

<span class="hljs-keyword">pub</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">mut</span> MESSAGES: <span class="hljs-built_in">Vec</span>&lt;User&gt; = <span class="hljs-built_in">Vec</span>::new();

<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Message</span></span> {
    <span class="hljs-keyword">pub</span> id: ActorId,
    <span class="hljs-keyword">pub</span> content: <span class="hljs-built_in">String</span>,
}

<span class="hljs-keyword">impl</span> Metadata <span class="hljs-keyword">for</span> MessageMetadata {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Init</span></span> = InOut&lt;Message, <span class="hljs-built_in">String</span>&gt;;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Handle</span></span> = InOut&lt;Message, <span class="hljs-built_in">String</span>&gt;;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">State</span></span> = Out&lt;<span class="hljs-built_in">Vec</span>&lt;Message&gt;&gt;;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Reply</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Others</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Signal</span></span> = ();
}
</code></pre>
<p>To implement the logic of the message-handling system for your program or smart contract, understanding how to set the metadata of your program is crucial.<br>Therefore, much attention is needed here.</p>
<p>The <code>MessageMetadata</code> struct you've defined implements the <code>Metadata</code> trait, which then structures the message metadata for the program. Also, a mutable static variable <code>MESSAGES</code> is declared to store all the messages you and your users send to the program. And since it’s a mutable static variable, unsafe code will be required to modify it due to Rust's safety guarantees around mutable static variables.</p>
<p>The <code>Message</code> struct is defined with two fields: <code>id</code> (sender's identifier) and <code>content</code> (the message text).</p>
<p>The <code>Metadata</code> trait is implemented for <code>MessageMetadata</code>, defining several associated types. The <code>Init</code> type is set to <code>InOut&lt;MessageInit, String&gt;</code>, specifying the input-output types for the initialization phase. \</p>
<p>This means that when the contract is initialized, it will accept a <code>MessageInit</code> type and return a <code>String</code>. The <code>Handle</code> type is set to <code>InOut&lt;Message, String&gt;</code>, specifying the input-output types for handling messages. It accepts a <code>Message</code> type as input and returns a <code>String</code>. </p>
<p>The <code>State</code> type is set to <code>Out&lt;Vec&lt;Message&gt;&gt;</code>, defining the state output type, meaning that the state of the contract will be a vector of <code>Message</code> objects, and it doesn’t accept any input to retrieve this state. The <code>Reply</code>, <code>Others</code>, and <code>Signal</code> types are all set to <code>()</code>, indicating no additional reply, other types, or signals are used in this case.</p>
<h3 id="heading-further-context-of-its-usage">Further Context of its usage.</h3>
<p>In this system, the metadata definition specifies how the smart contract should handle initialization and message handling. During the initialization phase (<code>Init</code>), when the contract is deployed on the Vara Network, it uses the <code>Init</code> type to set up the initial state. The input is expected to be of type <code>MessageInit</code>, and the output will be a <code>String</code>. During deployment, you provide your ID and message content, which the contract processes using the <code>init()</code> method.</p>
<p>After deployment, the contract can handle new messages using the <code>Handle</code> type, which expects a <code>Message</code> type as input and returns a <code>String</code> as a response. This functionality is useful for adding new messages to the <code>MESSAGES</code> vector. For state management (<code>State</code>), the contract’s state is a list of messages (<code>Vec&lt;Message&gt;</code>), and it doesn’t accept any input to retrieve the state but outputs the current state when queried.</p>
<p>So to summarize, the code in <strong>freecodecamp-gear-protocol/messages/io/src/lib.rs</strong> defines the structure and behavior of a message-handling smart contract, specifying how it initializes, handles messages, and manages state.</p>
<h3 id="heading-building-the-metadata">Building the Metadata</h3>
<p>In order to build your project with the metadata, you need to modify the <strong>build.rs</strong>, which initially looks like below:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    gear_wasm_builder::build();
}
</code></pre>
<p>There's nothing wrong with using the above code, but if you plan to build your program and deploy on the blockchain to use it on the client or anywhere else, it would be impossible to interact with your smart contract if the metadata is not defined. Think of it like <code>ABI</code> in other blockchain environment.</p>
<p>So replace the code with:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> messages_io::MessageMetadata;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    gear_wasm_builder::build_with_metadata::&lt;MessageMetadata&gt;();
}
</code></pre>
<p>Finally, you would be handling the logic for your smart contract in the <code>messages/src/lib.rs</code> using the <code>handle()</code> function.</p>
<p>Here is the code for the <code>lib.rs</code>:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#![no_std]</span>

<span class="hljs-keyword">use</span> gstd::{exec, msg, prelude::*, ActorId};

<span class="hljs-keyword">use</span> messages_io::*;

<span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">init</span></span>() {
    <span class="hljs-keyword">let</span> init: Message = msg::load().expect(<span class="hljs-string">"Unable to decode Message"</span>);
    <span class="hljs-keyword">let</span> init_message = Message {
        id: init.id,
        content: init.content,
    };

    <span class="hljs-keyword">unsafe</span> { MESSAGES.push(init_message) };    
    msg::reply_bytes(<span class="hljs-string">"Successfully initialized"</span>, <span class="hljs-number">0</span>).expect(<span class="hljs-string">"Failed to initialize successfully."</span>);
}


<span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">handle</span></span>() {

    <span class="hljs-keyword">let</span> message_handler: Message = msg::load().expect(<span class="hljs-string">"Unable to decode Message"</span>);
    <span class="hljs-keyword">let</span> message = Message {
        id: message_handler.id,
        content: message_handler.content,
    };
    <span class="hljs-keyword">unsafe</span> { MESSAGES.push(message) };
    msg::reply_bytes(<span class="hljs-string">"Message sent successfully."</span>, <span class="hljs-number">0</span>).expect(<span class="hljs-string">"Failed to send  reply message."</span>);
}


<span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">state</span></span>() {
    msg::reply(<span class="hljs-keyword">unsafe</span> { MESSAGES.clone() }, <span class="hljs-number">0</span>).expect(<span class="hljs-string">"Failed to share state"</span>);
}
</code></pre>
<h3 id="heading-initialization-function-init">Initialization Function (<code>init</code>)</h3>
<pre><code class="lang-rust"><span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">init</span></span>() {
    <span class="hljs-keyword">let</span> init: Message = msg::load().expect(<span class="hljs-string">"Unable to decode Message"</span>);
    <span class="hljs-keyword">let</span> init_message = Message {
        id: init.id,
        content: init.content,
    };

    <span class="hljs-keyword">unsafe</span> { MESSAGES.push(init_message) };
    msg::reply_bytes(<span class="hljs-string">"Successfully initialized"</span>, <span class="hljs-number">0</span>).expect(<span class="hljs-string">"Failed to initialize successfully."</span>);
}
</code></pre>
<p>The <code>init</code> function is the entry point for initializing the smart contract. It is marked with <code>#[no_mangle]</code> to prevent Rust from applying name mangling, making the function accessible from the smart contract runtime. </p>
<p>The function begins by loading the initial message from the input payload using <code>msg::load()</code>. This message is expected to be of type <code>Message</code>, and if decoding fails, the function will panic with an error message. Next, a new <code>Message</code> instance is created from the loaded data. This new message is then added to the global <code>MESSAGES</code> vector, which is a mutable static variable marked as unsafe due to potential data races. Finally, the function sends a reply indicating successful initialization using <code>msg::reply_bytes</code>. If this reply fails, the function will panic.</p>
<h3 id="heading-message-handling-function-handle">Message Handling Function (<code>handle</code>)</h3>
<pre><code class="lang-rust"><span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">handle</span></span>() {
    <span class="hljs-keyword">let</span> message_handler: Message = msg::load().expect(<span class="hljs-string">"Unable to decode Message"</span>);
    <span class="hljs-keyword">let</span> message = Message {
        id: message_handler.id,
        content: message_handler.content,
    };
    <span class="hljs-keyword">unsafe</span> { MESSAGES.push(message) };
    msg::reply_bytes(<span class="hljs-string">"Message sent successfully."</span>, <span class="hljs-number">0</span>).expect(<span class="hljs-string">"Failed to send  reply message."</span>);
}
</code></pre>
<p>The <code>handle</code> function is designed to handle incoming messages after the contract is deployed. Like the <code>init</code> function, it is marked with <code>#[no_mangle]</code> to ensure it can be called from the smart contract runtime. The function begins by loading the incoming message from the input payload. This message is decoded into a <code>Message</code> struct, and if decoding fails, the function will panic. </p>
<p>A new <code>Message</code> instance is then created from the decoded data and added to the global <code>MESSAGES</code> vector using an unsafe block. The function then sends a reply indicating that the message was sent successfully. If the reply fails, the function will panic.</p>
<h3 id="heading-state-query-function-state">State Query Function (<code>state</code>)</h3>
<pre><code class="lang-rust"><span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">state</span></span>() {
    msg::reply(<span class="hljs-keyword">unsafe</span> { MESSAGES.clone() }, <span class="hljs-number">0</span>).expect(<span class="hljs-string">"Failed to share state"</span>);
}
</code></pre>
<p>The <code>state</code> function allows querying the current state of the smart contract. It is also marked with <code>#[no_mangle]</code> for the same reasons as the previous functions. The function replies with a cloned version of the global <code>MESSAGES</code> vector, containing all the messages that have been added so far. This is done within an unsafe block due to the mutable static variable. If the function fails to send the state, it will panic.</p>
<p>So this code simply defines a smart contract with three main functions: <code>init</code> for initialization, <code>handle</code> for processing incoming messages, and <code>state</code> for querying the current state of the contract. Where each function carefully manages the global <code>MESSAGES</code> vector.</p>
<h3 id="heading-deployment-on-the-vara-network">Deployment on the Vara Network</h3>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.loom.com/share/e967ebf211f54f2c9c85fedc593e427e?sid=3ef6709a-8b5a-412b-b80c-93f721ba135b">https://www.loom.com/share/e967ebf211f54f2c9c85fedc593e427e?sid=3ef6709a-8b5a-412b-b80c-93f721ba135b</a></div>
<p>Now you're done with this project, and hope you learned and have understood most of what I've written. In our next project, you'll be building something a bit more complex than this. So let's begin.</p>
<p><a target="_blank" href="https://idea.gear-tech.io/programs/0x58acd467aa011554b0dc167f741e745b336a03943df6f1eba635e9c28ca9824e">Here is the program deployed on Vara Network</a>, and this is the <a target="_blank" href="https://github.com/rockyessel/freecodecamp-gear-protocol">entire repository for the 3 projects</a> we've built so far. The next project is going to be stand-alone project so you won't use the workspace.</p>
<h2 id="heading-final-project">Final Project</h2>
<p>In this final project, you'll build a very simple game: where you (<code>player</code>) fights with the <code>boss</code>. So here is a simple layman's explanation of the game mechanics.</p>
<h3 id="heading-game-description">Game Description</h3>
<p>This game is a one-on-one battle between a player and a boss. To begin, the player selects their character from three options: Warrior, Mage, or Archer. Once the player's character data is stored in the program, the game begins.</p>
<p>In the game, the player immediately faces the boss, who starts with 10 lives (represented as an integer), while the player begins with 10 lives by default. The objective is to defeat the boss using a specific rule: the boss has weaknesses represented by letters (X, Y, Z), each associated with a random number.</p>
<p>During gameplay, if the player enters one of these letters, for example, 'Y' with a value of 4, and the boss starts with 0 lives, the program subtracts 4 lives from the boss, leaving 6. Similarly, when the player makes a move with a letter, the boss also makes a move with the a random letter with an associated value added to it.</p>
<p>The player progresses to the next level upon defeating the boss, continuing the battle with new challenges. I call this game Battle Showdown <strong>🤣😁😂.</strong></p>
<h3 id="heading-battle-showdown-mechanics-summary"><strong>Battle Showdown</strong> Mechanics Summary</h3>
<h4 id="heading-player-and-boss-lives">Player and Boss Lives</h4>
<ul>
<li>Player starts with 10 lives.</li>
<li>Boss starts with 10 lives.</li>
</ul>
<h4 id="heading-weaknesses-and-values">Weaknesses and Values</h4>
<ul>
<li>Boss and the player has weaknesses represented by letters ( <code>X</code>, <code>Y</code>, <code>Z</code>), each associated with a random number.</li>
</ul>
<h4 id="heading-gameplay">Gameplay</h4>
<ul>
<li>Player inputs a letter (for example, <code>'Y'</code>) and the associated value (for example, <code>4</code>) is subtracted from the boss's lives.</li>
<li>Boss retaliates with a letter and the same value is subtracted from the player's lives.</li>
<li>The objective is for the player to reduce the boss's lives to 0 to progress to the next level.</li>
</ul>
<h3 id="heading-match-equation">Match Equation</h3>
<p>Let's define the key variables:</p>
<ul>
<li>(<code>Lp</code>) = Player's current lives.</li>
<li>(<code>Lb</code>) = Boss's current lives.</li>
<li>(<code>V</code>) = Value associated with the letter representing the attack.</li>
</ul>
<p><strong>Initial conditions:</strong></p>
<ul>
<li>( <code>Lp</code> = 10 )</li>
<li>( <code>Lb</code> = 10 )</li>
</ul>
<p><strong>Player's turn:</strong></p>
<ul>
<li>Player selects a letter with an associated value (<code>V</code>).</li>
<li>Boss's lives are reduced: (<code>Lb</code> = <code>Lb</code> - <code>V</code>).</li>
</ul>
<p><strong>Boss's retaliation:</strong></p>
<ul>
<li>Boss selects a letter (same value (<code>V</code>)).</li>
<li>Player's lives are reduced: (<code>Lp</code> = <code>Lp</code> - <code>V</code>).</li>
</ul>
<p>This continues until either ( <code>Lb</code> ) (boss's lives) or ( <code>Lp</code> ) (player's lives) reaches 0.</p>
<h3 id="heading-equations">Equations</h3>
<p>After the player's attack and the Boss's retaliation:<br>[<code>Lb</code> = <code>Lb</code> - <code>V</code>]<br>[<code>Lp</code> = <code>Lp</code> - <code>V</code>]</p>
<p>The game loop continues with the player and boss exchanging moves. Repeat until <code>Lb</code> <code>&lt;= 0</code> or <code>Lp</code> <code>&lt;= 0</code></p>
<h3 id="heading-example">Example</h3>
<p>If the player inputs <code>'Y'</code> with a value of <code>4</code>:</p>
<ul>
<li>Initial: ( <code>Lp</code> = 10 ), ( <code>Lb</code> = 10 )</li>
<li>Player's attack: ( <code>Lb</code> = 10 - 4 = 6 )</li>
<li>Boss's retaliation: ( <code>Lp</code> = 10 - 4 = 6 )</li>
</ul>
<p>Next move:</p>
<ul>
<li>If the player inputs another value, let's say: <code>'X'</code> with a value of <code>5</code>:</li>
<li>Player's attack: ( <code>Lb</code> = 6 - 5 = 1 )</li>
<li>Boss's retaliation: ( <code>Lp</code> = 6 - 5 = 1 )</li>
</ul>
<p>The player wins as the Boss's lives ( <code>Lb</code> ) have reached 0.</p>
<p>The match equation for each round of the game can be summarized as:<br>[<code>Lb</code> = <code>Lb</code> - <code>V</code>]<br>[<code>Lp</code> = <code>Lp</code> - <code>V</code>]<br>This process is repeated until either the player's lives (( <code>Lp</code> )) or the Boss's lives (( <code>Lb</code> )) reach 0, determining the winner of the battle.</p>
<h3 id="heading-windows-error">Windows Error</h3>
<p>If you use Windows, you may encounter an error with the <strong>link.exe</strong>. Honestly, I cannot explain the reason behind the error, but in the Gear docs, it was made clear that Windows users might experience some problems when building their project.</p>
<p>But rest assured, there's a solution, and I'm going to guide you through it. So please follow these steps carefully so you don't have to deal with bugs along the way.</p>
<h3 id="heading-step-1-install-wsl-via-command-prompt">Step 1 - Install WSL via Command Prompt</h3>
<p>Open your CLI with administrative privileges, and run the command below:</p>
<pre><code class="lang-bash">wsl --install
</code></pre>
<p>After excutting the command, run the command below to list other Linux releases. </p>
<pre><code class="lang-bash">wsl -l -o
</code></pre>
<p>This command shows a list of other Linux distros, and you can select anyone you've used before. If you're new to Linux distros, I recommend selecting the <code>Ubuntu-22.04</code>.</p>
<p>These are just lists and are read-only. In order to select your system, run the command below.</p>
<pre><code class="lang-bash">wsl --install -d {Distribtion Name here(Ubuntu-22.04)}
</code></pre>
<p>After you're done with the installation, restart your PC. Wait a little while for the terminal to popup and prompt you for your details such as your username and password. If the terminal doesn't open, go to your start menu, and you will find something similar to this in your <code>Start</code> menu.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/image-6.png" alt="Image" width="600" height="400" loading="lazy">
<em>Ubuntu in start menu</em></p>
<p>After that, the next thing to do is to install Rust on your WSL. </p>
<h3 id="heading-how-to-install-rust-on-your-wsl">How to Install Rust On Your WSL</h3>
<p>To install Rust on your machine, I recommend that whenever you want to install any package, it is best practice to install updates and upgrades to the system before continuing with the installation.</p>
<pre><code class="lang-bash">sudo apt update &amp;&amp; sudo apt upgrade -y
</code></pre>
<p>When you run <code>sudo apt update &amp;&amp; sudo apt upgrade -y</code>, you first update the package lists to get the latest information about available software packages. Then, if the update is successful, it proceeds to upgrade the installed packages to their latest versions, automatically confirming the upgrades to avoid manual intervention. This is a common and recommended practice to keep your Linux system up-to-date and secure.</p>
<h3 id="heading-essential-dependencies">Essential Dependencies.</h3>
<p>The command below installs essential development tools (<code>build-essential</code>, <code>gcc</code>, and <code>make</code>) and the <code>curl</code> utility for making HTTP requests and downloading files. These packages are commonly required for software development, compilation, and system administration tasks.</p>
<pre><code class="lang-bash"> sudo apt install curl build-essential gcc make -y
</code></pre>
<p>After that, run the command in the terminal  </p>
<pre><code class="lang-bash"> curl --proto <span class="hljs-string">'=https'</span> --tlsv1.2 -sSf https://sh.rustup.rs | sh
</code></pre>
<p>In the installation process, you'll be prompted a question: go with the <code>default</code> when it happens.</p>
<pre><code class="lang-bash">1. Proceed with installation (default) --&gt; Enter
2. Customize installation
3. Cancel installation.
</code></pre>
<p>After this prompt, you have successfully installed Rust on the Ubuntu System. Now the next step is to restart your terminal, simply close the current terminal. Open a new one, and run the command below.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> <span class="hljs-string">"<span class="hljs-variable">$HOME</span>/.cargo/env"</span>
</code></pre>
<p>What this command source <code>"$HOME/.cargo/env"</code> does is to activate the Rust environment. The reason is that the Rust environment comprises essential variables and configurations required for effective Rust usage. Now, once run, there's no output, so you can verify the installation by running the command below.</p>
<pre><code class="lang-bash"> rustc -V
</code></pre>
<p>Expected output:</p>
<pre><code class="lang-bash">rockyessel@UBUNTU-ROCKY:~$ rustc -V rustc 1.73.0 (cc66ad468 2024-02-07)
</code></pre>
<p>When you're done, there're also additional dependencies we have to install. So here, install them.</p>
<pre><code class="lang-bash">// Install the following.

 --&gt; rustup toolchain add nightly-2023-09-18
 --&gt; rustup target add wasm32-unknown-unknown --toolchain nightly-2023-09-18
</code></pre>
<p>After successfully installing them, head to the next section, which is building a game project.</p>
<p>In your WSL terminal, create your project name <code>battle-showdown</code>, and adding all the necessary <strong>toml</strong> files, and dependences. After that, <code>cd</code> into your project <code>battle-showdown</code> and added another program called <strong>io</strong>, this is where you write your metadate and other complex or simple data-type for your dApp.</p>
<pre><code class="lang-bash">battle-showdown
.
├── Cargo.toml
├── io
│   ├── Cargo.toml
│   └── src
│       └── lib.rs
└── src
    └── lib.rs
</code></pre>
<p>So head-over to to your <strong>./io/src/lib.rs</strong> and paste the follow code:</p>
<pre><code class="lang-bash"><span class="hljs-comment">#![no_std]</span>

use gmeta::Metadata;

pub struct BattleShowdown;

impl Metadata <span class="hljs-keyword">for</span> BattleShowdown {
    <span class="hljs-built_in">type</span> Init = ();
    <span class="hljs-built_in">type</span> Handle = ();
    <span class="hljs-built_in">type</span> State = ();
    <span class="hljs-built_in">type</span> Reply = ();
    <span class="hljs-built_in">type</span> Others = ();
    <span class="hljs-built_in">type</span> Signal = ();
}
</code></pre>
<p>Here, you have defined a new public struct named <code>BattleShowdown</code>. Structs are used to create custom data types by grouping fields of various types together. But in this case, you're providing an implementation for the required types of the <code>Metadata</code> trait for the <code>BattleShowdown</code> struct: <code>impl Metadata for BattleShowdown</code>.</p>
<p><code>type Init = ()</code>, <code>type Handle = ()</code>, <code>type State = ()</code>, <code>type Reply = ()</code>, <code>type Others = ()</code>, and <code>type Signal = ()</code> specifies that the handlers or functions data type for <code>BattleShowdown</code> is of type <code>()</code>, which in Rust's unit type, equivalent to <code>void</code> in other language such as <code>TypeScript</code>.</p>
<p>So for now, we're saying that these handlers do not send or receive data as such. Hence, the code just specifies how <code>BattlwShowdown</code> interacts with the system. However, it is worth mentioning that, the <code>BattleShowdown</code> struct itself doesn't have any specific initialization data, state, handling behavior, replies, signals, or other associated types defined.</p>
<h3 id="heading-building-our-game">Building Our Game</h3>
<p>First off, let's make register the <strong>io</strong> in your parent directory <strong>cargo.toml</strong>. So head over to <code>./cargo.toml</code> and paste the code below:</p>
<pre><code class="lang-toml"><span class="hljs-attr">workspace</span> = { members = [<span class="hljs-string">"io"</span>] }
<span class="hljs-section">[package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"battle-showdown"</span>
<span class="hljs-attr">version</span> = <span class="hljs-string">"0.1.0"</span>
<span class="hljs-attr">edition</span> = <span class="hljs-string">"2021"</span>

<span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">gstd</span> = <span class="hljs-string">"1.4.1"</span>
<span class="hljs-attr">battle-showdown-io</span>={path = <span class="hljs-string">"io"</span>}



<span class="hljs-section">[build-dependencies]</span>
<span class="hljs-attr">gear-wasm-builder</span> = <span class="hljs-string">"1.4.1"</span>
<span class="hljs-attr">battle-showdown-io</span>={path = <span class="hljs-string">"io"</span>}
</code></pre>
<p>I've ensured that the "battle-showdown-io" path is included in both the dependencies and build-dependencies sections. This decision was intentional because when it's added solely to build-dependencies, only the structs, enums, and other data types or functions within the build.rs file gain access to them, not the dependencies in your <strong><code>./src/lib.rs</code></strong>. This is important because I'll be utilizing <code>battle-showdown-io</code> in both build-dependencies (<code>build.rs</code>) and dependencies (<code>./src/lib.rs</code>).</p>
<p>This step is crucial because overlooking it can lead to frustrating import errors.</p>
<p>Next, is the file <strong><code>./io/cargo.toml</code></strong>, paste the following code below.</p>
<pre><code class="lang-toml"><span class="hljs-section">[package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"battle-showdown-io"</span>
<span class="hljs-attr">version</span> = <span class="hljs-string">"0.1.0"</span>
<span class="hljs-attr">edition</span> = <span class="hljs-string">"2021"</span>

<span class="hljs-comment"># See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html</span>

<span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">gstd</span> = <span class="hljs-string">"1.4.1"</span>
<span class="hljs-attr">gmeta</span> = <span class="hljs-string">"1.4.1"</span>
<span class="hljs-attr">parity-scale-codec</span> = { version = <span class="hljs-string">"3.6.12"</span>, default-features = <span class="hljs-literal">false</span> }
<span class="hljs-attr">scale-info</span> = { version = <span class="hljs-string">"2.11.3"</span>, default-features = <span class="hljs-literal">false</span> }
</code></pre>
<h3 id="heading-explaining-metadata-for-battleshown">Explaining Metadata For BattleShown</h3>
<p>It's crucial to pay closer attention to this section, as I'll shed more light on explaining the metadata types for <code>BattleShown</code> and deploying it on the Vara Network.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#![no_std]</span>

<span class="hljs-keyword">use</span> gmeta::Metadata;

<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BattleShowdown</span></span>;

<span class="hljs-keyword">impl</span> Metadata <span class="hljs-keyword">for</span> BattleShowdown {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Init</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Handle</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">State</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Reply</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Others</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Signal</span></span> = ();
}
</code></pre>
<h3 id="heading-defining-initialization-init">Defining Initialization – <code>Init</code></h3>
<p>To define the types for this purpose, consider whether your program or smart contract needs to store data or perform actions before the user can interact with it. In the case of this game, the answer is yes. </p>
<p>The game assumes that only one person is playing and does not allow users to create their characters or players. This means that you need to store data before proceeding to use this program, and in this scenario, we need information about the person/developer/actor/user deploying the contract or program, which is you.</p>
<p>Here is the information you'll want to store:</p>
<ul>
<li><strong>playerId - Type: ActorId</strong><br>The playerId is actually the address associated with your account, which has the type of <code>ActorId</code>.</li>
<li><strong>playerName - Type: String</strong><br>This has a type of string, pretty much straightforward.</li>
<li><strong>playerCharacterType - Type: Enum</strong><br>The <code>playerCharacterType</code> is an enum that gives the actor an option to select which type they want to be, with options including Mage, Warrior, and Archer.</li>
</ul>
<pre><code class="lang-rust"><span class="hljs-meta">#![no_std]</span>

<span class="hljs-keyword">use</span> gmeta::Metadata;

<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BattleShowdown</span></span>;

<span class="hljs-keyword">impl</span> Metadata <span class="hljs-keyword">for</span> BattleShowdown {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Init</span></span> = InOut&lt;InitBattleShowdown, <span class="hljs-built_in">String</span>&gt;;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Handle</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">State</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Reply</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Others</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Signal</span></span> = ();
}

<span class="hljs-meta">#[derive(Debug, Clone, Copy, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">CharacterType</span></span> {
    Warrior,
    Mage,
    Archer,
}


<span class="hljs-meta">#[derive(Default, Debug, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">InitBattleShowdown</span></span> {
    <span class="hljs-keyword">pub</span> player_id: ActorId,
    <span class="hljs-keyword">pub</span> player_character_type: CharacterType,
    <span class="hljs-keyword">pub</span> player_name: <span class="hljs-built_in">String</span>,
}
</code></pre>
<p>Although I've previously discussed metadata, you might be curious about what <code>type Init = InOut&lt;InitBattleShowdown, String&gt;;</code> means. Well, it's nothing complex. Here, we're simply stating that the <code>init</code> handle will accept a data type of <code>InitBattleShowdown</code> and will respond with a data type of <code>String</code>.</p>
<p>Before you continue, one more step remains: implementing a <code>default trait</code> for the enum <code>CharacterType</code>. This ensures that if the <code>CharacterType</code> is not explicitly defined, it defaults to <code>Warrior</code>. Simply add the following code to the existing code above:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> <span class="hljs-built_in">Default</span> <span class="hljs-keyword">for</span> CharacterType {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">default</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
        CharacterType::Warrior
    }
}
</code></pre>
<h3 id="heading-defining-the-handle">Defining the <code>Handle</code></h3>
<p>Defining a type for the <code>handle</code> function mirrors the process for the <code>init</code> function, but the actual implementation is left to the developer, which in this case, is you. After reviewing code and experimenting with different approaches, I discovered a method used by Gear Protocol (which shares similarities with some of their projects) that made more sense.</p>
<h3 id="heading-action-amp-event">Action &amp; Event</h3>
<p>In their implementation, they utilized Actions and Events. Actions represent a set of operations that the program can perform, while Events are the outcomes of these Actions.</p>
<p>For example, in the context of this game, you could have an action named <code>Attack</code> with a corresponding Event named <code>Attacked</code>. These could potentially accept parameters and return results.</p>
<p>Therefore, to define the handle type, include the following code in your existing codebase:</p>
<pre><code class="lang-rust">
<span class="hljs-meta">#[derive(Debug, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">BattleShowdownAction</span></span> {
    Attack {
        character_hit_power_value: PlayerHitPowerValue,
    },
}
</code></pre>
<p>Previously, when describing the game mechanics, I introduced a mechanic involving a letter with a randomly assigned number to inject an element of randomness. In this context, these letters correspond to an <code>ENUM</code> state of <code>X</code>, <code>Z</code>, and <code>Y</code>.</p>
<p>Therefore, to implement this mechanic, add the following code:</p>
<pre><code class="lang-rust">...

<span class="hljs-meta">#[derive(Debug, Clone, Copy, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">PlayerHitPowerValue</span></span> {
    X,
    Y,
    Z,
}
</code></pre>
<p>When an actor or user decides to attack the boss, they can select from the options provided above, each with a random value. Consequently, each attack on the boss will yield different outcomes due to the variability in these values. Similar to how you implemented a default trait for the <code>CharacterType</code>, you should follow suit here.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> <span class="hljs-built_in">Default</span> <span class="hljs-keyword">for</span> PlayerHitPowerValue {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">default</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
        PlayerHitPowerValue::X
    }
}
</code></pre>
<h3 id="heading-event">Event</h3>
<p>As mentioned earlier, events are the outcomes of actions. Unlike the <code>BattleShowdownAction</code>, which only had one action, the <code>BattleShowdownEvent</code> will encompass more than two actions. Why? Because the game's logic dictates that when the user attacks, the boss also counterattacks. This results in three possible outcomes: either the user loses, the boss is defeated, or the battle continues. </p>
<p>However, the third outcome is contingent upon the first two outcomes.<br>Therefore, for the <code>BattleShowdownEvent</code>, you will need to define:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">BattleShowdownEvent</span></span> {
    Attacked {
        id: ActorId,
        character_type: CharacterType,
        name: <span class="hljs-built_in">String</span>,
        player_lives: <span class="hljs-built_in">u32</span>,
        boss_livesL: <span class="hljs-built_in">u32</span>,
    },

    PlayerLost {
        id: ActorId,
        character_type: CharacterType,
        boss_livesL: <span class="hljs-built_in">u32</span>,
        player_lives: <span class="hljs-built_in">u32</span>,
        message: <span class="hljs-built_in">String</span>,
    },

    BossLost {
        character_type: CharacterType,
        player_lives: <span class="hljs-built_in">u32</span>,
        boss_livesL: <span class="hljs-built_in">u32</span>,
        message: <span class="hljs-built_in">String</span>,
    },
}
</code></pre>
<p>You have one action, but there are three possible events, correct? When the user/actor attacks the boss and the boss counterattacks, if either of them is defeated, the "Attacked" event is returned. However, if the player successfully defeats the boss, the "BossLost" event is returned.<br>Now that you have a solid understanding, let's incorporate both the input and output types for the Handle function: <code>type Handle = InOut&lt;BattleShowdownAction, BattleShowdownEvent&gt;;</code>.</p>
<h3 id="heading-defining-state">Defining <code>State</code></h3>
<p>As previously mentioned, the state stores information within your program. For <code>BattleShowdown</code>, the state you'd want to store includes information about the player, the boss, and the current level.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Default, Debug, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BattleShowdownState</span></span> {
    <span class="hljs-keyword">pub</span> player_id: ActorId,
    <span class="hljs-keyword">pub</span> player_character_type: CharacterType,
    <span class="hljs-keyword">pub</span> current_level: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> player_lives: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> player_name: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> boss_lives: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> player_hit_power: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> boss_hit_power: <span class="hljs-built_in">u32</span>,
}
</code></pre>
<p>Therefore, whenever you call the state function, you should expect to see the result in this format. Now, add the <code>BattleShowdownState</code> to the state in the metadata, like so: <code>type State = Out&lt;BattleShowdownState&gt;;</code>.</p>
<p>With that, the setup is complete. Here is the entire code for the <strong>./io/src/lib.rs</strong> file.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#![no_std]</span>

<span class="hljs-keyword">use</span> gmeta::{In, InOut, Metadata, Out};
<span class="hljs-keyword">use</span> gstd::{prelude::*, ActorId};

<span class="hljs-comment">// Define the main struct for the BattleShowdown</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BattleShowdown</span></span>;

<span class="hljs-comment">// Implementing Metadata for BattleShowdown</span>
<span class="hljs-keyword">impl</span> Metadata <span class="hljs-keyword">for</span> BattleShowdown {
    <span class="hljs-comment">// Define the type for initialization messages</span>
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Init</span></span> = InOut&lt;InitBattleShowdown, <span class="hljs-built_in">String</span>&gt;;
    <span class="hljs-comment">// Define the type for handle messages</span>
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Handle</span></span> = InOut&lt;BattleShowdownAction, BattleShowdownEvent&gt;;
    <span class="hljs-comment">// Define the type for state messages</span>
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">State</span></span> = Out&lt;BattleShowdownState&gt;;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Reply</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Others</span></span> = ();
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Signal</span></span> = ();
}

<span class="hljs-comment">// Struct for initializing the BattleShowdown</span>
<span class="hljs-meta">#[derive(Default, Debug, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">InitBattleShowdown</span></span> {
    <span class="hljs-keyword">pub</span> player_id: ActorId,
    <span class="hljs-keyword">pub</span> player_character_type: CharacterType,
    <span class="hljs-keyword">pub</span> player_name: <span class="hljs-built_in">String</span>,
}

<span class="hljs-comment">// Struct representing the state of the BattleShowdown</span>
<span class="hljs-meta">#[derive(Default, Debug, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BattleShowdownState</span></span> {
    <span class="hljs-keyword">pub</span> player_id: ActorId,
    <span class="hljs-keyword">pub</span> player_character_type: CharacterType,
    <span class="hljs-keyword">pub</span> current_level: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> player_lives: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> player_name: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> boss_lives: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> player_hit_power: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> boss_hit_power: <span class="hljs-built_in">u32</span>,
}

<span class="hljs-comment">// Enum representing different character types</span>
<span class="hljs-meta">#[derive(Debug, Clone, Copy, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">CharacterType</span></span> {
    Warrior,
    Mage,
    Archer,
}

<span class="hljs-comment">// Enum representing different values for player hit power</span>
<span class="hljs-meta">#[derive(Debug, Clone, Copy, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">PlayerHitPowerValue</span></span> {
    X,
    Y,
    Z,
}

<span class="hljs-comment">// Implementing Default for PlayerHitPowerValue</span>
<span class="hljs-keyword">impl</span> <span class="hljs-built_in">Default</span> <span class="hljs-keyword">for</span> PlayerHitPowerValue {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">default</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
        PlayerHitPowerValue::X
    }
}

<span class="hljs-comment">// Implementing Default for CharacterType</span>
<span class="hljs-keyword">impl</span> <span class="hljs-built_in">Default</span> <span class="hljs-keyword">for</span> CharacterType {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">default</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
        CharacterType::Warrior
    }
}

<span class="hljs-comment">// Enum representing different actions in the BattleShowdown</span>
<span class="hljs-meta">#[derive(Debug, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">BattleShowdownAction</span></span> {
    Attack {
        character_hit_power_value: PlayerHitPowerValue,
    },
}

<span class="hljs-comment">// Enum representing different events in the BattleShowdown</span>
<span class="hljs-meta">#[derive(Debug, Encode, Decode, TypeInfo)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">BattleShowdownEvent</span></span> {
    Attacked {
        id: ActorId,
        character_type: CharacterType,
        name: <span class="hljs-built_in">String</span>,
        player_lives: <span class="hljs-built_in">u32</span>,
        boss_lives: <span class="hljs-built_in">u32</span>,
    },
    PlayerLost {
        id: ActorId,
        character_type: CharacterType,
        boss_lives: <span class="hljs-built_in">u32</span>,
        player_lives: <span class="hljs-built_in">u32</span>,
        message: <span class="hljs-built_in">String</span>,
    },
    BossLost {
        character_type: CharacterType,
        player_lives: <span class="hljs-built_in">u32</span>,
        boss_lives: <span class="hljs-built_in">u32</span>,
        message: <span class="hljs-built_in">String</span>,
    },
}
</code></pre>
<h3 id="heading-buildrs"><code>Build.rs</code></h3>
<p>Import <code>BattleShowdown</code> to the <strong>build.rs</strong> from your parent directory at <strong>./src/build.rs</strong>. If you encounter an import error, make sure that in your <strong>./cargo.toml</strong>, you're registering <code>battle-showdown-io={path = "io"}</code> there.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> battle_showdown_io::BattleShowdown;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    gear_wasm_builder::build_with_metadata::&lt;BattleShowdown&gt;();
}
</code></pre>
<p>That's it for the <strong>build.rs</strong>, and what it does is to build your project into <code>wasm</code> and then build the <code>metadata</code> for <code>BattleShown</code> for you.</p>
<h3 id="heading-game-logic-implementation-srclibrs">Game Logic Implementation - <code>./src/lib.rs</code></h3>
<p>For this section, I'll write the code below, then I'll explain this as we go. There's going to be a problem I'd want you to solve, which will be about the state.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#![no_std]</span>

<span class="hljs-keyword">use</span> gstd::{exec, msg, prelude::*, ActorId};

<span class="hljs-keyword">use</span> battle_showdown_io::*;

<span class="hljs-comment">// Function to generate random number between 1 and 3</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_random_u32</span></span>() -&gt; <span class="hljs-built_in">u32</span> {
    <span class="hljs-keyword">let</span> salt = msg::id();
    <span class="hljs-keyword">let</span> (hash, _num) = exec::random(salt.into()).expect(<span class="hljs-string">"get_random_u32(): random call failed"</span>);
    (<span class="hljs-built_in">u32</span>::from_le_bytes([hash[<span class="hljs-number">0</span>], hash[<span class="hljs-number">1</span>], hash[<span class="hljs-number">2</span>], hash[<span class="hljs-number">3</span>]]) % <span class="hljs-number">3</span>) + <span class="hljs-number">1</span> <span class="hljs-comment">// Generate random number between 1 and 3</span>
}

<span class="hljs-meta">#[derive(Debug, Default)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BattleShowdown</span></span> {
    <span class="hljs-keyword">pub</span> player_id: ActorId,
    <span class="hljs-keyword">pub</span> player_character_type: CharacterType,
    <span class="hljs-keyword">pub</span> current_level: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> player_lives: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> player_name: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> boss_lives: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> character_hit_power_value: PlayerHitPowerValue,
    <span class="hljs-keyword">pub</span> player_hit_power: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> boss_hit_power: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> game_state: <span class="hljs-built_in">String</span>,
}

<span class="hljs-keyword">static</span> <span class="hljs-keyword">mut</span> BATTLESHOWNDOWN: <span class="hljs-built_in">Option</span>&lt;BattleShowdown&gt; = <span class="hljs-literal">None</span>;

<span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">unsafe</span> <span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">init</span></span>() {
    <span class="hljs-keyword">let</span> init: InitBattleShowdown = msg::load().expect(<span class="hljs-string">"Unable to decode InitBattleShowdown"</span>);

    <span class="hljs-keyword">let</span> battle_showdown = BattleShowdown {
        player_id: msg::source(),
        player_character_type: init.player_character_type,
        player_name: init.player_name,
        boss_lives: <span class="hljs-number">10</span>,
        player_lives: <span class="hljs-number">10</span>,
        ..<span class="hljs-built_in">Default</span>::default()
    };

    BATTLESHOWNDOWN = <span class="hljs-literal">Some</span>(battle_showdown);

    msg::reply_bytes(<span class="hljs-string">"Successfully initialized"</span>, <span class="hljs-number">0</span>).expect(<span class="hljs-string">"Failed to initialize successfully."</span>);
}

<span class="hljs-keyword">impl</span> Encode <span class="hljs-keyword">for</span> BattleShowdown {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">encode</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt; {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> encoded = <span class="hljs-built_in">Vec</span>::new();

        <span class="hljs-comment">// Encode each field of BattleShowdown struct</span>
        encoded.extend_from_slice(&amp;<span class="hljs-keyword">self</span>.player_id.encode());
        encoded.extend_from_slice(&amp;<span class="hljs-keyword">self</span>.player_character_type.encode());
        encoded.extend_from_slice(&amp;<span class="hljs-keyword">self</span>.current_level.encode());
        encoded.extend_from_slice(&amp;<span class="hljs-keyword">self</span>.player_lives.encode());
        encoded.extend_from_slice(&amp;<span class="hljs-keyword">self</span>.player_name.encode());
        encoded.extend_from_slice(&amp;<span class="hljs-keyword">self</span>.boss_lives.encode());
        encoded.extend_from_slice(&amp;<span class="hljs-keyword">self</span>.character_hit_power_value.encode());
        encoded.extend_from_slice(&amp;<span class="hljs-keyword">self</span>.player_hit_power.encode());
        encoded.extend_from_slice(&amp;<span class="hljs-keyword">self</span>.boss_hit_power.encode());
        encoded.extend_from_slice(&amp;<span class="hljs-keyword">self</span>.game_state.encode());

        encoded
    }
}

<span class="hljs-keyword">impl</span> BattleShowdown {
    <span class="hljs-comment">// Placeholder for the `attack` method</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">attack</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, _character_hit_power_value: PlayerHitPowerValue) -&gt; BattleShowdownEvent {
        <span class="hljs-comment">// Implement this method according to your game logic</span>
        <span class="hljs-comment">// For now, just returning an empty event</span>

        <span class="hljs-comment">// Calculate total hit power for player based on character type and random values</span>
        <span class="hljs-keyword">let</span> character_hit_power = <span class="hljs-keyword">match</span> &amp;<span class="hljs-keyword">self</span>.player_character_type {
            CharacterType::Warrior =&gt; <span class="hljs-number">4</span>,
            CharacterType::Mage =&gt; <span class="hljs-number">3</span>,
            CharacterType::Archer =&gt; <span class="hljs-number">2</span>,
        };

        <span class="hljs-keyword">let</span> player_hit_power = <span class="hljs-keyword">match</span> &amp;<span class="hljs-keyword">self</span>.character_hit_power_value {
            PlayerHitPowerValue::X =&gt; character_hit_power + get_random_u32(),
            PlayerHitPowerValue::Y =&gt; character_hit_power + get_random_u32(),
            PlayerHitPowerValue::Z =&gt; character_hit_power + get_random_u32(),
        };

        <span class="hljs-comment">// Placeholder for boss attack logic</span>
        <span class="hljs-comment">// Update boss hit power to a random value for each attack</span>
        <span class="hljs-keyword">self</span>.boss_hit_power = get_random_u32();

        <span class="hljs-keyword">self</span>.player_hit_power = player_hit_power;

        <span class="hljs-comment">// Reduce boss's lives based on player's hit power</span>
        <span class="hljs-keyword">self</span>.boss_lives = <span class="hljs-keyword">self</span>.boss_lives.saturating_sub(<span class="hljs-keyword">self</span>.player_hit_power);
        <span class="hljs-comment">// Reduce player's lives based on boss's hit power</span>
        <span class="hljs-keyword">self</span>.player_lives = <span class="hljs-keyword">self</span>.player_lives.saturating_sub(<span class="hljs-keyword">self</span>.boss_hit_power);

        <span class="hljs-comment">// Check if player or boss has lost</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.player_lives == <span class="hljs-number">0</span> {
            <span class="hljs-comment">// Player lost</span>
            <span class="hljs-keyword">self</span>.game_state = <span class="hljs-string">"Player lost."</span>.to_string();
            <span class="hljs-keyword">return</span> BattleShowdownEvent::PlayerLost {
                id: <span class="hljs-keyword">self</span>.player_id,
                boss_lives: <span class="hljs-keyword">self</span>.boss_lives,
                character_type: <span class="hljs-keyword">self</span>.player_character_type,
                message: <span class="hljs-string">""</span>.to_string(),
                player_lives: <span class="hljs-keyword">self</span>.player_lives,
            };
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.boss_lives == <span class="hljs-number">0</span> {
            <span class="hljs-comment">// Boss lost</span>
            <span class="hljs-keyword">self</span>.game_state = <span class="hljs-string">"Boss lost."</span>.to_string();
            <span class="hljs-keyword">return</span> BattleShowdownEvent::BossLost {
                boss_lives: <span class="hljs-keyword">self</span>.boss_lives,
                character_type: <span class="hljs-keyword">self</span>.player_character_type,
                player_lives: <span class="hljs-keyword">self</span>.player_lives,
                message: <span class="hljs-string">"You've defeated the boos"</span>.to_string(),
            };
        }

        <span class="hljs-keyword">self</span>.game_state = <span class="hljs-string">"The games continues."</span>.to_string();
        BattleShowdownEvent::Attacked {
            boss_lives: <span class="hljs-keyword">self</span>.boss_lives,
            character_type: <span class="hljs-keyword">self</span>.player_character_type,
            id: <span class="hljs-keyword">self</span>.player_id,
            name: <span class="hljs-keyword">self</span>.player_name.clone(),
            player_lives: <span class="hljs-keyword">self</span>.player_lives,
        }
    }
}

<span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">handle</span></span>() {
    <span class="hljs-keyword">let</span> battle_showdown_action: BattleShowdownAction =
        msg::load().expect(<span class="hljs-string">"Could not load BattleShowdownAction"</span>);
    <span class="hljs-keyword">let</span> battle_showdown = <span class="hljs-keyword">unsafe</span> {
        BATTLESHOWNDOWN
            .as_mut()
            .expect(<span class="hljs-string">"`BattleShowdown` is not initialized."</span>)
    };
    <span class="hljs-keyword">let</span> result: BattleShowdownEvent = <span class="hljs-keyword">match</span> battle_showdown_action {
        BattleShowdownAction::Attack {
            character_hit_power_value,
        } =&gt; battle_showdown.attack(character_hit_power_value),
    };
    msg::reply_bytes(result.encode(), <span class="hljs-number">0</span>)
        .expect(<span class="hljs-string">"Failed to encode or reply with `BattleShowdownEvent`."</span>);
}

<span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">state</span></span>() {
    <span class="hljs-keyword">let</span> battle_showdown = <span class="hljs-keyword">unsafe</span> {
        BATTLESHOWNDOWN
            .take()
            .expect(<span class="hljs-string">"Unexpected error in taking state"</span>)
    };

    msg::reply(battle_showdown, <span class="hljs-number">0</span>).expect(<span class="hljs-string">"Unable to share the state"</span>);
}
</code></pre>
<p>At first glance this might seem a lot, but it isn't, so don't get too intimidated. Before you start, make sure you understand the whole logic of the game description I gave earlier since you'll be implementing it here.</p>
<p>Above, we have some important functions, <code>struct</code>, and <code>impl</code>, and here is an overview of what they do.</p>
<ol>
<li>With the <code>get_random_u32</code> function, we generated a random number between 1 and 3.</li>
<li>The <code>BattleShowdown</code> struct in the <code>/src/lib.rs</code> represents the main state of the game. It holds information such as player and boss stats, current game level, and game state. The <code>static mut BATTLESHOWNDOWN: Option&lt;BattleShowdown&gt; = None;</code> is a static mutable variable that holds the current state of the game. It's wrapped in an <code>Option</code> to indicate whether the game has been initialized yet or not, which you'll use later in your implementation.</li>
<li><code>unsafe extern "C" fn init()</code> is responsible for initializing the game state when called after the contract has been uploaded. It loads an initialization message, constructs a <code>BattleShowdown</code> instance based on that message, and sets <code>BATTLESHOWNDOWN</code> to <code>Some</code> with the constructed instance.</li>
<li><code>impl Encode for BattleShowdown</code>: this trait is implemented for <code>BattleShowdown</code>, enabling it to be encoded into a byte representation. This is useful for serialization and sending the game state over the network. And there's a way to also implement the trait without creating an <code>impl</code> for <code>BattleShowdown</code>.</li>
<li><code>impl BattleShowdown</code>: this <code>impl</code> for <code>BattleShowdown</code> is where the entire logic happens, and for now, we've only added an <code>attack</code> method for it. It worth noting that we'll be adding more as we continue this project.</li>
<li>So what does the <code>attack</code> method do? Well, The <code>attack</code> method simulates a combat encounter between the player and the boss character in our game. It calculates the hit power for both entities based on character type and randomness, manages their health points accordingly, and generates game events to reflect the outcome of the encounter.</li>
<li><code>extern "C" fn handle()</code>: In our case, the <code>handle</code> function is used to process incoming messages, specifically <code>BattleShowdownAction</code>. So depending on the action perform by the actor, it dispatches a result of the action to the appropriate methods of <code>BattleShowdown</code>, such as <code>attack</code>, and sends back the resulting game events to the actor. Like disccued in the illustration.</li>
<li>And lastly, <code>extern "C" fn state()</code> simply retrieves the current game state represented by <code>BattleShowdown</code> and sends it as a reply.</li>
</ol>
<p>This is the overall explanation to the code in the file. But leaving with this isn't enough for even me. Let's disccus more below.</p>
<h3 id="heading-understanding-theinit">Understanding the<code>init()</code></h3>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug, Default)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BattleShowdown</span></span> {
    <span class="hljs-keyword">pub</span> player_id: ActorId,
    <span class="hljs-keyword">pub</span> player_character_type: CharacterType,
    <span class="hljs-keyword">pub</span> current_level: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> player_lives: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> player_name: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> boss_lives: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> character_hit_power_value: PlayerHitPowerValue,
    <span class="hljs-keyword">pub</span> player_hit_power: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> boss_hit_power: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> game_state: <span class="hljs-built_in">String</span>,
}

<span class="hljs-keyword">static</span> <span class="hljs-keyword">mut</span> BATTLESHOWNDOWN: <span class="hljs-built_in">Option</span>&lt;BattleShowdown&gt; = <span class="hljs-literal">None</span>;

<span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">unsafe</span> <span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">init</span></span>() {
    <span class="hljs-comment">// Load initialization data</span>
    <span class="hljs-keyword">let</span> init: InitBattleShowdown = msg::load().expect(<span class="hljs-string">"Unable to decode InitBattleShowdown"</span>);

    <span class="hljs-comment">// Create a BattleShowdown instance with initial values</span>
    <span class="hljs-keyword">let</span> battle_showdown = BattleShowdown {
        player_id: msg::source(),
        player_character_type: init.player_character_type,
        player_name: init.player_name,
        boss_lives: <span class="hljs-number">10</span>,
        player_lives: <span class="hljs-number">10</span>,
        ..<span class="hljs-built_in">Default</span>::default()
    };

    <span class="hljs-comment">// Store the BattleShowdown instance</span>
    BATTLESHOWNDOWN = <span class="hljs-literal">Some</span>(battle_showdown);

    <span class="hljs-comment">// Reply to signal successful initialization</span>
    msg::reply_bytes(<span class="hljs-string">"Successfully initialized"</span>, <span class="hljs-number">0</span>).expect(<span class="hljs-string">"Failed to initialize successfully."</span>);
}
</code></pre>
<p>The function loads data from an initialization message (<code>InitBattleShowdown</code>) sent by the developer or player. This data includes the player's chosen <code>character type</code> and <code>name</code>. Based on the initialization data, a <code>BattleShowdown</code> instance is created with initial values, which is stored in <code>battle_showdown</code>. </p>
<p>This instance represents the state of the game, including player and boss stats, current level, and game state. The created <code>BattleShowdown</code> instance is stored in the <code>BATTLESHOWNDOWN</code> static variable, allowing the game logic to access and manipulate the game state throughout the gameplay. Finally, a reply message is sent back to the developer or player to indicate successful initialization of the game contract. </p>
<p>This function sets up the initial state of the game, paving the way for further interactions and gameplay logic.</p>
<h3 id="heading-understanding-the-handle">Understanding the <code>handle()</code></h3>
<pre><code class="lang-rust"><span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">handle</span></span>() {
    <span class="hljs-comment">// Load the action from the message</span>
    <span class="hljs-keyword">let</span> battle_showdown_action: BattleShowdownAction =
        msg::load().expect(<span class="hljs-string">"Could not load BattleShowdownAction"</span>);

    <span class="hljs-comment">// Retrieve the current game state</span>
    <span class="hljs-keyword">let</span> battle_showdown = <span class="hljs-keyword">unsafe</span> {
        BATTLESHOWNDOWN
            .as_mut()
            .expect(<span class="hljs-string">"`BattleShowdown` is not initialized."</span>)
    };

    <span class="hljs-comment">// Execute the appropriate action on the game state and get the result</span>
    <span class="hljs-keyword">let</span> result: BattleShowdownEvent = <span class="hljs-keyword">match</span> battle_showdown_action {
        BattleShowdownAction::Attack {
            character_hit_power_value,
        } =&gt; battle_showdown.attack(character_hit_power_value),
    };

    <span class="hljs-comment">// Send back the result as a reply message</span>
    msg::reply_bytes(result.encode(), <span class="hljs-number">0</span>)
        .expect(<span class="hljs-string">"Failed to encode or reply with `BattleShowdownEvent`."</span>);
}
</code></pre>
<p>The <code>handle()</code> function plays a crucial role in processing incoming messages and orchestrating the game's actions. It serves as the bridge between player interactions and the game's internal logic. When invoked, <code>handle()</code> begins by loading the <code>action</code> sent by the player from the message. </p>
<p>This <code>action</code>, encapsulated as <code>BattleShowdownAction</code>, dictates the player's intended move, such as attacking the boss. Next, the function retrieves the current game state from the <code>BATTLESHOWNDOWN</code> variable. This state holds essential information about the player, the boss, and the overall game environment. </p>
<p>With both the action and the game state at hand, <code>handle()</code> proceeds to execute the appropriate action. For instance, if the player's action is an <code>attack</code>, the function triggers the <code>attack()</code> method on the <code>battle_showdown</code> instance. This method calculates the outcome of the player's attack, considering factors like the player's hit power and the boss's remaining health points.</p>
<p>Crucially, the <code>attack()</code> method requires a parameter: <code>character_hit_power_value</code>. This parameter corresponds to the player's choice between three options: <code>X</code>, <code>Y</code>, and <code>Z</code>, each associated with different hit power values as disccused in earlier sections. </p>
<p>Once the <code>action</code> is executed, <code>handle()</code> generates an event, encapsulated as <code>BattleShowdownEvent</code>, reflecting the outcome of the player's move. This event encapsulates important details, such as changes in player and boss health points. Finally, <code>handle()</code> responds to the player by replying with the result of the action as a byte-encoded message. This message contains the updated game state, allowing the player to understand their current situation, including their health status and that of the boss.</p>
<h3 id="heading-understanding-the-impl-battleshowdown-for-attack">Understanding the <code>impl BattleShowdown for attack</code></h3>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> BattleShowdown {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">attack</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, _character_hit_power_value: PlayerHitPowerValue) -&gt; BattleShowdownEvent {
        <span class="hljs-comment">// Calculate total hit power for player based on character type and random values</span>
        <span class="hljs-keyword">let</span> character_hit_power = <span class="hljs-keyword">match</span> &amp;<span class="hljs-keyword">self</span>.player_character_type {
            CharacterType::Warrior =&gt; <span class="hljs-number">4</span>,
            CharacterType::Mage =&gt; <span class="hljs-number">3</span>,
            CharacterType::Archer =&gt; <span class="hljs-number">2</span>,
        };

        <span class="hljs-keyword">let</span> player_hit_power = <span class="hljs-keyword">match</span> &amp;<span class="hljs-keyword">self</span>.character_hit_power_value {
            PlayerHitPowerValue::X =&gt; character_hit_power + get_random_u32(),
            PlayerHitPowerValue::Y =&gt; character_hit_power + get_random_u32(),
            PlayerHitPowerValue::Z =&gt; character_hit_power + get_random_u32(),
        };

        <span class="hljs-comment">// Placeholder for boss attack logic</span>
        <span class="hljs-comment">// Update boss hit power to a random value for each attack</span>
        <span class="hljs-keyword">self</span>.boss_hit_power = get_random_u32();

        <span class="hljs-keyword">self</span>.player_hit_power = player_hit_power;

        <span class="hljs-comment">// Reduce boss's lives based on player's hit power</span>
        <span class="hljs-keyword">self</span>.boss_lives = <span class="hljs-keyword">self</span>.boss_lives.saturating_sub(<span class="hljs-keyword">self</span>.player_hit_power);
        <span class="hljs-comment">// Reduce player's lives based on boss's hit power</span>
        <span class="hljs-keyword">self</span>.player_lives = <span class="hljs-keyword">self</span>.player_lives.saturating_sub(<span class="hljs-keyword">self</span>.boss_hit_power);

        <span class="hljs-comment">// Check if player or boss has lost</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.player_lives == <span class="hljs-number">0</span> {
            <span class="hljs-comment">// Player lost</span>
            <span class="hljs-keyword">self</span>.game_state = <span class="hljs-string">"Player lost."</span>.to_string();
            <span class="hljs-keyword">return</span> BattleShowdownEvent::PlayerLost {
                id: <span class="hljs-keyword">self</span>.player_id,
                boss_lives: <span class="hljs-keyword">self</span>.boss_lives,
                character_type: <span class="hljs-keyword">self</span>.player_character_type,
                message: <span class="hljs-string">""</span>.to_string(),
                player_lives: <span class="hljs-keyword">self</span>.player_lives,
            };
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.boss_lives == <span class="hljs-number">0</span> {
            <span class="hljs-comment">// Boss lost</span>
            <span class="hljs-keyword">self</span>.game_state = <span class="hljs-string">"Boss lost."</span>.to_string();
            <span class="hljs-keyword">return</span> BattleShowdownEvent::BossLost {
                boss_lives: <span class="hljs-keyword">self</span>.boss_lives,
                character_type: <span class="hljs-keyword">self</span>.player_character_type,
                player_lives: <span class="hljs-keyword">self</span>.player_lives,
                message: <span class="hljs-string">"You've defeated the boss"</span>.to_string(),
            };
        }

        <span class="hljs-keyword">self</span>.game_state = <span class="hljs-string">"The game continues."</span>.to_string();
        <span class="hljs-comment">// Return event indicating attack occurred</span>
        BattleShowdownEvent::Attacked {
            boss_lives: <span class="hljs-keyword">self</span>.boss_lives,
            character_type: <span class="hljs-keyword">self</span>.player_character_type,
            id: <span class="hljs-keyword">self</span>.player_id,
            name: <span class="hljs-keyword">self</span>.player_name.clone(),
            player_lives: <span class="hljs-keyword">self</span>.player_lives,
        }
    }
}
</code></pre>
<p>The <code>attack</code> method within the <code>BattleShowdown</code> implementation simulates a pivotal moment in the game: a combat encounter between the player and the boss character. </p>
<p>Here's how it works:</p>
<p>Firstly, the method calculates the total hit power for the player based on their character type (<code>character_hit_power</code>) and randomness (<code>player_hit_power</code>). Different character types (<code>Warrior</code>, <code>Mage</code>, or <code>Archer</code>) have different base hit powers. </p>
<p>Next, a random hit power value is added to the character's base hit power. This adds an element of unpredictability to each attack. The method then updates the boss's hit power (<code>self.boss_hit_power = get_random_u32();</code>) to a random value, representing the boss's retaliatory strike against the player.</p>
<p>After calculating the hit powers, the method reduces the boss's lives based on the player's hit power and vice versa, updating their respective health points accordingly.</p>
<pre><code class="lang-rust">        <span class="hljs-comment">// Reduce boss's lives based on player's hit power</span>
        <span class="hljs-keyword">self</span>.boss_lives = <span class="hljs-keyword">self</span>.boss_lives.saturating_sub(<span class="hljs-keyword">self</span>.player_hit_power);
        <span class="hljs-comment">// Reduce player's lives based on boss's hit power</span>
        <span class="hljs-keyword">self</span>.player_lives = <span class="hljs-keyword">self</span>.player_lives.saturating_sub(<span class="hljs-keyword">self</span>.boss_hit_power);
</code></pre>
<p>The game state is then checked to determine if either the player or the boss has lost the battle. If the player's health points reaches zero, the game state is updated to indicate that the player has lost. Conversely, if the boss's health points reach zero, the game state reflects the boss's defeat.</p>
<pre><code class="lang-rust">        <span class="hljs-comment">// Check if player or boss has lost</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.player_lives == <span class="hljs-number">0</span> {
            <span class="hljs-comment">// Player lost</span>
            <span class="hljs-keyword">self</span>.game_state = <span class="hljs-string">"Player lost."</span>.to_string();
            <span class="hljs-keyword">return</span> BattleShowdownEvent::PlayerLost {
                id: <span class="hljs-keyword">self</span>.player_id,
                boss_lives: <span class="hljs-keyword">self</span>.boss_lives,
                character_type: <span class="hljs-keyword">self</span>.player_character_type,
                message: <span class="hljs-string">""</span>.to_string(),
                player_lives: <span class="hljs-keyword">self</span>.player_lives,
            };
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.boss_lives == <span class="hljs-number">0</span> {
            <span class="hljs-comment">// Boss lost</span>
            <span class="hljs-keyword">self</span>.game_state = <span class="hljs-string">"Boss lost."</span>.to_string();
            <span class="hljs-keyword">return</span> BattleShowdownEvent::BossLost {
                boss_lives: <span class="hljs-keyword">self</span>.boss_lives,
                character_type: <span class="hljs-keyword">self</span>.player_character_type,
                player_lives: <span class="hljs-keyword">self</span>.player_lives,
                message: <span class="hljs-string">"You've defeated the boss"</span>.to_string(),
            };
        }

        <span class="hljs-keyword">self</span>.game_state = <span class="hljs-string">"The game continues."</span>.to_string();
        <span class="hljs-comment">// Return event indicating attack occurred</span>
        BattleShowdownEvent::Attacked {
            boss_lives: <span class="hljs-keyword">self</span>.boss_lives,
            character_type: <span class="hljs-keyword">self</span>.player_character_type,
            id: <span class="hljs-keyword">self</span>.player_id,
            name: <span class="hljs-keyword">self</span>.player_name.clone(),
            player_lives: <span class="hljs-keyword">self</span>.player_lives,
        }
</code></pre>
<p>Finally, if neither the player nor the boss has lost, the game state is updated to indicate that the battle continues.</p>
<h3 id="heading-understanding-the-state">Understanding the <code>State()</code></h3>
<pre><code class="lang-rust"><span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">state</span></span>() {
    <span class="hljs-keyword">let</span> battle_showdown = <span class="hljs-keyword">unsafe</span> {
        BATTLESHOWNDOWN
            .take()
            .expect(<span class="hljs-string">"Unexpected error in taking state"</span>)
    };

    msg::reply(battle_showdown, <span class="hljs-number">0</span>).expect(<span class="hljs-string">"Unable to share the state"</span>);
}
</code></pre>
<p>For this instance there's nothing more to share, it retrieves the current state of the game, represented by the <code>BattleShowdown</code> struct, from a static mutable variable <code>BATTLESHOWNDOWN</code>, and sends a reply message containing the game state back to the player. If there is an error sending the reply message, it will panic with an error message indicating the inability to share the state.</p>
<p>And that's that for this project. There are some exciting features you can consider if you want to extend this project. Imagine the possibility of resetting the game state, accommodating multiple players, or even resetting the game for a single player. And for the ambitious, you could even tackle the challenge of resetting the state for the entire game. These additions can offer new dimensions to the project and provide excellent opportunities for you to challenge yourself.</p>
<h3 id="heading-short-recording-of-what-weve-built-demo">Short Recording of what we've built - Demo</h3>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.loom.com/share/590d685f311f46c386943c41816dbf83?sid=e99d4948-f0ab-486d-a5fa-98fbcdfe3fe3">https://www.loom.com/share/590d685f311f46c386943c41816dbf83?sid=e99d4948-f0ab-486d-a5fa-98fbcdfe3fe3</a></div>
<p>In the video you could see I added another method for resetting everything back to it inital state. Though I didn't guide you through the process of doing that, you should know it is easy to implement, and I've added <a target="_blank" href="https://github.com/rockyessel/battle-showdown">a GitHub repository</a> for the entire code.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>As demonstrated, developing a smart contract with Gear Protocol becomes straightforward once you grasp the communication message concepts. By following the steps outlined, you can start building your own projects with confidence.</p>
<p>While this article didn't delve into handling transactions such as token transfers, minting, or NFTs, I will cover these topics in a future article.</p>
<p>For now, you can explore the repository of the project we built together: <a target="_blank" href="https://github.com/rockyessel/battle-showdown">Battle-Showdown</a>, and if you have any question to ask, feel free to reach @rockyessel on X.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
