Настройка, создание и развертывание локальной программы Solana в Rust

Rust - это наиболее распространенный язык программирования для написания программ Solana . Это руководство для быстрого запуска продемонстрирует, как быстро установить, собрать и установить вашу программу на основе Rust Solana в блокчейне.

Do you have the Solana CLI installed?

В этом руководстве используется Solana CLI и предполагается, что вы установили вашу среду разработки в локальном режиме. Checkout our local development quickstart guide here to quickly get setup.

Чему вы научитесь #

  • как установить язык Rust локально
  • как инициализировать новую программу Solana Rust
  • как написать базовую программу Solana на Rust
  • как создать и установить свою программу Rust

Установка Rust и Cargo #

Чтобы иметь возможность компилировать программы Solana на основе Rust, установите язык Rust и Cargo (менеджер пакетов Rust) с помощью Rustup:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Запустите валидатор на локальном хосте #

The Solana CLI comes with the test validator built in. This command line tool will allow you to run a full blockchain cluster on your machine.

solana-test-validator
PRO TIP

Запустите тест Solana в новом/отдельном окне терминала , которое останется открытым. Эта программа командной строки должна оставаться запущенной, чтобы ваш валидатор localhost оставался в режиме онлайн и был готов к работе.

Настройте Solana CLI на использование валидатора localhost для всех будущих команд терминала и развертывания программ Solana:

solana config set --url localhost

Создайте новую библиотеку Rust с помощью Cargo #

Solana programs written in Rust are libraries which are compiled to BPF bytecode and saved in the .so format.

Инициализируйте новую библиотеку Rust с именем hello_world через командную строку Cargo:

cargo init hello_world --lib
cd hello_world

Добавьте solana-program в вашу новую библиотеку Rust:

cargo add solana-program
Pro Tip

Настоятельно рекомендуется держать вашу solana-program и другие Solana Rust зависимостей в соответствии с установленной версией Solana CLI. For example, if you are running Solana CLI 2.0.3, you can instead run:

cargo add solana-program@"=2.0.3"

This will ensure your crate uses only 2.0.3 and nothing else. Если у вас возникли проблемы с совместимостью зависимостей Solana, загляните в Solana Stack Exchange

Откройте файл Cargo.toml и добавьте эти необходимые параметры конфигурации библиотеки Rust, изменив при необходимости имя проекта:

[lib]
name = "hello_world"
crate-type = ["cdylib", "lib"]

Создайте свою первую программу Solana #

Код программы Solana на основе Rust будет отображаться в вашем файле src/lib.rs. Внутри src/lib.rs вы сможете импортировать ваш ящик Rust и определить логику. Откройте файл src/lib.rs в вашем любимом редакторе.

В верхней части lib.rs, импортируйте ящик solana-program и принесите нам необходимые элементы в локальное пространство имен:

use solana_program::{
    account_info::AccountInfo,
    entrypoint,
    entrypoint::ProgramResult,
    pubkey::Pubkey,
    msg,
};

Каждая программа Solana должна определить entrypoint, который рассказывает Solana время выполнения, где начать выполнение кода onchain. Точка входа вашей программы должна предоставлять публичную функцию с именем process_instruction:

// declare and export the program's entrypoint
entrypoint!(process_instruction);
 
// program entrypoint's implementation
pub fn process_instruction(
    _program_id: &Pubkey,
    _accounts: &[AccountInfo],
    _instruction_data: &[u8]
) -> ProgramResult {
    // log a message to the blockchain
    msg!("Hello, world!");
 
    // gracefully exit the program
    Ok(())
}

Каждая программа в цепи должна вернуть Ok result enum со значением (). Это говорит среде выполнения Solana, что ваша программа выполнена успешно и без ошибок.

This program above will simply log a message of "Hello, world!" to the blockchain cluster, then gracefully exit with Ok(()).

Создайте программу Rust #

В окне терминала вы можете собрать программу Solana Rust, запустив ее в корне проекта (т.е. в директории с файлом Cargo.toml):

cargo build-sbf
Info

После каждой сборки программы Solana приведенная выше команда будет выводить путь сборки файла .so вашей скомпилированной программы и ключевой файл по умолчанию который будет использоваться для адреса программы. cargo build-sbf installs the toolchain from the currently installed solana CLI tools. Вам может понадобиться обновить эти инструменты, если вы столкнетесь с несовместимостью версий. In case you get an error like: error while loading shared libraries: librustc_driver-278a6e01e221f788.soyou may need to go to ~/.cache/solana/ and rm -rf the platform tools there and then run cargo build-sbf again.

Развертывание программы Solana #

Используя Solana CLI, вы можете развернуть свою программу на выбранном в данный момент кластере:

solana program deploy ./target/deploy/hello_world.so

Once your Solana program has been deployed (and the transaction finalized), the above command will output your program's public address (aka its "program id").

# example output
Program Id: EFH95fWg49vkFNbAdw9vy75tM7sWZ2hQbTTUmuACGip3

Поздравляем! #

Вы успешно настроили, собрали и развернули программу Solana на языке Rust.

Look at your program!

You can use the Solana Explorer to look at your newly deployed program. The explorer also works on localnet, you can open the Solana Explorer on localnet and just paste your programId in the search bar.

Let's call the Hello World program #

Now that the program is deployed we want to call it to see the actual "Hello World" on chain. For that we will use Javascript and the Solana web3.js library.

Install Node.js #

To use node in WSL2 on Windows, please follow this
guide to installing node in WSL2 to install node.

sudo apt-get install curl
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash

reopen the terminal

nvm install --lts
node --version

For macOS you can install node.js via package manager

Create the client file #

Install the Solana web3.js library and the Solana helpers library:

npm install @solana/web3.js @solana-developers/helpers

Create a new file called client.mjs and add the following code:

import {
  Connection,
  PublicKey,
  Transaction,
  TransactionInstruction,
} from "@solana/web3.js";
import { getKeypairFromFile } from "@solana-developers/helpers";
 
const programId = new PublicKey("YOUR_PROGRAM_ID");
 
// Connect to a solana cluster. Either to your local test validator or to devnet
const connection = new Connection("http://localhost:8899", "confirmed");
//const connection = new Connection("https://api.devnet.solana.com", "confirmed");
 
// We load the keypair that we created in a previous step
const keyPair = await getKeypairFromFile("~/.config/solana/id.json");
 
// Every transaction requires a blockhash
const blockhashInfo = await connection.getLatestBlockhash();
 
// Create a new transaction
const tx = new Transaction({
  ...blockhashInfo,
});
 
// Add our Hello World instruction
tx.add(
  new TransactionInstruction({
    programId: programId,
    keys: [],
    data: Buffer.from([]),
  }),
);
 
// Sign the transaction with your previously created keypair
tx.sign(keyPair);
 
// Send the transaction to the Solana network
const txHash = await connection.sendRawTransaction(tx.serialize());
 
console.log("Transaction sent with hash:", txHash);
 
await connection.confirmTransaction({
  blockhash: blockhashInfo.blockhash,
  lastValidBlockHeight: blockhashInfo.lastValidBlockHeight,
  signature: txHash,
});
 
console.log(
  `Congratulations! Look at your ‘Hello World’ transaction in the Solana Explorer:
  https://explorer.solana.com/tx/${txHash}?cluster=custom`,
);
Info

Don't forget to replace YOUR_PROGRAM_ID with the program ID you got from the deployment step.

Run the client #

Now lets use node run this file to see the "Hello World" on chain.

node client.mjs

You should see the following output:

Congratulations! Look at your ‘Hello World’ transaction in the Solana Explorer:
  https://explorer.solana.com/tx/2fTcQ74z4DVi8WRuf2oNZ36z7k9tGRThaRPXBMYgjMUNUbUSKLrP6djpRUZ8msuTXvZHFe3UXi31dfgytG2aJZbv?cluster=custom
Congrats

If you follow the link you should be able to see your 'Hello World' transaction on the Solana explorer.

Deploy to Solana devnet #

Now you have successfully deployed your program to your local cluster. If you want to deploy it to the public devnet to show your program to your friends you can do so by running the following command:

solana program deploy ./target/deploy/hello_world.so --url https://api.devnet.solana.com

Then change the connections url in your client.mjs also to https://api.devnet.solana.com and run the client again.

node client.mjs

You should see the same output as before but now on the public devnet cluster. You can see the transaction in the Solana Explorer again. Now you just need to switch it to devnet on the top right.

Congratulations, now everyone in the world can see your "Hello World" transaction on the Solana blockchain.

Следующие шаги #

По ссылкам ниже вы можете узнать больше о написании программ Solana на основе Rust: