Access and iterate over account metadata within a Solana(Anchor) Program?

1.2k views Asked by At

To access and iterate over Solana account metadata on the client one can simply use solana/web3.js. But how can I access the same data within the solana(Anchor) program itself. How can I get the number of tweet accounts created and access the pubKeys of the account authors. I want this to be done on-chain to prevent any users from manipulating the front-end code for their own benefit, such as minting/transferring utility tokens to themselves rather than other users of the dApp. Basically how can the web3 code below be implemented on-chain?

Below is the web3.js version of what I want to do within the program.

const tweetAccounts = await program.account.tweet.all();
let totalAccounts = tweetAccounts.length;
for (let tweetAccount of tweetAccounts) {
    let allKeys = [];
    let theKey = tweetAccount.author.publicKey;
    allKeys.push(theKey);
}

Solana Program Code I have to create tweet account.

 pub fn send_tweet(ctx: Context<SendTweet>, topic: String, content: String, review: i32) -> ProgramResult {
        let tweet: &mut Account<Tweet> = &mut ctx.accounts.tweet;
        let author: &Signer = &ctx.accounts.author;
        let clock: Clock = Clock::get().unwrap();

        if topic.chars().count() > 50 {
            return Err(ErrorCode::TopicTooLong.into())
        }

        if content.chars().count() > 280 {
            return Err(ErrorCode::ContentTooLong.into())
        }

        tweet.author = *author.key;
        tweet.timestamp = clock.unix_timestamp;
        tweet.topic = topic;
        tweet.content = content;
        tweet.review = review;

        Ok(())
    }

#[derive(Accounts)]
pub struct SendTweet<'info> {
    #[account(init, payer = author, space = Tweet::LEN)]
    pub tweet: Account<'info, Tweet>,
    #[account(mut)]
    pub author: Signer<'info>,
    pub system_program: Program<'info, System>,
}
1

There are 1 answers

2
Jon C On BEST ANSWER

It's impossible to dynamically load new accounts on-chain, meaning every account that you want to use must all be specified up front.

For your situation, this means that there is no immediate solution! The best way to get around this is to create a global account with all of the required counters, and update it as needed on every instruction.

I wish there were a more satisfying response, but this is the best I can come up with.