Marketplace has launched, further enabling blockchain developers! Learn more

How to Query Solana Naming Service Domains (.sol)

September 23, 2022

Overview

In a recent guide, we covered How to Create Solana Naming Service Domains. Solana Naming Service ("SNS") is a handy Solana Solana Program that allows users to create a readable domain name that can be used in place of a Public Key.

What You Will Do

In this guide, you will learn how to query Solana domain names using Typescript and Bonfida's SPL Name Service SDK. This will enable you to:
  • look up a user's wallet by their domain name and
  • look up a user's domain name(s) by their wallet

What You Will Need

Set Up Your Environment

To run our on-chain queries, we're going to use Nodejs. Open your code editor of choice and create a new project directory in your terminal with:

set up your environment

Copy
mkdir sns-example
cd sns-example

Create name-search.ts. We will use this as our primary app for running our scripts.

set up your environment

Copy
echo > name-search.ts

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

set up your environment

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

Install Solana Web3 dependencies:

set up your environment

Copy
yarn add @solana/web3.js @bonfida/spl-name-service
#or
npm install @solana/web3.js @bonfida/spl-name-service

Your environment should look something like this:
SNS Query Node Enviroment

Let's set up your app with all the dependencies you'll need. Open name-search.ts and on lines 1-2, import the following dependencies:

set up your environment

Copy
import { Connection, PublicKey } from "@solana/web3.js";
import { getDomainKey, NameRegistryState, getAllDomains, performReverseLookup } from "@bonfida/spl-name-service";

The @solana/web3.js dependencies will allow us to create a connection to the Solana network and get the Public Key of a wallet address.

The @bonfida/spl-name-service imports will help us query .sol domains (we will explain these in the subsequent section).

Alright, you're ready to go.

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. You'll need to use a mainnet endpoint to query users' Solana domain names. Copy the HTTP Provider link:

Connect to Solana Endpoint


line 4 of name-search.ts, add the following code replacing QUICKNODE_RPC with your HTTP Provider Link:

set up your quicknode endpoint

Copy
const QUICKNODE_RPC = 'https://example.solana-mainnet.quiknode.pro/000000/';//replace with your HTTP Provider from https://www.quicknode.com/endpoints
const SOLANA_CONNECTION = new Connection(QUICKNODE_RPC);

Lookup .SOL Domain Owner

Let's start by creating a new async function, getPublicKeyFromSolDomain, that we will use to find the wallet owner of a given .sol domain. On line 7 of name-search.ts, add:

lookup sol domain owner

Copy
async function getPublicKeyFromSolDomain(domain: string):Promise<string>{
    const { pubkey } = await getDomainKey(domain);
    const owner = (await NameRegistryState.retrieve(SOLANA_CONNECTION, pubkey)).registry.owner.toBase58();
    console.log(`The owner of SNS Domain: ${domain} is: `,owner);
    return owner;
}

Our function accepts a string as a parameter, domain, which will be the domain name we want to look up (with or without the ".sol" extension). Finding the owner of the domain is a two-part process:

  1. Identify the public key associated with the domain (this is kind of like the mint address of an NFT). We do this above using the getDomainKey function and passing our domain parameter. We're looking specifically for the pubkey key from the returned object.
  2. Retrieve the owner's address from the name registry. We do this by invoking the retrieve method on the NameRegistryState class. The Name Registry stores information about the domain name on chain. The retrieve method will return an object that includes the registry, which holds the owner's public key (fetched by calling .registry.owner.toBase58()).

After fetching the owner's address, we log and return the results.

Reverse Lookup: Find All Domains Owned by a Wallet

Create a new function below getPublicKeyFromSolDomain (line 14 for us) that accepts a wallet address string and returns an array of strings (to account for users who hold multiple Solana Domains).

reverse lookup find all domains owned by a wallet

Copy
async function getSolDomainsFromPublicKey(wallet: string):Promise<string[]>{
    const ownerWallet = new PublicKey(wallet);
    const allDomainKeys = await getAllDomains(SOLANA_CONNECTION, ownerWallet);
    const allDomainNames = await Promise.all(allDomainKeys.map(key=>{return performReverseLookup(SOLANA_CONNECTION,key)}));
    console.log(`${wallet} owns the following SNS domains:`)
    allDomainNames.forEach((domain,i) => console.log(` ${i+1}.`,domain));
    return allDomainNames;
}

First, we get the PublicKey of the wallet we passed as our parameter, and then we use Bonfida's getAllDomains function to fetch the Public Key of all domains owned by that wallet and store the values in allDomainKeys. Next, we use Promise.all to run performReverseLookup for each key stored in allDomainKeys. The performReverseLookup function will resolve the .sol domain for the associated public key we pass into it. Because we used Promise.all, our formula will return an array of each domain name owned by the wallet.

After fetching the wallet's domains, we loop through the array and log each domain name.

Almost done. Nice work!

Run Your Code

Let's declare our search queries and call our functions. On line 23 of name-search.ts, paste:

run your code

Copy
//Examples for our search. You can replace these with your own wallet or Solana Naming Service queries. 
const DOMAIN_TO_SEARCH = 'bonfida';
const WALLET_TO_SEARCH = 'E645TckHQnDcavVv92Etc6xSWQaq8zzPtPRGBheviRAk';  

getPublicKeyFromSolDomain(DOMAIN_TO_SEARCH);
getSolDomainsFromPublicKey(WALLET_TO_SEARCH);

We have included a couple of sample queries in the DOMAIN_TO_SEARCH and WALLET_TO_SEARCH variables, but feel free to replace them with any wallet or domain that you would rather search.

Finally, we call both functions we created and pass our search variables as parameters. We have included our entire code sample on Github here.

Now, let's run it! Head back to the terminal and type:

run your code

Copy
ts-node name-search.ts

Do you see something like this?

SNS Query Results


Nice work!

Apply Your Skills

You now have the tools to run on-chain queries to find domain owners or domains held by a wallet. You can apply these same concepts to your own Solana dApp to improve your users' experience. Haven't built a dApp? Check out our Guide: How to Connect Users to Your dApp with the Solana Wallet Adapter and Scaffold.

If you don't already have a .sol domain and want to get one, check out our Guide: How to Create Solana Naming Service Domains.

Want some help with this guide? Find us on Discord or reach out to us via 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 Use the Solana Memo Program
Originally Published On: Sep 16, 2022
Updated On: Sep 23, 2022

Tools like Create a new project directory... Import Necessary... To send a memo transaction, we... Now, how can we fetch that memo... You may have noticed in creating... Transaction memos can be a handy...

Continue reading
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 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