How to sign transactions on Solana

In this post we are going to generate a simple transaction and then sign it on Solana Blockchain.

There are 2 ways in which you can sign a Solana transaction:

  • Using a Solana wallet (phantom, sollet, etc) and approving manually in the browser.

  • Using a private key, which is useful if you want to automate the signing process say for example in the backend.

We have deployed a small project to test out transaction signing while working with Shyft APIs. Try it out here: https://shyft-insider.vercel.app/

In this tutorial, we will cover how to sign transactions automatically without having to approve every time through a wallet.

We will create a simple transaction instruction to transfer some SOL from account A to B. Then sign it using a code snippet.

A = GE4kh5FsCDWeJfqLsKx7zC9ijkqKpCuYQxh8FYBiTJe
B = AaYFExyZuMHbJHzjimKyQBAH1yfA9sKTxSzBc6Nr5X4s

Generating Transaction Instruction

Below is the code to generate simple transfer instructions to transfer 1 SOL, on devnet:

import {
  clusterApiUrl,
  Keypair,
  PublicKey,
  SystemProgram,
  Transaction,
} from '@solana/web3.js';

async createTransferInstruction() : Promise<any> {
    const fromPubKey = new PublicKey('GE4kh5FsCDWeJfqLsKx7zC9ijkqKpCuYQxh8FYBiTJe');
    const tx = new Transaction().add(SystemProgram.transfer({
    fromPubkey: fromPubKey,
    /** Account that will receive transferred lamports */
    toPubkey: new PublicKey('AaYFExyZuMHbJHzjimKyQBAH1yfA9sKTxSzBc6Nr5X4s'),
    /** Amount of lamports to transfer */
    lamports: 100000000,
  }));
  const connection = new Connection(clusterApiUrl("devnet"), 'confirmed');
  const blockHash = (await connection.getLatestBlockhash('finalized')).blockhash;
  tx.feePayer = fromPubKey;
  tx.recentBlockhash = blockHash;
  const serializedTransaction = tx.serialize({ requireAllSignatures: false, verifySignatures: true });
  const transactionBase64 = serializedTransaction.toString('base64');
  return { 
    encoded_transaction: transactionBase64 
  };
}

The above code snippet returns base64 encoded version of the transaction.

Signing Transaction

Now, let's come to the second part where we take the response from the above function, sign, and send this transaction into the blockchain. Along with the encodedTransaction string from the previous function, this function also needs the private_key of the sender to successfully sign the transaction. The sender's private key is needed because while creating the transaction above we assigned the fromPubKey as the tx.feePayer.

import { clusterApiUrl, Keypair, Transaction, VersionedTransaction } from '@solana/web3.js';

async signTransaction(encodedTransaction: string, fromPrivateKey: string) : Promise<any> {
  try {    
    const connection = new Connection(clusterApiUrl("devnet"), 'confirmed');
    const feePayer = Keypair.fromSecretKey(decode(fromPrivateKey));
    const recoveredTransaction = getRawTransaction(encodedTransaction);
    if (recoveredTransaction instanceof VersionedTransaction) {
      recoveredTransaction.sign([feePayer]);
    } else {
      recoveredTransaction.partialSign(feePayer);
    }
    const txnSignature = await connection.sendRawTransaction(
      recoveredTransaction.serialize(),
    );
    return txnSignature;
  } catch (error) {
    console.log(error);    
  }
}


function getRawTransaction(
  encodedTransaction: string
): Transaction | VersionedTransaction {
  let recoveredTransaction: Transaction | VersionedTransaction;
  try {
    recoveredTransaction = Transaction.from(
      Buffer.from(encodedTransaction, 'base64')
    );
  } catch (error) {
    recoveredTransaction = VersionedTransaction.deserialize(
      Buffer.from(encodedTransaction, 'base64')
    );
  }
  return recoveredTransaction;
}

The above function signs and sends the transaction to Solana's devnet and return the transaction signature.

Conclusion

You can use the code for above 2 functions to create a backend API to transfer SOL. This can be achived by exposing the first function via API call, which returns the encodedTransaction. You can put the code in second function in your client side or FE. So that, your users never have to pass their privates keys over the network.

Hope this is useful. Happy hacking.

Last updated