Blockchain Development Engineer 2022-05-14 03:57:19 阅读数:32
In this tutorial , We will learn how to develop Solana Chain program , The content includes creating Solana account number 、 Get free... From the test chain SOL、 Compile, deploy and test process , And develop a simple Solana Chain program . At the end of the tutorial, you can download the complete source code .
Before delving into this tutorial , Please make sure that you have followed This tutorial The steps in set up the environment and install the tool kit . You can visit here to see Solana RPC API file .
If you don't have your own node, don't worry ,Solana It provides the same configuration as the main network devnet. So here, let's start with API Endpoint Set as development chain - https://devnet.solana.com:
1 2 3 4 | [email protected]:~$ solana config set --url https://devnet.solana.com Config File: /home/ubuntu/.config/solana/cli/config.yml RPC URL: https://devnet.solana.com WebSocket URL: wss://devnet.solana.com/ (computed) |
Every program on the chain is actually a Account, But it is marked “Executable: true”, This means that it is an executable . To store this file , We need to create another one that can pay for Solana Account :
1 | solana-keygen new |
Enter the password and confirm , The new account is saved in /home/ubuntu/.config/solana/id.json
in , As our default key . You can run the following command to check the public key :
1 2 | [email protected]:~$ solana-keygen pubkey /home/ubuntu/.config/solana/id.json 7FqW6xXE4sMmZSeVxFsoTr83He4MhhePvA1vRAv9zgQf |
stay Solana On the test chain , You can run the following commands for free SOL In order to perform subsequent operations :
1 2 3 | [email protected]:~$ solana airdrop 10 7FqW6xXE4sMmZSeVxFsoTr83He4MhhePvA1vRAv9zgQf Requesting airdrop of 10 SOL from 34.82.57.86:9900 10 SOL |
Let's check our balance :
1 2 | [email protected]:~$ solana balance 7FqW6xXE4sMmZSeVxFsoTr83He4MhhePvA1vRAv9zgQf 10 SOL |
wow , rich .
Then we create another account , Used to store program files :
1 | solana-keygen new -o solana_memo_program.json |
ad locum , We use -o
Option to output the new key pair to a new file solana_memo_program.json .
from 1.4.x edition (2020-10-22 Release ) Start ,Solana Provides cargo-build-bpf and cargo-test-bpf Tools such as , Help us to cargo The project is compiled as BPF Format file .
have access to Solana The memo program provided by the official team to try this . First clone the warehouse :
1 | git clone https://github.com/solana-labs/solana-program-library.git |
Then jump to the folder solana-program-library/memo/program/ And run :
1 | cargo build-bpf |
This is the program we mentioned above cargo-build-bpf The wrapper . If you see the following error :
1 2 3 | = note: /usr/bin/ld: cannot find Scrt1.o: No such file or directory /usr/bin/ld: cannot find crti.o: No such file or directory collect2: error: ld returned 1 exit status |
That's because you lack some 32 Bit dependent package , Let's fix it by installing :
1 | sudo apt install gcc-multilib |
Then we compile again , obtain :
1 2 | To deploy this program: $ solana deploy /home/ubuntu/solana/solana-program-library/target/deploy/spl_memo.so |
Okay , Ready to deploy , Here we deploy it to the account we created and export it to a file solana_memo_program.json, Let's get the key first :
1 2 | solana-keygen pubkey ~/solana_memo_program.json D8Cnv1UcThay2WijWP4SQ8G683UuVsKPaZEU7TNVKW1j |
Then run the deployment :
1 2 | solana deploy /home/ubuntu/solana/solana-program-library/target/deploy/spl_memo.so ~/solana_memo_program.json {"programId":"D8Cnv1UcThay2WijWP4SQ8G683UuVsKPaZEU7TNVKW1j"} |
Now we have successfully deployed a program to the test company , Program address :D8Cnv1UcThay2WijWP4SQ8G683UuVsKPaZEU7TNVKW1j
To verify the results of the command line , Can be in Solana explorer Check our program on , go to https://explorer.solana.com/ And change the network to Devnet, Enter the program address , You might see :
Yes , Our program is right there !
In order to interact with our chain program , We need old friends here @solana/web3.js. Let's create a new js Project and add package @solana/web3.js:
1 2 | yarn init yarn add @solana/web3.js |
Then create a similar one in the root folder and test code index.js Entrance js file :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | var solana_web3 = require('@solana/web3.js'); function testMemo(connection, account){ const instruction = new solana_web3.TransactionInstruction({ keys: [], programId:new solana_web3.PublicKey('D8Cnv1UcThay2WijWP4SQ8G683UuVsKPaZEU7TNVKW1j'), data: Buffer.from('cztest'), }); console.log("account:", account.publicKey.toBase58()) solana_web3.sendAndConfirmTransaction( connection, new solana_web3.Transaction().add(instruction), [account], { skipPreflight: true, commitment: "singleGossip", }, ).then(()=>{console.log("done")}).catch((e)=>{console.log("error",e)}); }function main() { connection = new solana_web3.Connection("https://devnet.solana.com", 'singleGossip'); const account = new solana_web3.Account() const lamports = 10*1000000000 connection.requestAirdrop(account.publicKey, lamports).then(()=>{ console.log("airdrop done") testMemo(connection, account) }); } main() |
Let's see what happened here .
First connect to devnet Endpoint , And then we use solana_web3 Provided solana_web3.Account()
Function creation A new account , This account will be used to interact with our program later .
Then we go from devnet Get some free SOL , And then called this. testMemo function , This function sends a transaction to our program , Parameters are passed in as data streams ( Here we pass a string “ cztest ”)
Now? , Let's use Explorer again to check our Solana Program :
The transaction shown above , We can see the data in hexadecimal format , have access to binascii Tools like to decode this data :
1 2 3 | >>> import binascii >>> binascii.a2b_hex('637a74657374') b'cztest' |
Here we can see that the result is the same as the string we sent to the program
We just tried one from Solana official repo Program extracted from , So what should we do to write from scratch One Solana The program on the chain ? As an ordinary Rust project ,Solana The program on the chain is also made by cargo Managed .
First , Let's use cargo To start our new project :
1 | cargo new onchain_program |
Then open it with your favorite editor onchain_program/Cargo.toml And add some basic information to the project :
1 2 3 4 5 6 7 8 9 10 | [dependencies] arrayref = "0.3.6" num-derive = "0.3" num-traits = "0.2" num_enum = "0.5.1" solana-program = "1.4.8" thiserror = "1.0"[dev-dependencies] solana-sdk = "1.4.8"[lib] crate-type = ["cdylib", "lib"][package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] |
We also added a Xargo.toml file , Used in compiling bpf Cross platform is supported when file . Then it's time to do it yourself , Let's write some Rust Code . First of all we have src/lib.rs Add an entry point to :
1 2 3 | #![deny(missing_docs)]//! A simple program that return success.#[cfg(not(feature = "no-entrypoint"))] mod entrypoint;// Export current sdk types for downstream users building with a different sdk version pub use solana_program; |
Then in the entry file entrypoint.rs Add some code to :
1 2 3 4 5 6 7 8 9 10 11 12 | //! Program entrypointuse solana_program::{ account_info::AccountInfo, entrypoint, entrypoint::ProgramResult, program_error::ProgramError, pubkey::Pubkey, }; use std::str::from_utf8;entrypoint!(process_instruction); fn process_instruction( _program_id: &Pubkey, _accounts: &[AccountInfo], instruction_data: &[u8], ) -> ProgramResult { Ok(()) } |
This is a very simple program , We haven't done anything here , Just return success
function process_instruction Is the entire entry function we pass in the instruction structure . It contains all the information needed to execute the instruction : _program_id Show program ,_accounts Indicates all accounts required in this instruction ,instruction_data It means that we use it to convey Serialized data stream of other parameters . When the program works well , We use Ok(()) Return to success , Or use Err(error) Return failed .
If you're ready , Next, you can deploy the program as you did before :
1 2 | cargo build-bpf...To deploy this program: $ solana deploy /home/ubuntu/solana/memo_test/onchain_program/target/deploy/onchain_program.so |
With the help of Solana All tools and SDK, We can use cargo Easy access to target files . Once you understand the whole process , You'll find it's just a Rust project , It USES rustrc Provided LLVM Translate it into BPF Format file , Then we deploy it on the chain . What I want to mention is , Developing Solana On chain program , Not all Rust Features can be used , Details can be stay here find . If you use 1.3.x Version of the tool suite , Then it needs to be xargo-build.sh.
The tutorial code can be downloaded from here : example-helloworldhttps://github.com/solana-labs/example-helloworld#rust-limitations
solana-program-libraryhttps://github.com/solana-labs/solana-program-library cargo-build-bpf
https://github.com/solana-labs/solana/tree/master/sdk/cargo-build-bpf
版权声明:本文为[Blockchain Development Engineer]所创,转载请带上原文链接,感谢。 https://netfreeman.com/2022/134/202205140348123043.html