Try   HackMD

Get The Basic Idea About Solana Program

tags: solana

Index

  • Concepts
    • Accounts
    • Executable & Writable
    • Program & Client
  • Counter Example

Concepts

Accounts

Accounts are just buffers that store serialized binary data on chain.

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Executable & Writable

  • Programs are stored in executable accounts
  • Programs are stateless on Solana.
  • States are stored in non-executable accounts which can be writable or read-only
  • Think state accounts as rows in database. They can be modified and queried

Program & Client

You may think programs (smart contract) as AWS Lambda functions.

Just like client-server model that we are familiar in web2, we develop and deploy prgrams then use clients to interact with them.

Counter Example

offical repo

Program

pub fn process_instruction( program_id: &Pubkey, // Public key of the account the hello world program was loaded into accounts: &[AccountInfo], // The account to say hello to _instruction_data: &[u8], // Ignored, all helloworld instructions are hellos ) -> ProgramResult { msg!("Hello World Rust program entrypoint"); // Iterating accounts is safer than indexing let accounts_iter = &mut accounts.iter(); // Get the account to say hello to let account = next_account_info(accounts_iter)?; // The account must be owned by the program in order to modify its data if account.owner != program_id { msg!("Greeted account does not have the correct program id"); return Err(ProgramError::IncorrectProgramId); } // Increment and store the number of times the account has been greeted let mut greeting_account = GreetingAccount::try_from_slice(&account.data.borrow())?; greeting_account.counter += 1; greeting_account.serialize(&mut &mut account.data.borrow_mut()[..])?; msg!("Greeted {} time(s)!", greeting_account.counter); Ok(()) }

Client (partial)

... // Establish connection to the cluster const connection = new Connection(RPCURL, 'confirmed'); const version = await connection.getVersion(); console.log('Connection to cluster established:', RPCURL, version); // Get the payer to pay this transaction var secretKeyString = await fs.readFile(payer_keypair_path, {encoding: 'utf8'}); var secretKey = Uint8Array.from(JSON.parse(secretKeyString)); const payerKeypair = Keypair.fromSecretKey(secretKey); console.log("Payer: ", payerKeypair.publicKey.toBase58()); // Get the program's pubkey (ID) secretKeyString = await fs.readFile(program_keypair_path, {encoding: 'utf8'}); secretKey = Uint8Array.from(JSON.parse(secretKeyString)); const programKeypair = Keypair.fromSecretKey(secretKey); const programId = programKeypair.publicKey console.log("Program ID: ", programId.toBase58()); // Invoke our Hello Solana Program const instruction = new TransactionInstruction({ keys: [], programId, data: Buffer.alloc(0), }); await sendAndConfirmTransaction( connection, new Transaction().add(instruction), [payerKeypair], );

Resources