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.
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.
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 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.
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.
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.
Fear not, I've been digging deep and unearthed some key components to map your learning journey:
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.
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.
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!
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.
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.
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.
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.
Cross-Chain Platforms: Cross-chain platforms facilitate interactions and transactions between different blockchain networks. Examples are Thorchain and Wrapped Tokens.
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.
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:
The terms "Smart Contracts," "Networks," and "Tokens" are essential concepts in the context of blockchain and cryptocurrency. Here's a brief explanation of each:
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 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:
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.
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;
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):
Vara Network is NPoS(Nominated Proof-of-Stake).
Layer-2 (Scaling Solutions):
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.
When I was defining Vara Network, I mentioned Gear Procotol, so probably you’re wondering what is it.
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:
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.
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:
Interoperability Potential:
Development Tools and Languages:
Community and Collaboration:
It's important to remember:
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.
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.
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:
Benefits Compared to Shared Memory Models:
Specific Features of Vara Network's Actor Model:
Comparison to Other Blockchain Platforms:
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.
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:
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:
Unlocking Web3 for Web2 Developers:
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.
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:
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;
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",
]
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]
:
2. use gstd::{msg, prelude::*};
:
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]
:
4. extern "C" fn handle() {}
:
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.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 inc
, dec
, 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");
:
command
variable.expect
method panics, terminating the contract execution with an error message.2. let mut counter = unsafe { COUNTER };
:
COUNTER
variable.COUNTER
is declared with mut
, we need unsafe
to acknowledge potential mutability risks (explained later).counter
, which allows modification.3. match command.as_slice() { ... }
:
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 };
:
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.
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.
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).
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“
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.
Click on the submit, to start the 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.
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
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.
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.
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.