Shyft
Start BuildingSupportWebsite
  • Welcome
    • 👋Introducing Shyft
    • 🏗️Start Building
  • Solana Infrastructure
    • 🚁Shyft RPCs
  • Yellowstone gRPC Network
    • Decoding gRPC Latency
    • ⚡gRPC Docs
      • Introduction
      • Authentication
      • Subscribe Requests
      • FAQ
      • Getting Started
        • Initializing the Yellowstone Client
        • Making a gRPC connection
        • Adding a Reconnection Mechanism
        • 🔥Replaying Slots with Solana yellowstone gRPCs
        • Modifying your Subscribe Request
        • Closing a gRPC Connection
      • Subscribing to Transactions
        • All Transactions of an address
        • Subscribing to all transactions of a Liquidity Pool
        • Subscribing to all transactions of multiple addresses
        • Subscribing to all transactions of a Token
      • Subscribing to Accounts
        • Account Updates for a Program
        • Account Updates for an Address
        • Account updates using memcmp
      • Streaming Blocks & BlocksMeta
        • Streaming Block Updates
        • Subscribing to BlocksMeta
      • Modifying & Unsubscribing
  • Solana defi data
    • DeFI APIs
      • Get Pool By Address
      • Get Pools By Token Pair
      • Get All Pools for a Token
      • Get Liquidity Details of a Pool
  • Callbacks
    • ☎️What are Callbacks?
      • Transaction Callbacks
      • Account Callbacks
    • 📔Callback APIs
      • Response Structure
      • List Callbacks
      • Register callback
      • Remove callback
      • 🔥Pause a callback
      • 🔥Resume a callback
      • Update Callbacks
      • Add Addresses
      • Remove addresses
  • Solana Super Indexers
    • 🌩️GraphQL APIs
      • Getting Started
      • Building Queries
      • Paginating Response
      • Applying Filters
      • Ordering and Sorting Data
    • 📀Case Studies
      • Tensor
        • Get Active Listings of a Wallet
        • Get Active Bids of a Wallet
        • Get Active Listings of a Collection
        • Get all Bids of a Collection
        • Get all Pools of a Margin Account
        • Get all Pools by Owner
      • Raydium
        • Get Pool By Address
        • Get Pools By Token Address
        • Get Pools Created Between Time
        • Get Pool Burn Percentage
        • Get Liquidity Details of a Pool
        • Get Pool and OpenBook Market Info
        • Get Token Supply Percentage In Pool
      • Orca Whirlpool
        • Get Pool by Address
        • Get Pool by Token Address
        • Get Positions for a Pool
        • Get Positions for a Wallet
        • Get Liquidity Details of a Pool
      • Kamino
        • Get Borrow Details of a Wallet
        • Get Deposit Details of a Wallet
        • Get Reserve Details
      • Cross Marketplace Queries
        • Get active listings across marketplaces for a wallet
        • Get listings for a collection across marketplaces
        • Get floor price of a collection
      • Cross Defi Queries
        • Fetch Liquidity Pools for Token
      • Native Staking
        • Get Stakes for a Wallet
        • Get Stakes For Validator
      • Governance/Realms
        • Get DAO Token Owners
        • Get Proposals For Governing Mint
        • Get All Proposals For DAO
        • Get DAO Treasury Info
        • Get All Active Proposals For Wallet
      • Meteora
        • Get All LB Position Pairs
        • Get Position of a User Wallet
        • Get Pool by Token Addresses
        • Get All Deposits for a User
        • Get All Withdraws for a User
        • Get All Fees Claimed by a User
        • Get All User Positions and Deposits for a Pool
        • Get All User Positions and Withdrawals for a Pool
      • Fluxbeam
        • Get Pool by Address
        • Get Pool by Token Addresses
      • Drift
        • Get User account for Delegate
        • Get User accounts based on authority
        • Get User details based on Referrer
        • Get Borrow/Deposit Amount for an User
        • Get PrepPositions for an User Account
        • Getting OrderId and userOrderId
        • Get OpenOrders for a User Account
      • 🔥Pumpswap
        • 🔥Get Pool by Address
        • 🔥Get Pool by Creator Address
        • 🔥Get Pools by Token Addresses
      • Raydium Launchpad
        • Get Bonding Curve Details by Pool Address
        • Get All Pools for a Creator
        • Get Pools by Token Addresses
        • Get Migration details of a Pool
  • Solana APIs
    • API Reference
    • Transactions
      • Parsed Transaction Structure
      • Transaction APIs
        • History
        • Parse Signature
        • Parse Multiple Signatures
        • Send
        • Send Multiple
    • NFT
      • 🔥Create Gasless
      • Create
      • Read All
      • Burn
      • 🔥Burn Multiple NFTs V2
      • Update
      • 🔥Create NFT from Metadata
      • 🔥Read Wallet Nfts
      • 🔥Read Selected NFTs
      • 🔥Get NFT Owners
      • 🔥Update NFT Metadata Uri
      • 🔥Update V2
      • Search
      • Transfer
      • Transfer Multiple NFTs
      • Mint
      • Read
    • Wallet
      • Get Balance
      • Get Token Balance
      • Get All Tokens Balance
      • Get Portfolio
      • Resolve Address
      • Get All Domains
      • Get Stake Accounts
    • Fungible Tokens
      • Create
      • Mint
      • Burn
      • 🔥Update
      • Get Token Info
      • Transfer
      • Airdrop
Powered by GitBook
On this page
  • Generating Transaction Instruction
  • Signing Transaction
  • Conclusion

Was this helpful?

  1. Tutorials

How to sign transactions on Solana

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

Last updated 1 year ago

Was this helpful?

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:

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.

https://shyft-insider.vercel.app/