3

I am trying to write a vector of objects into a solana account. The problem is, the pre-allocated size of the account might be too small for my vector. I know i can re-size the account with realloc, but I still don't know the serialized size of my vector of objects, which I need to call realloc.

I could implement my own serialization logic, but I'd prefer not to do that.

Are there any serialization libraries out there that tell you the size of the serialized object before you serialize it?

5
  • I took a quick look at borsh and bincode and I don't think they satisfy this requirement.
    – Ripleys 0x
    Commented Nov 20, 2022 at 16:47
  • Borsh is fine and I've used it for variable size objects (like vec). However; if you are trying to manage a large vector or it's growth can potentially be large you may want to consider using PDA for whatever info you would store in the vec. Any serialization is going to consume more CU and that may be prohibitive.
    – Frank C.
    Commented Nov 20, 2022 at 22:10
  • Can you add more context to your question? What are you storing in the vector, how often will it grow? What is the general use case?
    – Frank C.
    Commented Nov 20, 2022 at 22:12
  • I have a struct called Obligation, which manages a user's deposits and borrows. The amount of deposits and borrows is dynamic. Currently, we have the size hardcoded so the amount of deposits and borrows can't exceed 10. I would like to remove this constraint, especially since re-alloc lets us do dynamic resizing.
    – Ripleys 0x
    Commented Nov 21, 2022 at 14:47

1 Answer 1

4

You wouldn't want to serialize an account within the runtime. For any meaningfully sized account, this will use up more compute units than you have. I have generally gotten away with just looking up the byte length of the account after all state changes have been made and then calling realloc with that value.

let data_len = my_account.try_to_vec()?.len();
my_account.to_account_info().realloc(data_len, false)?;
3
  • ok interesting...im surprised that works. i kinda assumed you wouldn't even be able to make length-increasing state changes without calling realloc first. Time to dig into source code lol
    – Ripleys 0x
    Commented Nov 26, 2022 at 14:15
  • Will mark as correct when i verify this :)
    – Ripleys 0x
    Commented Nov 26, 2022 at 14:15
  • This seems to be how the Account is stored on chain. Since it is a vector, I think your answer works! Thanks
    – Ripleys 0x
    Commented Nov 26, 2022 at 14:42

Your Answer

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

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