Your First Solana Smart Contract Using Anchor
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
-
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 -
Install Anchor: You can install the Anchor CLI using Cargo (Rust's package manager) with the following command:
cargo install anchor-cli --locked -
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:
-
Open your terminal and navigate to the directory where you want to create your project.
-
Run the following command to generate a new Anchor project:
anchor init my_first_solana_contractThis command will create a new directory called
my_first_solana_contractwith the necessary files and folder structure. -
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
-
Open the
lib.rsfile located in theprograms/my_first_solana_contract/srcdirectory. This is where you will define your smart contract logic. -
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>, } -
This contract allows you to initialize a counter and increment it. The
initializefunction sets the counter to zero, while theincrementfunction 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
-
Open the
tests/my_first_solana_contract.jsfile 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
-
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.
-
Deploy your contract with the following command:
anchor deploy -
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:
-
Initialize the Counter:
anchor run initialize --program your_program_id -
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 →Keep reading
A Comprehensive Guide to Account Management in Solana
Solana account management — comprehensive guide covering everything you need to know.
Getting Started Solana DevelopmentA Deep Dive into Solana Accounts: Structures and Use Cases
Solana account structures — comprehensive guide covering everything you need to know.
Getting Started Solana DevelopmentBest Resources for Solving Development Issues on Solana
Solana development resources — comprehensive guide covering everything you need to know.