Writing Data to the Solana Blockchain
Solana Javascript SDK
@solana/web3.js
is the JavaScript API built on top of the Solana JSON RPC API. We will use it to interact with the Solana Network
SDK Basics
Keypairs
Keypairs are a system of public and private keys used to access the Solana blockchain network. A keypair consists of a public key (which is publicly available and used to receive tokens) and a private key (which is kept securely and used to sign transactions).
Making a new KeyPair
const keypair = Keypair.generate() // Helper function from **@solana/web3.js**
const publicKey = keypair.publickey // Index public key
const privateKey = keypair.secretkey // Index private key
Transactions
Transactions are instructions that call solana programs, usually to modify on-chain data.
They have 3 key elements:
uid of the program to call
list of accounts to read/write to
data in the form of a byte array
/* a simple transaction might look like this.
we are using helper functions from **@solana/web3.js** */
const transaction = new Transaction()
const sendInstruction = SystemProgram.transfer({
fromPubkey: sender, // sender address
toPubkey: recipient, // reciever address
lamports: LAMPORTS_PER_SOL * amount // amount of SOL to be sent
})
transaction.add(sendSolInstruction)
Writing Data
Here is an example of a complete program that writes data to the network.
async function callProgram(
connection: web3.Connection,
payer: web3.Keypair,
programId: web3.PublicKey,
programDataAccount: web3.PublicKey
) {
/* This is a new transaction instruction - the programId
is the key of the program you are calling and keys contains
accounts that will be written to */
const instruction = new web3.TransactionInstruction({
keys: [
{
pubkey: programDataAccount,
isSigner: false,
isWritable: true
},
],
programId
})
/* "sig" waits for the confirmation of the transaction being completed.
The return of this is a signature created from the message and secret key,
used to log the transaction. */
const sig = await web3.sendAndConfirmTransaction(
connection,
new web3.Transaction().add(instruction),
[payer]
)
console.log(sig)
}
Assignment
Generate a new keypair using the Keypair.generate() method from the @solana/web3.js library.
Create a program that creates a new transaction that transfers a specified amount of SOL from the public key to another public key, while also storing a message to be sent with the transaction.
The message should be encrypted using a basic encryption algorithm of the your choice (e.g. Caesar cipher, Vigenère cipher, etc.).
Confirm that the transaction has been completed, retrieve the encrypted message from the data account, and decrypt it.
Note: You should use the information provided in the course, including the code examples, to complete the assignment. The program should be written in JavaScript and use the @solana/web3.js
library.
Once you’re done, make a PR with your react app to the homework repository on Github.
Last updated