How to Develop Programs(Smart Contracts) on Solana Blockchain?

Introduction

Smart contracts are programs deployed on the blockchain that autonomously execute predefined functions when triggered by specific conditions. These programs are written in programming languages like Rust and executed within the Solana runtime environment. By using Solana's high-performance blockchain infrastructure, smart contracts on Solana can process a large volume of transactions at lightning speed, making them suitable for applications requiring high throughput and low latency. Smart contracts have revolutionized the way transactions are conducted on blockchain networks.

These self-executing contracts, encoded with predefined rules and conditions, automate and facilitate the exchange of digital assets without the need for intermediaries. Their significance lies in their ability to enhance transparency, security, and efficiency in various industries, including finance, supply chain management, and decentralized applications (dApps). To understand the Programs and Accounts mechanism in Solana, explore the following article.

programs

Advantages of Using Solana for Smart Contract Development

  • Scalability: Solana's innovative architecture enables horizontal scalability, allowing the network to handle a high volume of transactions without compromising performance. This scalability is crucial for applications requiring real-time interactions and high throughput.
  • High Throughput: Solana is capable of processing thousands of transactions per second, making it suitable for applications that require fast and efficient transaction processing.
  • Low Latency: Transactions on Solana are confirmed within milliseconds, providing near-instant finality and enabling real-time interactions between users and applications.
  • Low Transaction Costs: Solana's efficient design minimizes transaction fees, making it cost-effective for developers and users to interact with smart contracts on the network.
  • Decentralization: Solana maintains decentralization through its permissionless network of distributed validator nodes, ensuring security, censorship resistance, and robustness against single points of failure.

Setting up the development environment

Explore the following article to set up the development environment.

Create new workspace

After finishing the setup let's create a new workspace using Anchor. Run the following command to create a new workspace.

anchor init <YOUR_WORKSPACE_NAME>

Output

anchor-init

If you face any error then make sure you have installed 'yarn' or 'node.js' in your system. Now our workspace is created navigate to the workspace directory using the following command.

cd <YOUR_WORKSPACE_NAME>

Open this directory into your favorite IDE. If you want to open it on VS Code then type 'code .' in the terminal and hit enter. Open the 'lib.rs' file that is located in the 'programs/src' directory. The initial code of this file will be as follows.

initial-code

Let's break down this code line by line.

Importing Anchor crate

use anchor_lang::prelude::*;

This line imports the prelude module from the anchor_lang crate. The prelude module typically contains commonly used items, structures, and traits that are often needed when working with the Anchor framework. Importing it with the wildcard (*) brings all these items into the current scope, making them accessible without needing to specify their full paths.

Declaring program ID

declare_id!("6WUVexxGLLuRehEgrXf6nDqKzCzRg8cvhqmyhEGRM33B");

This line is using the declare_id! macro provided by Anchor to declare the program's ID on the Solana blockchain. The ID is a public key that uniquely identifies the program. The ID is typically generated based on a seed string, which can be arbitrary but should ideally be unique to the program.

Declaring program module

#[program]
pub mod hello_csharp {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        Ok(())
    }
}

This section defines a Solana program module named hello_csharp using the #[program] attribute. Within this module, there's a function called initialize, which serves as the entry point for the program. The function takes a Context struct with a type parameter Initialize as its argument. The Context struct contains information about the current program invocation, including accounts, instructions, and the program ID. The function returns a Result with an empty tuple () inside the Ok variant, indicating success.

Declaring struct

#[derive(Accounts)]
pub struct Initialize {}

This section defines a struct named Initialize using the #[derive(Accounts)] attribute. The Initialize struct represents the accounts required for the initialize function defined earlier. However, in this example, the struct is empty, indicating that the initialize function doesn't require any specific accounts to be passed to it. Let's modify the initialize function and add a message to that.

pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        msg!("Hello! C# Corner.");
        Ok(())
    }

Build program

Our program is ready. Now build this program by running the following command.

anchor build

If you are facing any version compatibility error with rustc and Solana, then run the following commands to update both.

rustc update

solana-install update

After updating these then again run the 'anchor build' command. Once the build is successful, you will get the output as follows.

anchor-build

Deploy program

Then deploy this into the blockchain on the localnet. To achieve this, run the following command.

anchor deploy

First, check what network we have selected by running the following command.

solana config get

If it is not your localhost, then run the following command to set it to localhost.

solana config set --url localhost

Now run the following command to deploy the program.

anchor deploy

When the deployment is successful, you will get the output as follows.

anchor-deploy

To view the information of our deployed program run the following command.

solana program show <PROGRAM_ID>

Output

program-show

It will display all the details related to that program.

So we have learned to develop the basic program using Anchor, in our upcoming articles we will learn to write some complex programs and also learn how to interact with the deployed program using client-side libraries.

Conclusion

Solana's high-performance blockchain infrastructure enables fast, efficient, and cost-effective smart contract development. Its scalability, high throughput, low latency, and low transaction costs make it an attractive platform for a wide range of applications. With tools like the Anchor framework, developers can easily create, deploy, and interact with smart contracts, revolutionizing various industries.