跳至主要內容

How to Write Your First Anchor Program in Solana - Part 1

更新於
2025年11月26日

閱讀時間 6 分鐘

概覽

Programs are what Solana calls Smart Contracts--they are the engine that handles information and requests: everything from token transfers and Candy Machine mints to 'hello world' logs and DeFi escrow governance. Solana supports writing on-chain programs using Rust, C, and C++ programming languages. Anchor is a framework that accelerates building secure Rust programs on Solana. Let's build your first Solana Program with Anchor!

您將負責的工作內容

In this 2-part guide, you will create your first Solana program using Anchor and Solana Playground, a web-based tool for compiling and deploying Solana Programs. You will:

  • Initiate a new Solana Program
  • Deploy a new Program to Solana's Devnet
  • Create and send a 'Hello World' message
  • Implement an increment function to track how many times your program has been used (Part 2)

您需要準備的物品

  • Solana基礎知識
  • 具備 JavaScript/TypeScript 及 Rust 程式語言的基本知識
  • 一款現代化的網路瀏覽器(例如Google Chrome

啟動您的專案

Create a new project in Solana Playground by going to https://beta.solpg.io/. Solana Playground is a browser-based Solana code editor that will allow us to get up and running with this project quickly. You're welcome to follow along in your own code editor, but this guide will be tailored to Solana Playground's required steps. First, click "Create a new project":

Enter a project name, "Hello World," and select "Anchor (Rust)":

Click the "Create" button. Solana Playground will initiate your project. Open lib.rs and remove the default text starting at line 7, after the declare_id! statement. Your environment should look like this:

建立並連結錢包

由於此專案僅供示範之用,我們可以使用一個「一次性」錢包。透過 Solana Playground 即可輕鬆建立一個。您應該會在瀏覽器視窗的左下角看到一個標有「未連線」的紅色圓點。請點擊它:

Solana Playground 將為您生成一個錢包(您也可以匯入自己的錢包)。若您願意,歡迎將其儲存以備日後使用;準備就緒後,請點擊「繼續」。 系統將建立一個新錢包並連線至 Solana 開發網。Solana Playground 會自動向您的新錢包空投一些 SOL,但我們會額外請求少量 SOL,以確保有足夠的餘額來部署我們的程式。在瀏覽器終端機中,您可以使用 Solana CLI 指令。輸入`solana airdrop 2` 即可將 2 SOL 空投至您的錢包。此時您的錢包應已連線至開發網,餘額為 6 SOL:

你已經準備好了!讓我們開始動手吧!

Hello World

建立您的課程

Open lib.rs (the base library for all Solana on-chain Rust programs). We kept two lines of code from our template:

  1. use anchor_lang::prelude::*; imports anchor's key features.
  2. declare_id!("11111111111111111111111111111111"); sets the public key of your program. The default value, a string of 1's, will be overwritten when we build our program.

Below, create your hello_world program using the #[program] module (this is where all of our logic will be included):

#[program]
mod hello_world {
use super::*;

}

We define a new module, hello_world, using the program module and use super to allow us to use elements of the parent module (program).

After your hello_world module, create a new account struct, SayHello using #[derive(Accounts)]. This initial struct will not require any accounts to be passed in since we are just going to log a message:

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

Finally, we need a function in our program that we can call from our front end. Inside hello_world, after use super, declare a function, say_hello:

    pub fn say_hello(_ctx: Context<SayHello>) -> Result<()> {
msg!("Hello World!"); // Message will show up in the tx logs
Ok(())
}

This function will log a message to the Solana program logs using msg! and return a success value by calling Ok(()). Your Hello World program should look like this:

use anchor_lang::prelude::*;

declare_id!("11111111111111111111111111111111");

#[program]
mod hello_world {
use super::*;
pub fn say_hello(_ctx: Context<SayHello>) -> Result<()> {
msg!("Hello World!");
Ok(())
}
}

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

Compile and Deploy Your Program

Click 🔧 Build on the left side of your screen to compile your code and check for errors. You should see a log like this in your console:

You should notice that your declare_id! now has a Public Key--that is the key that will be used for your program.

Finally, let's deploy it to Devnet. Click the Tools Icon 🛠 on the left side of the page, and then click "Deploy":

This will likely take a minute or two, but on completion, you should see something like this in your browser terminal:

Call Your Program from a Client

Navigate back to the "Files" tab. You may have already noticed that Solana Playground has a client section. This is a handy way to interact with our program directly from the same window. Go ahead and expand the 'client' toggle and open client.ts.

We will use TypeScript to write a simple function that calls our say_hello function. Replace the code in client.ts with:

console.log(pg.wallet.publicKey.toString(), "saying hello:");
// Fetch the latest blockhash
let latestBlockhash = await pg.connection.getLatestBlockhash('finalized');

// Create a Solana transaction for the say_hello method
const tx = await pg.program.methods
.sayHello()
.transaction();

// Send and confirm the transaction and log the tx URL
const txid = await web3.sendAndConfirmTransaction(pg.connection, tx, [pg.wallet.keypair])
console.log('Transaction Complete: ',`https://explorer.solana.com/tx/${txid}?cluster=devnet`);

Here's a breakdown of what we're doing here:

  1. Fetching the latest blockhash.
  2. Using Anchor's helpful tools, we call our say_hello method (note here in TypeScript it is formatted sayHello). Anchor is actually doing a bunch behind the scenes here. First, pg.program is drawing a connection to our Program through an IDL (Interactive Data Language), which is effectively a .json file that maps your rust Program to methods that can be called by the client. We will go into them in more detail in another guide, but if you want to explore your project's IDL, you can access it in your projects "🛠 Build & Deploy" tab. If you have built on Solana before, you may notice that our method is not passing any accounts in our transaction. Since Anchor knows what program we are calling, it is taking care of that for us behind the scenes.
  3. Finally, we wait for the cluster to confirm the transaction and log the results.

Go ahead and click "▶️ Run" in the left sidebar. You should see a log of your transaction URL:

Click it and scroll to the bottom of the transaction logs on Solana Explorer. Hello?

Great job! You now have a program that can allow the client to interact with the cluster.

總結

Nice work, and congrats on your first Solana Program! This is a substantial first step towards your path as a Solana Developer. Want to keep building? In Part 2 of this Guide, we add functionality to this same Program to store a count on-chain of how many times we call hello_world.

如果你遇到困難、有任何疑問,或是單純想聊聊你正在開發的專案,歡迎在DiscordTwitter 上聯絡我們!

我們 ❤️ 您的回饋!

如果您對這份指南有任何意見或建議,請告訴我們。我們非常樂意聽取您的意見。

其他資源

分享這份指南