Zum Hauptinhalt springen

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

Aktualisiert am
26. November 2025

6 Minuten Lesezeit

Übersicht

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!

Ihre Aufgaben

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
  • Eine „Hello World“-Nachricht erstellen und versenden
  • Implementiere eine Inkrementierungsfunktion, um zu erfassen, wie oft dein Programm bereits verwendet wurde (Teil 2)

Was Sie benötigen

  • Basic knowledge of Solana Fundamentals
  • Grundkenntnisse in den Programmiersprachen JavaScript/TypeScript und Rust
  • Ein moderner Webbrowser (z. B. Google Chrome)

Starten Sie Ihr Projekt

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":

Geben Sie den Projektnamen „Hello World“ ein und wählen Sie „Anchor (Rust)“ aus:

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:

Eine Wallet erstellen und verbinden

Since this project is just for demonstration purposes, we can use a "throw-away" wallet. Solana Playground makes it easy to create one. You should see a red dot "Not connected" in the bottom left corner of the browser window. Click it:

Solana Playground will generate a wallet for you (or you can import your own). Feel free to save it for later use if you like, and click continue when you're ready. A new wallet will be initiated and connected to Solana devnet. Solana Playground airdrops some SOL to your new wallet automatically, but we will request a little extra to ensure we have enough for deploying our program. In the browser terminal, you can use Solana CLI commands. Enter solana airdrop 2 to drop 2 SOL into your wallet. Your wallet should now be connected to devnet with a balance of 6 SOL:

Du bist startklar! Los geht’s!

Hallo Welt

Erstellen Sie Ihr Programm

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::*; importiert die wichtigsten Funktionen von anchor.
  2. declare_id!("11111111111111111111111111111111"); legt den öffentlichen Schlüssel Ihres Programms fest. Der Standardwert, eine Zeichenkette aus Einsen, wird beim Kompilieren unseres Programms überschrieben.

Erstellen Sie im folgenden Abschnitt Ihr „hello_world“-Programm mithilfe des Moduls #[program] (hier wird unsere gesamte Logik untergebracht):

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

}

Wir definieren ein neues Modul namens „hello_world“ unter Verwendung des Moduls „program“ und nutzen „super“, um Elemente des übergeordneten Moduls („program“) verwenden zu können.

Erstellen Sie nach Ihrem „hello_world“-Modul eine neue Struktur namens „SayHello“ mit #[derive(Accounts)]. Für diese anfängliche Struktur müssen keine Konten übergeben werden, da wir lediglich eine Meldung protokollieren werden:

#[ableiten(Konten)]
pub struct SayHello {}

Zuletzt benötigen wir in unserem Programm eine Funktion, die wir von unserem Frontend aus aufrufen können. Deklarieren Sie innerhalb von „hello_world“ nach „use super“ eine Funktion namens „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 {}

Kompilieren und Bereitstellen Ihres Programms

Klicken Sie auf 🔧 „Build“ auf der linken Seite Ihres Bildschirms, um Ihren Code zu kompilieren und auf Fehler zu überprüfen. In Ihrer Konsole sollte nun ein Protokoll wie das folgende angezeigt werden:

Sie sollten feststellen, dass Ihre ` declare_id! ` nun über einen öffentlichen Schlüssel verfügt – das ist der Schlüssel, der für Ihr Programm verwendet wird.

Zum Schluss stellen wir es auf Devnet bereit. Klicken Sie auf das Symbol „Tools“ 🛠 auf der linken Seite und anschließend auf „Bereitstellen“:

Das wird wahrscheinlich ein oder zwei Minuten dauern, aber sobald der Vorgang abgeschlossen ist, sollte in Ihrem Browser-Terminal etwa Folgendes angezeigt werden:

Rufen Sie Ihr Programm von einem Client aus auf

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.

Wir werden TypeScript verwenden, um eine einfache Funktion zu schreiben, die unsere Funktion „say_hello“ aufruft. Ersetzen Sie den Code in „client.ts“ durch Folgendes:

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`);

Hier ist eine Übersicht darüber, was wir hier tun:

  1. Den neuesten Block-Hash abrufen.
  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. Schließlich warten wir darauf, dass der Cluster die Transaktion bestätigt, und protokollieren die Ergebnisse.

Klicken Sie nun in der linken Seitenleiste auf „▶️ Ausführen“. Sie sollten nun ein Protokoll mit der URL Ihrer Transaktion sehen:

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

Tolle Leistung! Du hast nun ein Programm, mit dem der Client mit dem Cluster interagieren kann.

Zusammenfassung

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.

Wenn du nicht weiterkommst, Fragen hast oder einfach nur darüber reden möchtest, woran du gerade arbeitest, schreib uns doch einfach auf Discord oder Twitter!

Wir ❤️ Feedback!

Wenn Sie Anregungen zu diesem Leitfaden haben, teilen Sie uns diese bitte mit. Wir freuen uns über Ihr Feedback.

Weitere Ressourcen

Diesen Leitfaden teilen