Add dependencies
Add the following dependencies to your project:web3-solanalibrary provides the abstraction classes likeTransactionandAccountMetato simplify building Solana transactions.rpc-corelibrary provides aSolanaRpcClientclass with convenient RPC methods.kborshlibrary for Borsh serialization of instruction data.
Example: Counter Program
As an example, we’ll build a transaction using this devnet on-chain Counter Program that was created with Anchor. Specifically, let’s invoke theIncrement instruction.
Instruction Format
Taking a look at the source code, observe that theIncrement instruction format expects:
Program ID
- The Counter Program is deployed on devnet with the Program Id:
ADraQ2ENAbVoVZhvH5SPxWPsF2hH5YmFcgx61TafHuwu.
- The Counter account PDA as a non-signer.
"counter"is the only seed used to derive the PDA.
- An
amount: u64parameter. - An additional 8 bytes for the Anchor discriminator
1. Find the Counter account PDA
To derive the Counter PDA, we’ll use theProgramDerivedAddres interface in the web3-solana module which provides a find method.
Call ProgramDerivedAddres.find and pass "counter" as a seed and the Counter program ID:
2. Serialize the instruction data
The next step is to build and serialize the instruction data. Using thekotlinx serialization library, define the expected increment arguments as a @Serializable class.
AnchorInstructionSerializer to serialize the instruction arguments and lastly use the kBorsh library to Borsh encode the data.
INFOAnchor instruction data uses a unique Anchor discriminator to determine which instruction is called.The
AnchorInstructionSerializer will handle this discriminator during serialization, as long as you pass the correct instruction name (e.g increment) into the constructor.3. Construct the instruction
Putting all the inputs together, you can build the fullTransactionInstruction.
4. Create the transaction
Then build a transaction message and construct theTransaction packed with the increment instruction.
5. Sign the transaction
At this point, you have successfully created an unsigned Solana transaction for incrementing the counter account. Before submitting to the network, the transaction must be signed by the fee payer.Signing with Mobile Wallet Adapter
If you want users to sign the transaction using their mobile wallet app (e.g Phantom, Solflare) you can use Mobile Wallet Adapter to request signing. Read the Using Mobile Wallet Adapter guide to learn how to prompt users to sign these transactions and submit them to the Solana network.Signing with a keypair
If you have direct access to a keypair, you can serialize the Transaction message, sign the bytes, and construct the signed transaction.6. Sending the transaction
After the transaction is signed, it can be submitted to an RPC using theSolanaRpcClient class.
