1

I am currently writing a frontend for my custom on-chain program. The frontend is supposed to take input from a form and then submit the data to the program. Currently I'm following this tutorial (https://docs.solana.com/developing/clients/javascript-api#interacting-with-custom-programs) to write the frontend code.

The issue I'm running into is in composing my struct for the layout of the transaction. My struct is created thusly:

let starshipStruct = {
    index: 1,
    layout: struct([
      u32('instruction'),
      cstr('container'),
      u16('hours'),
    ]),
  };

When I attempt to allocate a Buffer for this struct, I receive an error that the size cannot be -1. I've determined the issue is with the cstr function which is returning a value of -1. How would one set the size for this function? I'm using the @solana/buffer-layout library for these functions. Thanks in advance!

1 Answer 1

1

The size of a string in C is roughly "keep going until you see a 0 byte", which doesn't work when you need to know the exact size. This is why you're seeing an error.

You must pre-allocate the space required, wither either the size of an existing string, or a fixed number of bytes. If you do 50 bytes for your string, you can do something like:

let starshipStruct = {
    index: 1,
    layout: struct([
      u32('instruction'),
      seq(u8(), 50),
      u16('hours'),
    ]),
  };

and then interpret those 50 bytes as a utf-8 string in your program.

1
  • This worked! I had to be sure to import seq and u8 into my file so the import line looks like this for me: import { struct, seq, u8, u16, u32 } from '@solana/buffer-layout'; Commented Mar 28, 2023 at 0:14

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.