SolWipe logoSolWipeCheck Wallet
You might have SOL you don't know about. Check for free.
Getting Started Solana Development

Your First Solana Smart Contract Using Anchor

SW
SolWipe Team
··4 min read

To build your first Solana smart contract, you’ll be diving into the world of Anchor, a powerful framework that simplifies the development process. Anchor streamlines many of the complexities of Solana programming, allowing you to focus on writing efficient contracts in Rust. In this guide, we will walk you through the steps necessary to set up your project, create your smart contract, test it locally, and deploy it on the Solana blockchain.

Setting Up Your Project

Before you can start coding, you need to set up your development environment. This involves installing the necessary tools and creating a new Anchor project. Follow these steps to get started:

Prerequisites

  1. Install Rust: Rust is the programming language used for writing Solana smart contracts. You can install it using rustup by running:

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    
  2. Install Anchor: You can install the Anchor CLI using Cargo (Rust's package manager) with the following command:

    cargo install anchor-cli --locked
    
  3. Install Solana CLI: The Solana command-line interface is essential for interacting with the Solana blockchain. Install it by following the instructions on the Solana documentation.

Creating a New Anchor Project

Once you have everything installed, you can create a new project:

  1. Open your terminal and navigate to the directory where you want to create your project.

  2. Run the following command to generate a new Anchor project:

    anchor init my_first_solana_contract
    

    This command will create a new directory called my_first_solana_contract with the necessary files and folder structure.

  3. Navigate to your project directory:

    cd my_first_solana_contract
    

Congratulations! You have set up your first Solana smart contract project using Anchor.

Creating the Smart Contract

With your project set up, it’s time to write your first Solana smart contract. In this section, you'll define the logic of your contract using Rust.

Writing the Contract

  1. Open the lib.rs file located in the programs/my_first_solana_contract/src directory. This is where you will define your smart contract logic.

  2. Here’s an example of a simple counter contract:

    use anchor_lang::prelude::*;
    
    declare_id!("YourProgramIDHere");
    
    #[program]
    pub mod my_first_solana_contract {
        use super::*;
    
        pub fn initialize(ctx: Context<Initialize>) -> ProgramResult {
            let counter = &mut ctx.accounts.counter;
            counter.count = 0;
            Ok(())
        }
    
        pub fn increment(ctx: Context<Increment>) -> ProgramResult {
            let counter = &mut ctx.accounts.counter;
            counter.count += 1;
            Ok(())
        }
    }
    
    #[account]
    pub struct Counter {
        pub count: u64,
    }
    
    #[derive(Accounts)]
    pub struct Initialize<'info> {
        #[account(init, payer = user, space = 8 + 8)]
        pub counter: Account<'info, Counter>,
        #[account(mut)]
        pub user: Signer<'info>,
        pub system_program: Program<'info, System>,
    }
    
    #[derive(Accounts)]
    pub struct Increment<'info> {
        #[account(mut)]
        pub counter: Account<'info, Counter>,
    }
    
  3. This contract allows you to initialize a counter and increment it. The initialize function sets the counter to zero, while the increment function increases the counter by one.

Building the Contract

To compile your contract, run the following command from the root of your project:

anchor build

This will compile your Rust code into a binary that can be deployed on the Solana blockchain.

Testing Your Contract Locally

Testing is an essential part of smart contract development. Anchor provides built-in support for testing using Mocha and JavaScript.

Writing Tests

  1. Open the tests/my_first_solana_contract.js file to create your tests. Here is an example of how to test the counter contract:

    const anchor = require('@project-serum/anchor');
    const { SystemProgram } = anchor.web3;
    
    describe("my_first_solana_contract", () => {
        const provider = anchor.Provider.local();
        anchor.setProvider(provider);
    
        it("Initializes the counter!", async () => {
            const program = anchor.workspace.MyFirstSolanaContract;
            const counter = anchor.web3.Keypair.generate();
    
            await program.rpc.initialize({
                accounts: {
                    counter: counter.publicKey,
                    user: provider.wallet.publicKey,
                    systemProgram: SystemProgram.programId,
                },
                signers: [counter],
            });
    
            const account = await program.account.counter.fetch(counter.publicKey);
            console.log("Counter: ", account.count.toString());
            assert.equal(account.count.toString(), "0");
        });
    
        it("Increments the counter!", async () => {
            const program = anchor.workspace.MyFirstSolanaContract;
            const counter = anchor.web3.Keypair.generate();
    
            await program.rpc.initialize({
                accounts: {
                    counter: counter.publicKey,
                    user: provider.wallet.publicKey,
                    systemProgram: SystemProgram.programId,
                },
                signers: [counter],
            });
    
            await program.rpc.increment({
                accounts: {
                    counter: counter.publicKey,
                },
            });
    
            const account = await program.account.counter.fetch(counter.publicKey);
            assert.equal(account.count.toString(), "1");
        });
    });
    

Running Tests

To run your tests, execute the following command:

anchor test

This command will compile your program and run the tests you created. If everything is set up correctly, you should see output confirming that your tests passed.

Deploying and Interacting with Your Contract

After successfully testing your contract locally, the next step is to deploy it to the Solana blockchain.

Deploying the Contract

  1. Make sure you have your Solana wallet set up and have some SOL in it. You can get SOL from a faucet or by transferring from an exchange.

  2. Deploy your contract with the following command:

    anchor deploy
    
  3. This command will upload your compiled contract to the Solana blockchain. After a successful deployment, you will receive a program ID, which you will need to interact with your contract.

Interacting with Your Contract

You can interact with your deployed contract using the Anchor CLI or through a front-end application. Here's how to call the initialize and increment functions using the CLI:

  1. Initialize the Counter:

    anchor run initialize --program your_program_id
    
  2. Increment the Counter:

    anchor run increment --program your_program_id
    

Additional Resources

To learn more about Solana programming and smart contracts, consider exploring the following topics:

By following these steps, you have successfully created, tested, and deployed your first Solana smart contract using Anchor. With your foundational knowledge in place, you can now explore more complex smart contracts and further develop your skills in Rust for smart contracts.

If you need assistance managing your token accounts or recovering locked SOL rent, check out the SolWipe guide for a comprehensive overview of using the SolWipe tool. Start your journey into Solana development today!

Recover your hidden SOL now

Connect your wallet, scan for free, and claim your locked SOL in under 30 seconds.

Find My Hidden SOL →

More from SolWipe

View all articles →
Advanced Wallet Features Multisig

10 Best Tools for Managing Squads on Solana

Squad management in the Solana ecosystem is essential for teams looking to streamline their operations and enhance collaboration. With the rise of decentralized finance and blockchain applications, managing squads effectively has become crucial. Utilizing the

Feb 20, 2026
Decentralized Storage Computing Filecoin

10 Best Use Cases for the Akash Network in 2026

The Akash Network is revolutionizing the way we think about cloud computing by providing a decentralized platform for hosting applications and services. By connecting users in need of cloud resources with providers who have excess computing power, Akash Networ

Feb 20, 2026
Privacy Cryptocurrency Mixers Zeroknowledge

10 Crypto Mixers You Should Know About in 2026

When it comes to maintaining crypto anonymity, using top crypto mixers is a crucial step for individuals looking to enhance their privacy in transactions. As the landscape of cryptocurrency continues to evolve, ensuring your digital footprint remains discreet

Feb 20, 2026
Solana Blockchain Explorers Analytics

10 Must-Know Solana Data Tools for Investors in 2023

Investing in the Solana blockchain can be both exciting and daunting. With its rapid growth and innovative technology, the need for effective Solana data tools for investors is more crucial than ever. These tools help you make informed decisions, analyze marke

Feb 20, 2026
Blockchain Technology Fundamentals Blockchains

10 Ways Consensus Algorithms Impact Blockchain Performance

Consensus algorithms are a foundational element of blockchain technology, determining how transactions are validated and how nodes in the network come to an agreement. Understanding how consensus algorithms impact blockchain performance is crucial for anyone i

Feb 20, 2026
Sol Investing Fundamentals Buying

2023 Solana Investment Trends: What You Need to Know

The Solana blockchain has gained significant traction in the crypto space, and understanding the Solana investment trends for 2023 can help you make informed decisions. As the ecosystem evolves, it’s essential to stay updated on market dynamics, emerging use c

Feb 20, 2026