Marketplace has launched, further enabling blockchain developers! Learn more

How to Use the Solana Memo Program

September 23, 2022

Overview

Tools like Solana Explorer are handy for querying transactions, but sometimes your use case may benefit from including additional information about the transaction. Say, for example, you want to include a note about the transaction or an associated invoice ID.

Solana's Memo Program makes doing this easy. If you have used getSignaturesForAddress, you may have noticed the resulting objects contain a memo key that is often null. Let's change that!

What You Will Do

In this guide, you will learn how to add a note (or notes) to your transaction using the Solana Memo program. You will create a simple app using Typescript that will send a transaction with a memo to the Solana network and fetch it from the chain.

What You Will Need

  • Nodejs (version 16.15 or higher) installed
  • Typescript experience and ts-node installed

Set Up Your Project

Create a new project directory in your terminal with:

set up your project

Copy
mkdir solana-memo
cd solana-memo

Create a file for your app, app.ts:

set up your project

Copy
echo > app.ts

Initialize your project with the "yes" flag to use default values for your new package:

set up your project

Copy
yarn init --yes
#or
npm init --yes

Create a tsconfig.json with .json importing enabled:

set up your project

Copy
tsc -init --resolveJsonModule true

Install Solana Web3 Dependency

We will need to add the Solana Web3 library for this exercise. In your terminal type:

set up your project

Copy
yarn add @solana/web3.js
#or
npm install @solana/web3.js

Create a Wallet and Airdrop SOL

You'll need to create a Solana File System Wallet (keypair written to a guideSecret.json file) and airdrop some SOL to it. You can do this using Solana CLI or use this script we have created for you.

Make sure you save your wallet to your project directory as guideSecret.json.

Let's get started.

Set Up Your App

Import Necessary Dependencies

Open app.ts, and paste the following imports on line 1:

set up your app

Copy
import { Connection, Keypair, PublicKey, sendAndConfirmTransaction, SystemProgram, Transaction, TransactionInstruction } from "@solana/web3.js";
import secret from './guideSecret.json';

In addition to the Wallet we created in the previous step, we are also importing a few essential methods and classes from the Solana Web3 library.

Set Up Your QuickNode Endpoint

To build on Solana, you'll need an API endpoint to connect with the network. You're welcome to use public nodes or deploy and manage your own infrastructure; however, if you'd like 8x faster response times, you can leave the heavy lifting to us. See why over 50% of projects on Solana choose QuickNode and sign up for a free account here. We're going to use a Solana Devnet node.

Copy the HTTP Provider link:
New Node


Inside app.ts under your import statements, declare your RPC and establish your Connection to Solana:

set up your app

Copy
const QUICKNODE_RPC = 'https://example.solana-devnet.quiknode.pro/0123456/';
const SOLANA_CONNECTION = new Connection(QUICKNODE_RPC);

Create two new async functions, logMemo and fetchMemo, that we will use to send a memo transaction to Solana and fetch a memo, respectively:

set up your app

Copy
async function logMemo (message: string) {

}

async function fetchMemo() {

}

Create Log Memo Function

To send a memo transaction, we will need to do a few things:

  1. Declare a Keypair from our secret that will be used to sign our transaction (and pay the Solana network fees)
  2. Create a Solana Transaction
  3. Add a memo instruction to the Transaction
  4. Send and Confirm the Transaction
  5. Log Transaction URL
Add the following code to your logMemo function:

create log memo function

Copy
async function logMemo (message: string) {
    // 1. Declare Keypair to sign transaction 
    const fromKeypair = Keypair.fromSecretKey(new Uint8Array(secret));
    
    // 2. Create Solana Transaction
    let tx = new Transaction();

    // 3. Add Memo Instruction
    await tx.add(
        new TransactionInstruction({
          keys: [{ pubkey: fromKeypair.publicKey, isSigner: true, isWritable: true }],
          data: Buffer.from(message, "utf-8"),
          programId: new PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),
        })
      )
    // 4. Send Transaction
    let result = await sendAndConfirmTransaction(SOLANA_CONNECTION, tx, [fromKeypair]);
    // 5. Log Tx URL
    console.log("complete: ", `https://explorer.solana.com/tx/${result}?cluster=devnet`);
    return result;
}

Believe it or not, that's all you need to write a memo to Solana. Let's dive deeper into Step 3 before we test it out. First, we use the .add method on our transaction to add a new TransactionInstruction. Transaction instructions require three components: keys, data, and programId. Because our transaction instruction will only interact with the payer wallet, that's the only key we will need for this instruction--that key will be a signer and will need to be writable to allow for the transfer of SOL for the payment. For the Memo Program, we need to generate a Buffer from our message (a string) encoded as utf-8. Finally, the Program ID of the Memo Program is MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr. Make sure to call it as a PublicKey.

Go ahead and call logMemo() with a String as the message argument. Add this code to the bottom of app.ts:

create log memo function

Copy
logMemo("QuickNode Memo Guide Test");

And run it. In your terminal, type:

create log memo function

Copy
ts-node app.ts

You should get a link to your transaction on Solana Explorer. Open it. You should see your memo down at the bottom of the page inside the Memo Instruction and in the Program logs:

Memo received. Nice job!

Create Fetch Memo Function

Now, how can we fetch that memo ourselves? Just a single call to Solana! Inside of your fetchMemo function, add:

create fetch memo function

Copy
async function fetchMemo() {
    const wallet = Keypair.fromSecretKey(new Uint8Array(secret)).publicKey;
    let signatureDetail = await SOLANA_CONNECTION.getSignaturesForAddress(wallet);
    console.log('Fetched Memo: ', signatureDetail[0].memo);
}

What we're doing here is grabbing the PublicKey from the same wallet that initiated our transaction, fetching the signature details for that address using getSignaturesForAddress, and logging the detail of the first signature in the resulting array (the most recent transaction).

Now you can replace your logMemo() call with fetchMemo():

create fetch memo function

Copy
// logMemo("QuickNode Test Memo Guide Test");
fetchMemo()

Finally, rerun your code. In your terminal, type:

create fetch memo function

Copy
ts-node app.ts

You should see the memo from your last transaction in your terminal, preceded by an array with a value in it (the length of your memo):
Fetched Memo Returned in Terminal


Great job!

Leave Us a Message!

You may have noticed in creating the logMemo function that the memo we made was just one instruction in our transaction. You can add other transaction instructions to your script to log a memo to your typical transactions (e.g., transferring SOL, interacting with a custom Program, etc.).

Try modifying the logMemo function to add a SOL transfer to your transaction using SystemProgram.transfer. Try sending us some Devnet SOL to HHWnihfANXc78ESGG7RbVeC1xyKtvr6FEoKY3aHqDLfS and leave us a message in your memo!

Wrap Up

Transaction memos can be a handy tool for adding additional context or information to your transaction logs. You now have the tools you need to add your own memos! Want to try adding memos to practice some more? Try performing our Bulk Transaction Guide with a unique memo message for each transaction.

Got questions or having trouble? Reach out on Discord or Twitter!

We <3 Feedback!

If you have any feedback or questions on this guide, let us know. We’d love to hear from you!

Related articles 26

How to Transfer SPL Tokens on Solana
Originally Published On: Sep 23, 2022
Updated On: Sep 23, 2022

Sending Solana Program Library... Before getting started, it is... Create a new project directory... Import Necessary... If you have created a fungible... Create a new async function,... Finally, at the end of your... Awesome! You now know how to...

Continue reading
How to Send Bulk Transactions on Solana
Originally Published On: Aug 31, 2022
Updated On: Sep 23, 2022

Are you running a batch process... Create a new project directory... Let's start by creating a list... Import Necessary... If you're new to Solana or web3,... Alright! You have an array of... Let's call our functions and... So, our simple example above... Congrats! You just sent SOL to...

Continue reading
How to Send a Transaction On Solana Using JavaScript
Originally Published On: Aug 15, 2021
Updated On: Sep 23, 2022

Hello reader! Today is an... You need to set up your project... While this goal could be... To connect to the devnet that... With a connection to the... On to the fun bit! We can now... Congratulations! If you made it...

Continue reading
How to Query Solana Naming Service Domains (.sol)
Originally Published On: Aug 19, 2022
Updated On: Sep 23, 2022

In a recent guide, we covered To run our on-chain queries,... To build on Solana, you'll need... Let's start by creating a new... Create a new function below... Let's declare our search queries... You now have the tools to run...

Continue reading
How to Deploy an NFT Collection on Solana Using Sugar (Candy Machine)
Originally Published On: Jul 28, 2022
Updated On: Sep 23, 2022

Are you ready to launch your NFT... Create a new project directory... Mac... One of the cool new features of... Next, we will want to fund our... If you have used Candy Machine... Create a new file,... Because we've set our RPC and... For the easiest possible set up,... Congrats! You created a Candy...

Continue reading
How to Mint an NFT on Solana
Originally Published On: Aug 27, 2021
Updated On: Sep 23, 2022

Updated at: April 10,... Solana's goal is singular in... Open Terminal and navigate to a... Open the... The first task we'll need to... We'll now need to create a new... We have an account to send the... Now it's time to mint an NFT and... If you made it this far, you...

Continue reading
How to Mint an NFT on Solana Using Candy Machine
Originally Published On: Sep 20, 2021
Updated On: Sep 23, 2022

NOTE:... Hello reader! We have had a lot... Candy Machine is a tool that... There are two different... With all of the code pulled down... With everything in place there... Congratulations! You just minted...

Continue reading
Como crear un NFT en SOLANA
Originally Published On: Dec 27, 2021
Updated On: Sep 23, 2022

¡Hola querido lector!... Solana tiene un objetivo muy... Nosotros usaremos Solana Devnet... Esta es la parte divertida! La... Si has llegado hasta aquí, has...

Continue reading
How to Create Websocket Subscriptions to Solana Blockchain using Typescript
Originally Published On: Jul 15, 2022
Updated On: Sep 23, 2022

Creating event listeners is an... Create a new project directory... To build on Solana, you'll need... On line 5, create a new... To track a wallet on Solana,... This code is ready to run as is,... Let's go ahead and test it... Solana has created a built-in... Solana has several other,... Nice work! Now you should have a...

Continue reading
An Introduction to the Solana Account Model
Originally Published On: Apr 18, 2022
Updated On: Sep 23, 2022

The Accounts are any place where... There are two types of accounts... Unfortunately, storing all this... To create an account on Solana,... Since the program code and data... Creating and interacting with...

Continue reading
How to Get Transaction Logs on Solana
Originally Published On: Jun 24, 2022
Updated On: Sep 23, 2022

Ever need to pull all the... Create a new project directory... To build on Solana, you'll need... The... If everything is set up... So we've got some useful basic... Kudos! You've now got an inside...

Continue reading
How to Deploy an NFT on Solana Using Candy Machine V2
Originally Published On: Jan 15, 2022
Updated On: Sep 23, 2022

Candy Machine 2 has been... Hello readers, in this guide we... Now, let us begin the... If you have used CMv1 or... With all of our assets loaded... For the easiest possible set up,... Congratulations on successfully...

Continue reading
Como crear un NFT en Solana usando Candy Machine
Originally Published On: Dec 27, 2021
Updated On: Sep 23, 2022

¡Hola querido lector! Hemos... Candy Machine es un programa que... Hay dos repositorios diferentes... Una vez que el código se ha... Con todo lo que hemos realizado... ¡Felicidades! Acabas de hacer...

Continue reading
How to Build a Wallet Generator for Solana in React
Originally Published On: Oct 27, 2021
Updated On: Sep 23, 2022

In this practical guide you will... We have prepared a small... Connection to Solana Network is... To create an account we will... To get the balance of an account... As we said before, in... Congratulations on making it to...

Continue reading