paint-brush
Comprehensive Tutorials On How To Build And Deploy Decentralised Application On Vara Networkby@rockyessel
406 reads
406 reads

Comprehensive Tutorials On How To Build And Deploy Decentralised Application On Vara Network

by Rocky EsselMarch 14th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

I believe that decentralization marks the future trajectory for various domains including the web, financial sectors, gaming, record-keeping, trading, and more.
featured image - Comprehensive Tutorials On How To Build And Deploy Decentralised Application On Vara Network
Rocky Essel HackerNoon profile picture

A year ago I wrote about how fascinating the decentralized world was and the brains behind it. So this time, I have taken it upon myself to explore a more detailed explanation with you and build and deploy a smart contract on the blockchain using Vara Network.

You can read it here

I will explain every step on the way, and won’t leave any stone unturned in this tutorial. By the end of this tutorial, you understand Centralisation, Decentralisation, Smart contracts, Networks, and the tools you will use to build the dApp. So let’s begin.


I believe that decentralization marks the future trajectory for various domains including the web, financial sectors, gaming, record-keeping, trading, and more. At its core, decentralization revolves around granting users control, authority, and decision-making powers, a level of empowerment not afforded by centralized systems.


Now for users that are new to the concept of decentralisation and centralization, here is what it means.

Centralized Systems

I’ll begin by exploring centralization with you, which by definition involves the concentration of control, authority, and decision-making within a single system. In such a setup, individuals often find themselves with limited authority and little say in the events that directly impact them. While some systems may grant a certain level of control, it is subject to numerous restrictions that could be revoked based on the entity's policies or terms and conditions.


For instance, certain banks may provide users with a degree of authority to withdraw money up to a specified limit. However, these institutions can, at their discretion, lock or block accounts from any transactions without providing a clear reason. This exemplifies the workings of a centralized system.


This brought about the concept of decentralization that addresses these limitations. Do know that, the concept of decentralization has been present in various forms throughout history, and it's not tied to a specific moment of discovery or introduction. However, the modern emphasis on decentralization in the context of technology, finance, and governance has evolved.

Decentralized Systems

If decentralization serves as the antithesis of centralization, how do you define it?

I define decentralization as a system where authority, power, control, decision-making, and governance are distributed among multiple participants (such as users, customers, or individuals) within a network. This concept diverges from the concentration of power typically found in a central entity

Decentralization is a broader concept, and blockchain is the system that embodies it.

Blockchain

Blockchain is a technology, that best describes decentralization, or proves that there’s a future where decentralization can fully take over. This technology fundamentally transforms how data is stored, verified, and transacted securely and transparently. At its core, a blockchain is a decentralized and distributed ledger that records transactions across a network of computers.

Don’t know what a Network is? Well, worry not, I’ll explain later in the article.

In the context of decentralization, blockchain plays an important role, but note this very well, decentralization has been a concept applied in various domains, including computer networks, governance structures, and distributed systems, before the advent of blockchain, but however, blockchain was introduced a practical and effective way to implement decentralization securely and transparently, particularly in the context of financial transactions.

Why Explore Blockchain?

For developers contemplating whether to delve into blockchain, consider this: it represents the future, attracting substantial investments. Similar to the trajectory of AI, blockchain is a major technological development. Just as AI gained widespread attention with ChatGPT's release, blockchain, though underrated, holds immense potential. Many developers hesitated to learn it initially due to its perceived difficulty. However, as witnessed with AI, breakthroughs can shift perceptions. Waiting for blockchain to blossom before delving in ensures that, like with AI, you seize the most opportunities and chances it presents once it gains widespread recognition


The global blockchain technology market size is expected to reach USD 1,235.71 Billion by 2030”, according to a new study by Polaris Market Research.


The motivation to delve into blockchain is rooted in its undeniable status as the future of technology. As we witness the remarkable success of web3, decentralized applications (dApps), and other blockchain-driven systems, it becomes apparent that major tech enterprises are actively investing in these transformative technologies.


Whether it's a dApp shaping the landscape or a tool facilitating seamless interactions within these systems, the blockchain ecosystem is robust and evolving. The substantial growth it has experienced over the years is not just a passing trend; it is a testament to its enduring significance.


Amidst the surge in popularity of artificial intelligence (AI), especially among aspiring developers, there's a tendency for confusion to arise. Many find themselves at a crossroads, torn between learning blockchain and opting for the seemingly more mainstream AI. The key lies in recognizing that while AI holds its own merit, blockchain is an equally compelling and enduring choice.


Is Passion needed?

Passion, though not a mandatory prerequisite, is a guiding force that propels individuals through the initial challenges of coding. As someone who has experienced intermittent struggle and returned to coding, I can attest to the pivotal role passion plays in this journey. In the end, it is declined


Passion, though not a mandatory prerequisite, is a guiding force that propels individuals through the initial challenges of coding.


Just made my own quote. 😊😂


For web 2.0 developers, here's an interesting fact: any application you've built using web 2.0 technology can seamlessly transition into the web 3.0 realm with the adoption of web3 technology.


For new or aspiring developers, I recommend starting with a foundational understanding of Web 2.0 technology. While not mandatory, it is advisable to grasp concepts such as asynchronous programming, how HTTPS functions, and the available HTTP methods. This knowledge will provide you with a solid base as you embark on your development journey, enhancing your ability to comprehend and work with more advanced technologies in the future.


Now, let's shift our focus to the next topic – learning blockchain. As I mentioned earlier, blockchain is a vast field, and attempting to grasp everything simultaneously can be ineffective. The optimal approach is to immerse yourself in a specific ecosystem, specialize in it, and then progressively explore advanced concepts or stacks.


The subsequent step involves selecting a tool, language, and everything else related to the system and its functionality. This strategy is advantageous because specializing in a particular tech stack enables you to leverage AI for enhancement and advancement, aligning with the adage that 'AI will replace those who don't integrate it into their work for efficient and rapid automation.' So, let's embark on this journey.

How do you start learning blockchain?

Hope you’re excited to delve into the world of blockchain. Buckle up, because I'm here to guide you through its captivating ecosystem.

The blockchain world is vast, and knowing where to start can be overwhelming.

Blockchain Ecosystem

Fear not, I've been digging deep and unearthed some key components to map your learning journey:


  1. Blockchain Platforms: Think of these as the base where decentralized applications (dApps) live and transactions happen securely. Names like Ethereum, Bitcoin, and even Vara Network and Binance Smart Chain fall under this umbrella. Imagine them as rooms built specifically for decentralization.


  2. Decentralized Finance (DeFi): Remember our discussion about the control traditional financial systems exert? Limits on withdrawals, inconvenient hours, and restrictions on accessing your own money are frustrating realities, well DeFi flips the script. No single entity controls things, giving you transparency and freedom, right from your internet connection.


  3. Non-Fungible Tokens (NFTs): These unique digital assets are stored on the blockchain, often representing ownership of something special, like artwork or even physical items! Did you know NFTs can even track the journey of physical goods, ensuring authenticity and transparency? Think supply chain tracking or event access – the possibilities are endless!


  4. Blockchain Interoperability: Interoperability focuses on the ability of different blockchain networks to communicate and share data seamlessly. It allows and enhances collaboration and connectivity between disparate blockchain ecosystems. Here for more info.


    Now I want you to Imagine different blockchain networks chatting freely, sharing data seamlessly. That's what interoperability does, and platforms like Polkadot, Cosmos, and Wanchain make it happen.


  5. Blockchain Identity and Security: Blockchain-based identity verification system platforms provide users or individuals control over their digital identities, which then enhances security and privacy. Furthermore, the blockchain utilizes digital cryptography.


  6. Enterprise Blockchain Solutions: Enterprise blockchain solutions cater to the needs of businesses, offering secure and efficient ways to manage data and processes. Examples are Hyperledger and Corda.


  7. Blockchain Development Tools: Development tools simplify the process of creating, testing, and deploying applications on blockchain platforms. Examples are Truffle Suite, Remix IDE, Gear, etc.


  8. Cross-Chain Platforms: Cross-chain platforms facilitate interactions and transactions between different blockchain networks. Examples are Thorchain and Wrapped Tokens.


  9. Community and Social Platforms: Is a like any social media platform but on the blockchain, which also know as SocialFi, which enables users to engage, create, content, and earn cyptocurrencies without centralized control. An example is the Mirror.


Now, I don't want you to feel pressured to conquer everything at once. Instead, let your interests guide you. Whether you're drawn to building SocialFi or DeFi applications, understanding the ecosystem's strengths will empower you to contribute to building amazing things.


This is an evolving technology, and decentralization, in its broader sense, extends its influence across various industries, disrupting conventional models and introducing new paradigms of collaboration and trust. This evolution is expected to modify existing ecosystems and potentially create new ones to facilitate its growth.

Blockchain Tools

I'm excited to talk about blockchain tools with you! As you might know, these tools come in all shapes and sizes, each built with different programming languages. We've got Rust powering Solana's speed, Solidity crafting magic on Ethereum, and Go keeping the Binance Smart Chain humming. It's a real smorgasbord!


When it comes to picking the right language, I'm a big fan of Rust. It's steadily taking the system development world by storm, and its features make it a great fit for building secure and efficient blockchain applications.


But for this particular tutorial, we're going to explore a different path! I've set my sights on Vara Network as our playground for smart contracts. Why? Well, it's a rising star with tons of potential, and its passionate community on platforms like Discord and Telegram is truly inspiring.


So, buckle up and join me as we dive into the exciting world of Vara and create our very first smart contract together!


Opportunities

I’ll explore with you the additional compelling reasons to focus on Vara Network:

  1. Rapidly Growing Community:
    • Vara Network boasts a thriving and swiftly expanding community, providing an engaging environment for developers to connect, share insights, and collaborate. Currently 3600+ developers.
  2. Comprehensive Documentation for New Developers:
    • Vara Network offers robust documentation tailored to freshly minted developers, easing the onboarding process and ensuring a smoother learning curve.
  3. Seasonal Hackathons (Currently Season 4):
    • Hosting regular hackathons, Vara Network promotes continuous innovation and creativity within its community, providing an avenue for developers to showcase their skills and potentially win accolades. With total prize pool is $66,000.00, with $6,000.00 distributed at the end of each season
  4. Opportunity for Tool Creation and Profit:
    • Given its status as a new and rapidly growing platform, Vara Network presents an opportune moment for developers to create tools around it, potentially leading to profitable ventures.
  5. Inclusive Developer Ecosystem:
    • Vara Network fosters an inclusive developer ecosystem, encouraging diversity and collaboration among developers with varied backgrounds and expertise.
  6. Educational Initiatives and Workshops:
    • Vara Network actively engages in educational initiatives and workshops, facilitating continuous learning and skill development for its community members.
  7. Active Developer Support Channels:
    • The platform provides active developer support channels whether on Telegram or Discord, ensuring that developers can seek assistance, share knowledge, and troubleshoot effectively.
  8. Regular Platform Updates and Improvements:
    • Vara Network prioritizes continuous improvement, regularly rolling out updates to enhance the platform's functionality and user experience.
  9. Integration Opportunities with Emerging Technologies:
    • As a dynamic platform, Vara Network opens doors for developers to explore integrations with emerging technologies, providing a space for innovation and experimentation.
  10. Community-Driven Governance:
    • Vara Network emphasizes community-driven governance, giving developers a voice in decision-making processes and fostering a sense of ownership within the ecosystem.
  11. GitHub Contribution Opportunities:
    • Developers can actively contribute to Vara Network's development on GitHub, fostering collaboration and allowing for community-driven enhancements and innovations.


Core Blockchain Concept

The terms "Smart Contracts," "Networks," and "Tokens" are essential concepts in the context of blockchain and cryptocurrency. Here's a brief explanation of each:


  1. Smart Contracts
  2. Token
  3. Networks

Smart Contracts:

These are self-executing contracts with the terms of the agreement directly written into code. I want you to think of these as automatic or self-executing agreements or contracts, written in code and stored on the blockchain.


They behave like vending machines: because once you put in the conditions (e.g., "pay 50 cents for a can-drink"), and when met, the action happens automatically (dispense the can-drink).


This cuts out the middleman and ensures trust


In the context of our can-drink analogy, the "middleman" referred to by smart contracts or agreements can have different interpretations depending on the specific scenario.


Here is one example:

Ticketing services: When buying concert tickets through traditional platforms, fees, and markups are often added by intermediaries(middlemen). Smart contracts can enable direct ticket sales between artists and fans, potentially reducing costs and increasing transparency.

Tokens:

Tokens represent digital assets or units of value on a blockchain. They can represent various assets such as your cryptocurrencies, assets in your decentralized application (DApp), or even real-world assets like real estate. Tokens can be transferred or exchanged on a blockchain network, and they often serve as a means of incentivizing network participants.


Now, let's delve into Networks:

Networks

In the context of blockchain, a network refers to a decentralized system of nodes (computers) that are interconnected and communicate with each other to maintain the integrity of the blockchain. This network is responsible for validating transactions, reaching consensus on the state of the blockchain, and ensuring security. Blockchain networks can be categorized into two main types: public and private.

What is Vara Network?

Vara Network is a standalone layer-1 blockchain built on top of Gear Protocol. This means that it leverages the infrastructure and technology provided by Gear, including its Substrate-based programming platform.


For those who don’t understand what layer-1 means, I’ll stretch on it to provide you with base insight. So now, in the context of blockchain, there are typically two main layers;


  1. Layer-1 (Main Chain)
  2. Layer-2 (Scaling Solutions)


Note that, the above are the two main layers of the blockchain, but I think it's worth mentioning that other layers or subcategories may exist in specific blockchain ecosystems. Additionally, research and development are constantly growing in the blockchain space, so new scaling solutions and even Layer-3 concepts are emerging.


Layer-1 (Main Chain):

  • Think of it as the foundation: This is the core blockchain where all transactions are permanently recorded and secured through a consensus mechanism like Proof-of-Work (PoW), Proof-of-Stake(PoS), and Nominated Proof-of-Stake(NPoS).

Vara Network is NPoS(Nominated Proof-of-Stake).

  • Examples: Bitcoin, Ethereum, Solana, Avalanche, Vara Network
  • Pros: Highly secure and decentralized, tamper-proof data, robust security mechanisms.
  • Cons: Limited transaction capacity, high fees, potentially slow transaction speeds.


Layer-2 (Scaling Solutions):

  • Think of them as extensions: These are separate systems built on top of the main chain, aiming to overcome Layer-1's scalability limitations.
  • Examples: Lightning Network (Bitcoin), Polygon (Ethereum), Loopring (Ethereum), Optimism (Ethereum).
  • Pros: Faster transaction speeds, lower fees, improved scalability.
  • Cons: Can inherit some security risks from the underlying Layer-1, and may have specific limitations depending on the solution.


Here's a table summarizing the key differences:

Feature

Layer-1

Layer-2

Core function

Base blockchain

Scaling solution

Security

Primarily inherited from Layer-1

Varies depending on a specific solution

Decentralization

Highly decentralized

Varies depending on the solution

Transaction speed

Slower

Faster

Fees

Higher

Lower


So remember, understanding these layers is important when evaluating different blockchain projects and considering their suitability for specific use cases.


So calling Vara Network a layer-1 blockchain emphasizes its role as an independent, foundational, and decentralized blockchain layer, providing the essential infrastructure for decentralized applications and transactions. It utilizes the infrastructure and technology provided by Gear Protocol.

Gear Protocol

When I was defining Vara Network, I mentioned Gear Procotol, so probably you’re wondering what is it.


The Gear Protocol is an advanced substrate-based smart contract engine that enables developers to build next-gen Decentralized Applications (dApps) that are faster, more secure, and cheaper for users to operate than if they were deployed on other EVM-based blockchains.


So let’s break down the definition for a more solid understanding of it.


I want you to think of Gear Protocol as a construction kit for building your next-generation decentralized applications (dApps). It empowers developers(you and I) to create dApps that are:


  • Fast: Imagine processing transactions instantly, unlike waiting minutes on other blockchains.

  • Secure: Built-in security features that protect your dApps and user data.

  • Affordable: Run your dApps without breaking the bank with lower fees.

  • Substrate-based: Gear utilizes the flexible Substrate framework, allowing customization for specific needs.

  • Advanced smart contract engine: It handles code execution efficiently, leading to faster dApp performance.

  • EVM-based alternative (using WASM): Compared to popular Ethereum Virtual Machine (EVM) blockchains, Gear, which utilizes the WebAssembly (WASM) virtual machine, aims for significant improvements in speed, security, and cost.

    Let me break down the potential benefits:

    • Speed: WASM is a more lightweight and efficient virtual machine compared to EVM. This translates to faster transaction processing times and potentially lower latency on the Gear network.
    • Security: WASM's design places a premium on memory safety, creating a more secure and sandboxed environment for smart contracts. This helps mitigate risks associated with vulnerabilities like buffer overflows often seen in EVM contracts.
    • Cost: Faster processing and a more efficient virtual machine can lead to lower transaction fees on the Gear network compared to congested EVM-based blockchains.
    • Scalability: WASM's design is more modular and allows for future optimizations. This potentially enables the Gear network to scale better as adoption and transaction volume increase.


Key Takeaway:

Gear Protocol provides developers with a powerful toolkit to build secure, fast, and affordable dApps, potentially unlocking new possibilities in the blockchain world.

Shared Concepts Between Vara Network and Gear Protocol

While Vara Network is a standalone layer-1 blockchain, it leverages certain aspects of Gear Protocol, its underlying infrastructure. Here are some key shared concepts:

Substrate Framework:

  • Both Vara Network and Gear Protocol are built on the Substrate framework, an open-source blockchain development framework from Parity Technologies. This provides a modular and versatile foundation for building custom blockchains.
  • Substrate offers components like consensus mechanisms, networking protocols, and on-chain governance, which Vara Network can tailor to its specific needs.

Interoperability Potential:

  • Both Vara and Gear share some underlying infrastructure, paving the way for potential future interoperability. This could enable communication and asset transfer between the two networks, although it's not currently implemented.
  • Interoperability could unlock benefits like broader liquidity access for users and developers building dApps across both ecosystems.

Development Tools and Languages:

  • Vara Network benefits from development tools and languages familiar to Gear Protocol developers. This familiarity can potentially ease development, attract developers comfortable with the Gear ecosystem, and accelerate dApp creation on Vara.
  • However, Vara isn't restricted to Gear-specific tools, and developers have the freedom to use compatible alternatives for building dApps directly on Vara.

Community and Collaboration:

  • Vara and Gear share a common developer community with expertise in Substrate and related technologies. This shared knowledge base can foster collaboration and support for both projects.
  • However, each ecosystem also has its own distinct community focused on its specific goals and functionalities.


It's important to remember:

  • Vara shares some ideas with Gear, but it operates on its own independent blockchain with its unique token (VARA), way of reaching agreement (consensus mechanism), and voting system (governance processes).
  • The extent of future interoperability between the two networks remains to be seen and depends on ongoing development and community decisions.

Core Vara Features

I talked about Gear Protocol and how Vara is built on top of this technology, now with Gear's powerful tech stack, which includes the Actor Model for secure and isolated execution, Persistent Memory for individual data storage, and the versatile WebAssembly virtual machine (Wasm), that Vara benefits from, and is very unique compared to popular tools.


  1. Actor Model
  2. Persisant Memory
  3. Wasm


Don’t worry if you’re new to this concept, I’ll explain this carefully, and openly as this concept is crucial for writing secure and performant smart contracts on Vara Network.

Actor Model

In Vara Network's Actor Model, each smart contract operates as an independent unit called an "actor." These actors are isolated from each other, possessing their own private memory and communicating solely through asynchronous messages. This isolation and message-based communication ensures order and avoids conflicts with enhanced network security by minimizing shared resources and potential vulnerabilities.


While isolation enhances security, it's important to note that smart contract data itself is still publicly accessible on the blockchain. Only individual actor memory remains private.


Let me break it down more:

Key Principles:

  • Actors: Individual units of computation representing smart contracts or programs operating independently.
  • Isolation: Actors communicate through asynchronous message passing, preventing shared memory issues and enhancing security.
  • Non-Blocking: Actors process messages one at a time, ensuring responsiveness and scalability.
  • Concurrency: Multiple actors can run concurrently, potentially improving performance and handling simultaneous requests.


Benefits Compared to Shared Memory Models:

  • Improved Security: Isolation and message passing minimize opportunities for vulnerabilities associated with shared memory access.
  • Enhanced Scalability: Non-blocking nature and concurrency enable processing multiple requests efficiently.
  • Fault Tolerance: Individual actor failures don't necessarily crash the entire system, promoting robustness.


Specific Features of Vara Network's Actor Model:

  • Asynchronous Messaging: Actors rely on message-passing queues, enabling flexible and decentralized communication.
  • Persistent Memory: Each actor has its own dedicated memory space, further strengthening security and isolation.
  • Deterministic Execution: Messages are processed in a defined order within each actor, ensuring predictable behaviour.


Comparison to Other Blockchain Platforms:

  • Ethereum Virtual Machine (EVM)-based platforms: These platforms often use shared memory models, potentially leading to scalability and security challenges.
  • Other Actor Model-based platforms: Vara offers unique features like persistent memory and asynchronous messaging within its Actor Model implementation.


Implications for Developers: I've provided a detailed explanation because grasping the Actor Model is essential for crafting secure and efficient smart contracts on Vara Network. As developers, we should prioritize message-based communication over traditional shared memory practices. Fortunately, Vara offers tools and resources that make it easier to develop using the Actor Model.

Persistent Memory

With this concept, Vara eliminates the reliance on shared storage for your programs. It ensures that each of your program's entire state is consistently stored within its memory space.


For clarity, I want you to imagine each of your smart contracts on Vara having its own dedicated locker, instead of having to share one big communal storage space. Your locker securely stores the contract's data and state, separate from other contracts.


Benefits of Persistent Memory:

  • By isolating data, it prevents conflicts and vulnerabilities that could arise from shared memory access as I talked about in the Actor Model.
  • Since each contract operates independently, it improves scalability which enables smoother performance even with many contracts running simultaneously.
  • Greater Flexibility.

Wasm

Vara provides the necessary speed, scalability, and security for modern Web3 solutions. Within Vara, smart contracts are implemented as Wasm programs (referred to as Actors), leveraging familiar programming languages like Rust, C++, or Go. By utilizing Wasm, Vara achieves native speed for deterministic cross-platform computations, ensuring cost-effective transactions and interoperability with other Wasm-based ecosystems.


Benefits for Developers:

  • Developers familiar with different languages can easily contribute to Vara Network, expanding the innovation potential.
  • Faster development, since compiling from existing code saves time and effort compared to starting from scratch in a new language.
  • Also improve performance boost, since wasm code can run very efficiently, resulting in faster and more responsive dApps.


Unlocking Web3 for Web2 Developers:

  • I think If you're already comfortable building applications for the web, Wasm makes transitioning to Web3 (the world of blockchain) much easier. You can leverage your existing skills and adapt them to this new environment.


Why use WASM

You should consider using WebAssembly (Wasm) because it lets you create high-performance web applications by running code from various languages directly in the browser, offering near-native speeds and improved security.

Starting a Vara Projects

At this point, I believe you understand the blockchain system, tools, platforms, smart contracts, decentralization, network, and centralization. Fast forward, we’ll be building a very simple project with Gear Protocol and deploying it on Vara Network to show how everything works, if you’re interested in learning more, then I recommend you visit Gear Academy, which is currently open.


Let’s process to install the needed packages, language, and tools for your project:


Language: For this project, you will use Rust, now don’t panic if you're new to Rust programming, for you to understand a basic knowledge is required, but can you still follow this tutorial if you’re feeling adventurous? So here is an article I have written on how to install Rust Programming on your Linux System.

Wallets: So for interacting with your smart contract, you’ll need a wallet, which I’ll provide you with a link to on how to install and create them. Currently, I'm aware of three wallet extensions that can help you interact with the smart contract: Polkadot.js Extension, Subwallet, Nova Wallet and Talisman.


Explore the following links to create your wallets:

  1. Polkadot.js Extension.
  2. Talisman
  3. Subwallet
  4. Nova Wallet


My Recommandation

As a developer who builds smart contracts, I know the struggle of juggling multiple MetaMask wallets across different Chrome profiles just for testing. That's why I highly recommend the Polkadot.js extension. It's incredibly easy to use and lets you create multiple wallets, making it a breeze to test your smart contracts without the hassle. So try it out.


Feel free to proceed with your next steps to creating our contract. On your Desktop, open your terminal and run the command below to get started on your smart contract.

cargo new contract --lib


This is how your initial project should look like:

.
├── Cargo.toml
└── src
    └── lib.rs

1 directory, 2 files


Run cargo test to verify if everything is good, and you sure expect this output:

rockyessel@UBUNTU-ROCKY:~/Desktop/lleryo/3.0/web3/contract$ cargo test
   Compiling contract v0.1.0 (/home/rockyessel/Desktop/lleryo/3.0/web3/contract)
    Finished test [unoptimized + debuginfo] target(s) in 0.51s
     Running unittests src/lib.rs (target/debug/deps/contract-d8d8bbe93b55038e)

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests contract

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


Which generates additional directories and files:

.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── lib.rs
└── target
    └── ...


We'll use:

  • gstd — a standard library for smart contracts on Gear Protocol.
  • gear-wasm-builder — a helping module aiding in building programs using Gear (added as build dependency).


In your Cargo.toml files, add the following dependency to your file.

[package]
name = "contract"
version = "0.1.0"
edition = "2021"


[lib]
crate-type = ["rlib"]

[dependencies]
gstd = { git = "https://github.com/gear-tech/gear.git", tag = "v1.0.2" }


[build-dependencies]
gear-wasm-builder = { git = "https://github.com/gear-tech/gear.git", tag = "v1.0.2", features = ["wasm-opt"] }


Let’s handle how you build your gear smart contract, there are two ways to build your smart contracts as wasm;

  1. One is to locate .cargo on your system, then create a config.toml with a build.

    [build]
    target = "wasm32-unknown-unknown"
    rustflags = [
        "-C", "link-args=--import-memory",
        "-C", "linker-plugin-lto",
    ]
    


  2. This second method is very easy and doesn’t require you to add additional dir/files to your .cargo, so will go by this method.

    Now create a build.rs in your parent directory with the code below

    fn main() {
        gear_wasm_builder::build();
    }
    


Now, you’re left with one more file to add, and that rust-toolchain.toml, so make sure to create the file with the code below:

[toolchain]
channel = "nightly-2023-09-18"
targets = ["wasm32-unknown-unknown"]
profile = "default"


Something to note, Remember I said about the smart contract, as they are message-based

In your lib.rs clear everything, then past the following code:

#![no_std]
use gstd::{msg, prelude::*};

#[no_mangle]
extern "C" fn handle() {}


Let me break this code above:


This snippet represents a very basic Gear Protocol smart contract with minimal functionality. Let's analyze each part:

1. #![no_std]:

  • This statement indicates that the code doesn't use the Rust standard library. Most standard library functions are not available in Gear environments due to their resource-constrained nature.

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

  • This line imports necessary components from the Gear standard library:
    • msg: Provides functions for interacting with messages, sending replies, and accessing data received by the contract.
    • prelude::*: Imports common Rust functions and traits to improve code readability (optional).

3. #[no_mangle]:

  • This attribute applies to exported functions, making them accessible from outside the contract. Functions without this attribute wouldn't be visible for interaction.

4. extern "C" fn handle() {}:

  • This defines the handle function, which is the core interaction point for the contract.
    • extern "C" ensures compatibility with C calling conventions.
    • fn handle() {} declares a function named handle with no arguments and no return value.
    • The empty body currently means the contract doesn't respond to any message.

In Summary:

So you should know that this code defines a rudimentary Gear smart contract structure but lacks any concrete functionality, so your next step is to add some functionality to it.


#![no_std]

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

static mut COUNTER: i32 = 0;

#[no_mangle]
extern "C" fn handle() {
    let command = msg::load_bytes().expect("Invalid message");

    let mut counter = unsafe { COUNTER };

    match command.as_slice() {
        b"inc" => counter += 1,
        b"dec" => counter -= 1,
        b"get" => {
            msg::reply_bytes(format!("{counter}"), 0).expect("Unable to reply");
        }
        _ => (),
    }

    unsafe { COUNTER = counter };
}


This simple program accepts incdec, and get commands. Paste it, and let me explain in more detail.

Have already explained the import and the msg etc.

1. let command = msg::load_bytes().expect("Invalid message");:

  • This line tries to load a byte array from the received message.
  • If successful, it stores the loaded data in the command variable.
  • If loading fails, the expect method panics, terminating the contract execution with an error message.

2. let mut counter = unsafe { COUNTER };:

  • This line reads the current value of the global COUNTER variable.
  • Since COUNTER is declared with mut, we need unsafe to acknowledge potential mutability risks (explained later).
  • The value is stored in the local variable counter, which allows modification.

3. match command.as_slice() { ... }:

  • This is a match statement based on the content of the command byte array.
    • b"inc": If the command is "inc", increment the counter by 1.
    • b"dec": If the command is "dec", decrement the counter by 1.
    • b"get": If the command is "get", send the current value of counter as a reply message.
    • _: An underscore represents any other command, which gets ignored.

4. unsafe { COUNTER = counter };:

  • This line updates the global COUNTER variable with the modified value of counter.
  • unsafe is again used to acknowledge mutability risks.


Done with the code, now in your terminal run the command below to build your smart contract into a wasm file, which then deploys on the Vara Network.

cargo build --release 


After the build is done, your wasm file should be generated at this location.

rockyessel@UBUNTU-ROCKY:~/Desktop/lleryo/3.0/contract$ tree
.
├── ...
└── target
    ├── ...
    └── wasm32-unknown-unknown
        └── release
            ├── contracts.opt.wasm -----> This is what will use for the deployment.
            └── ...

4 directories, 8 files
rockyessel@UBUNTU-ROCKY:~/Desktop/lleryo/3.0/contract$ 


Now head over to the deployment website.

Program Deployment Page

Let’s change and make you're on the testnet, so at the sidebar bottom down, click on “Vara Network“, then select the testnet, and click on the “Switch “ button.

Vara Network Selection

The next step is to connect your wallet, I provided you a link on how to create your wallet. Now, after connecting, we need to get a test token from Vara, so at the Navbar right-hand side, the first icon with Gear and Dollar in it, click on it, pass the “I’m not a robot“ challenge, then you show to receive your token, which will be a 100 TVARA(Test Token).


Test Token(TVARA)


Now that your account has a token, click on the “upload program” button, then select your smart contract file({{contract name}}.opt.wasm), after selecting the file, set the Gas limit to 10, and click on the (10+), then on the “Calculate

Upload Field View


There’s something I want you to note when you click on the calculate, then you get the result below, it usually means that your smart contract can be deployed, and there’s no error at all.

So click the “Upload Program“ to deploy your contract.

Uploading Smart Contract File(WASM)

Click on the submit, to start the deployment process.

Deployment Process


After submitting, you’ll be asked to approve the transaction from your wallet to deploy your smart contract. so approve and at the right bottom corner. You’ll see the following pop-ups below.


Upload confirmation

Now, that you have successfully deployed your contract, the next step is to go to the Programs and click on your contract with the “contract” if you followed this article.

I

Smart Contract

Now I want you to take the next step yourself to interact with the smart contract by visiting this link here. As someone deeply passionate about Gear and Vara, I invite you to subscribe to my newsletter for the latest articles. Join the community where both Gear and Vara enthusiasts come together to create something truly captivating. I’ll provide you with vital links to learn more about what you learnt in this guide/tutorial.

Further Exploration & Resources

I crafted this content to provide education and insights for developers, whether you're just starting or have experience, and are eager to delve into the world of decentralization and its associated ecosystem and tools.


As for me, the links provided above and below are not affiliated links. I encourage developers to explore these resources to gain a deeper understanding of Gear and Vara, beyond what I've covered in this discussion.



Final thought

In the end, the reason I shared such insight is to serve as an invitation to developers to join the dynamic world of blockchain, contribute to its growth, and future, and harness the transformative power it holds for all the applications you’ll build. So I edge you whether you're a seasoned developer or just starting, the blockchain ecosystem awaits your exploration, innovation, and contribution.