3

I'm trying to get the account data using Rust and the solana_sdk. I have the following code where account.data is a Vec.

    let pubkey = Pubkey::from_str("4qRdUCHMGAfBEE3MNTiZZXpx3DawAWpGwDpqE2EV2QQ2").unwrap();

    let account = client.get_account(&pubkey).unwrap();
    println!("{:?}", account.data);

When trying to decode the byte array:

    let data = String::from_utf8(account.data).unwrap();

I get an error:

error: Utf8Error { valid_up_to: 1, error_len: Some(1) } }

How can I decode account data using Rust?

6
  • The cookbook doc does not help here? solanacookbook.com/guides/get-program-accounts.html#facts
    – chalda
    Commented Jun 1 at 18:02
  • Not that I can find? Please be more specific if you have any pointers. In this specific case I'm trying to decode/deserialize a metadata account, but whatever what I try I'm not able to decode the "data" property. Commented Jun 1 at 20:13
  • Can you please elaborate a bit on what you mean? If you talk about Solana account metadata then it's just the predefined set of things (lamports, executable, pubkey) solana.com/docs/core/accounts that brings data which is a set of bytes where every program on Solana decides on its own what how to encode/decode. What is the Metadata account more specifically? Do you have your code somewhere?
    – chalda
    Commented Jun 3 at 8:05
  • @chalda I updated the code now with a pubkey of a metadata account. But the problem is just in general for all metadata accounts. How can I read/decode the "data" property? account.data to be specific. Commented Jun 4 at 21:16
  • 1
    Ok. The data of the account is just a buffer of bytes. There is no meaning in them. The schema is defined by a program that loads them on-chain. Every program works with a different schema and you need to know what program you want to work with (see github.com/Unboxed-Software/solana-course/blob/main/content/…). There are standards to define schema (the mostly used Anchor IDL) that maps the order and size of bytes slices in the buffer to "a meaning". Search for deserialised solana (Anchor) data here in other topics.
    – chalda
    Commented Jun 5 at 5:54

1 Answer 1

2

mpl_token_metadata::accounts::Metadata has a function from_bytes which serializes the bytes into a Metadata struct:

let meta: Metadata = Metadata::from_bytes(&account.data).unwrap();

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