1

I am currently facing a big problem with Solana.

I will start with a very simple example for the explanation:

In fact I want to create a smart contract, in this smart contract there will be the name of users which will be stored in a unique way.

Solana being a stateless program, the data are stored in separate accounts.

So I'm looking for a way to retrieve the data in the Solana program (OnChain) and to be able to tell if the nickname has already been taken or not.

I already know how to do this on the client side with React / Solana Web3 Js but I'm looking for a way to do it in the Solana program.

For example, here is an equivalent I would like to do in a language like Solidity :

// SPDX-License-Identifier: RevX.9
pragma solidity ^0.8.2;
contract Example {
struct  owner_of_keywords
{
 address[] user_address; //It's a array
} 
 mapping(string=>owner_of_keywords) Keywords1;

 function verify(string memory _ressearch) view private returns(uint)
 {
   return Keywords1[_ressearch].user_address.length; //If length >= 1 , Pseudo already 
   used
 }

 function addItems(string memory pseudo_add) external payable
 {
   uint index = verify(pseudo_add); //return the length of array if >=1 Pseudo already 
   used
   require(index==0,"Pseudo already used"); // if index =0 pseudo are not used else 
   pseudo 
   is already used
   Keywords1[pseudo_add].user_address.push(msg.sender); //insert wallet addres of user 
  }
 }

Anyone can help me please ?

1 Answer 1

5

The solution is to use something called Program Derived Addresses.

What Are They?

Your program has its own unique address space to which it can allocate Program Derived Addresses. These are derived partly from your program address, and partly from any arbitrary seed data. This makes them easily derivable from just your Program ID and the seed data, making it possible to "check if the account for seed X exists."

You can use the nicknames for your seeds, or even better, a vector of seeds with the string literal "nickname", and the actual nickname itself, i.e. ["nickname", <the-nickname>].

So in this setup, every nickname is an account. No HashMap needed. In fact, you should think of your program's PDA address space as a kind of HashMap of its own, with the seeds like your key, and the account data the value.

How to Make Them?

Initializing PDAs in Anchor programs is very easy to do, and the instruction will fail if the account already exists, making your desired behavior plug-and-play.

On the PDA itself, you can store whatever data you want, and in this case, you'd want to at least store the owner address of the nickname, so that you can authorize operations for that account appropriately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.