The Hackett Group Announces Strategic Acquisition of Leading Gen AI Development Firm LeewayHertz
Select Page

How to Build & Deploy Smart Contracts on Solana?

Anatoly Yakovenko introduced Solana in 2017 with the vision to eliminate scalability issues in the existing blockchains. On a standard gigabit network, Solana can process up to 710,000 transactions per second if transactions, on average, do not exceed 176 bytes. The platform emerges as the fastest-growing ecosystem compatible with global adoption with great capabilities and many innovative features.

The platform has been architectured to empower growth and frequency-oriented decentralized applications, crucial for setting up a permissionless financial system. With more than 400 projects spanning Web3, DeFi, NFTs, and so on, Solana blockchain claims to be the world’s fastest blockchain and rapidly growing ecosystem.

Solana pioneers proof-of-history consensus to achieve high speed and scalability. It secures a position among top-performing blockchains with great scalability and excellent throughput capabilities. Thus Solana network is expanding with many new projects. So, let’s understand the underlying concept of the Solana blockchain and learn how to build & deploy smart contracts on top of Solana.

What is Solana?

Solana is a decentralized blockchain ecosystem designed to avoid the congestion and scalability issues prevalent in the existing blockchains. The blockchain has its core focus on improving scalabilities such as higher transaction per second (TPS) and fast confirmation times. It’s an open-source project comprised of revolutionary technologies from Intel, Netscape, Google, Qualcomm to support Solana in maintaining high-performing standards. For in-depth analysis about Solana, read our insight dedicated entirely to Solana.

What’s the Architecture of Solana Smart Contract?

Solana’s smart contract model differs from traditional EVM-enabled blockchains. Traditional EVM-based contract combines code/logic and state into a single contract that is deployed on-chain. In contrast, a smart contract on Solana remains on read-only or stateless mode and contains program logic only. Once the smart contract is deployed, it can be accessed by external accounts, and these accounts interact with the program to store program interaction-related data.

This way, the logical separation of state (accounts) and contract logic (programs) happens, which is a significant difference between traditional EVM-enabled and Solana smart contracts. Moreover, accounts on Solana and other blockchains (like Ethereum) are also quite different. Account on Solana stores data (like wallet information) in contrast to Ethereum accounts that are just the references for users’ wallets.

In addition, Solana comes with a CLI and JSON RPC API to enhance DApps’ interaction with the Solana. Moreover, decentralized applications can also use existing SDKs to interact with the blockchain and programs on Solana.
Architecture of Solana Smart Contract

  • In the above diagram, the Program on the right represents the development workflow that allows users to create and deploy custom Rust, C, C++ programs on the Solana blockchain.
  • Once these programs are successfully deployed, anyone who is versed with programming skills can use them. To communicate with these programs, users need to write dApps with any available client SDKs and use the JSON RPC API under the hood.
  • Under the second development workflow, Client (on the bottom right), users can write decentralized apps for communicating with the deployed programs. These apps submit transactions to these programs via client SDK and can create various applications like crypto wallets, decentralized exchanges, and more.
  • The two pieces of workflow- Program and Client function together to form a complete network of dApps and programs that can interact to update the state and examine the blockchain.

How to build a smart contract on Solana?

Under this section, you will learn to create and deploy a Solana smart contract called ‘hello world.’ HelloWorld is written in Rust programming language that prints output to the console. Before starting the development, the first step is to set up a Solana environment on Windows to make the work easier.

1. Set Up A Solana Development Environment

Running the smart contract code directly from Windows is confusing for many people. Hence, it’s recommended to set up a Ubuntu version of WSL (window Subsystem for Linux) so that you can write the code in Windows and then compile the Rust smart contract into a .so file.

Here are the commands to set up the Solana development environment:

apt upgradeapt updateapt install nodejsapt install npmapt install python3-pipcurl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shsh -c "$(curl -sSfL https://release.solana.com/v1.5.7/install)"source $HOME/.cargo/envexport PATH="/root/.local/share/solana/install/active_release/bin:$PATH"export RUST_LOG=solana_runtime::system_instruction_processor=trace,solana_runtime::message_processor=debug,solana_bpf_loader=debug,solana_rbpf=debugsolana-test-validator --log

Next, run the Hello World application to test it:

git clone https://github.com/solana-labs/example-helloworld.git  cd example-HelloWorld/npm installnpm run build:program-rust

2. Create Solana smart contract in Rust programming language

Requisites:

You require the following installation for deploying smart contracts:

  • NodJS v14 or greater and NPM
  • The latest stable Rust build
  • Solana CLI v1.7.11 or later
  • Git

 

Modular blockchain solutions for new-age enterprise software

Build on Solana with LeewayHertz.

About the HelloWorld Program

HelloWorld is a program or smart contract that prints output to the console. In addition, it also counts the exact number of times the HelloWorld program has been called for the given account, along with storing this number on-chain. Let’s understand its concept by breaking down the code into separate sections.

The first section specifies some standard parameters for the Solana program and determines an entry point for the program (the ‘process_instruction’ function). Apart from this function, this section uses borsh (Binary Object Representation Serializer for Hashing) to serialize and deserialize parameters that pass to and from the deployed program.

Use the given command to setup the HelloWorld program:

use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint,
entrypoint::ProgramResult,
msg,
program_error::ProgramError,
pubkey::Pubkey,
};
/// Define the type of state stored in accounts
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct GreetingAccount {
/// number of greetings
pub counter: u32,
}
// Declare and export the program's entrypoint
entrypoint!(process_instruction);

Next, the process_instruction function accepts the program_id, a public key where the program is being deployed and the accountInfo, which is the account used to say hello to.

pub fn process_instruction(
program_id: &Pubkey, // Public key of the account the hello world program was loaded into
accounts: &[AccountInfo], // The account to say hello to
_instruction_data: &[u8], // Ignored, all helloworld instructions are hellos

The ProgramResult stores the main logic of the program. In this case, the ProgramResult prints a message and then chooses the desired account from the ‘accounts.’ However, we use only one account for our example.

) -> ProgramResult {
msg!("Hello World Rust program entrypoint")
// Iterating accounts is safer then indexing
let accounts_iter = &mut accounts.iter();
// Get the account to say hello to
let account = next_account_info(accounts_iter)?;

After that, the program determines if it has permission to modify data for the particular account.

// The account must be owned by the program in order to modify its data
if account.owner != program_id {
msg!("Greeted account does not have the correct program id");
return Err(ProgramError::IncorrectProgramId);
}

Finally, the function fetches the existing account’s stored number, raises the value by 1, writes back the result, and displays a message.

// Increment and store the number of times the account has been greeted
let mut greeting_account = GreetingAccount::try_from_slice(&account.data.borrow())?;
greeting_account.counter += 1;
greeting_account.serialize(&mut &mut account.data.borrow_mut()[..])?;
msg!("Greeted {} time(s)!", greeting_account.counter);
Ok(())

 

3. Deploy the Smart Contract

The first step to deploying the program or smart contract is to clone the repository.

git clone https://github.com/solana-labs/example-helloworld 
cd example-HelloWorld

Once this is done, you can set the current environment to Devnet, the test network for Solana developers to write smart contracts.

solana config set --url https://api.devnet.solana.com 

After this, you are required to create a new keypair. This keypair allows your account to interact with the deployed programs or smart contracts on the Solana Devnet. However, this method is deemed insecure for storing keys and is only useful for demo purposes. Thus, you will be promoted to passphrase for security reasons.

Solana-keygen new --force

Once you create an account, you can use the airdrop program and obtain the required SOL tokens. For this, you also need some imports for the smart contract deployment. Use this command to request SOL tokens into your newly generated account:

Solana airdrop 5

Now, you are all set to build the hello world program. Use the below command to build it.

npm run build:program-rust

After the program is built, deploy it to Devnet. With the previous command’s output, you get the commando to run the program, which looks similar to the following:

Solana program deploy dist/program/HelloWorld.so

With that, you have successfully deployed the Hello World programs to Devnet along with an assigned program Id. You can authenticate the program on the Solana Devnet explorer.

Solana Blockchain Development by LeewayHertz

Solana is a high-performing and fast-developing blockchain with superior scalability. As a protocol, it supports the development of different types of smart contracts for powering dApps like P2P lending systems, NFT marketplaces, Wallets, DEXs, and much more.

At LeewayHertz, we provide end-to-end Solana blockchain development services – Blockchain Consulting, DApp Development, NFT Marketplace Development, SPL Token Development, Exchange Integration, Wallet Development, Node Development & Maintenance, Smart Contract Development & Audit, and Defi Development.

After demonstrating an example of smart contract development on Solana, here is a glimpse of our dApp development process.

  • Finalizing the scope and collecting criteria
  • Creating a suitable UI design for the decentralized app
  • Writing smart contracts for the decentralized app
  • Smart contract auditing
  • Developing the necessary features of DApp
  • Front and back-end integration of smart contracts
  • Testing the developed application using test cases
  • Mainnet deployment for the DApps

Our DApps development services meet the client’s needs and help them launch user-friendly decentralized applications powered by the scalability and speed of the Solana network.

Conclusion

With more industries adopting blockchain and decentralized technology, the use of decentralized apps continues to grow. As a high-speed, scalable, and low-cost ecosystem, Solana facilitates the development of fast and scalable smart contracts & decentralized applications. Also, it publishes frequent updates. Developers like us are excited to develop on Solana for it offers a bundle of new-age resources like frameworks, SDKs, and developers tools. In addition, the platform has intrusive tools like Solana CLI (it allows users to interact with the protocol via command line) and Solana explorer (it allow users to search transactions and accounts over various Solana clusters.)

If you are looking for Solana development services, please get in touch with our Solana blockchain developers.

Author’s Bio

 

Akash Takyar

Akash Takyar LinkedIn
CEO LeewayHertz
Akash Takyar is the founder and CEO of LeewayHertz. With a proven track record of conceptualizing and architecting 100+ user-centric and scalable solutions for startups and enterprises, he brings a deep understanding of both technical and user experience aspects.
Akash's ability to build enterprise-grade technology solutions has garnered the trust of over 30 Fortune 500 companies, including Siemens, 3M, P&G, and Hershey's. Akash is an early adopter of new technology, a passionate technology enthusiast, and an investor in AI and IoT startups.

Start a conversation by filling the form

Once you let us know your requirement, our technical expert will schedule a call and discuss your idea in detail post sign of an NDA.
All information will be kept confidential.

Our Insights

Follow Us