1

I want to write the following structure to the account:

#[derive(BorshDeserialize, BorshSerialize, Clone, Debug, PartialEq)]
pub struct Bid {
    /// XJUST lamports
    pub xjust: u64,
    /// selected side
    pub side: u8,
    /// user key
    pub pubkey: String,
}

#[derive(BorshDeserialize, BorshSerialize, Debug, Default)]
pub struct BidData {
    // list bids
    pub bids: Vec<Bid>,
}

allocate memory:

class Bid {
  xjust = new BN('10000000');
  side = 0;
  pubkey = "";
  constructor(fields: { xjust: BN, side: number, pubkey: string } | undefined = undefined) {
    if (fields) {
      this.xjust = fields.xjust;
    }
  }
}

class BettingAccount extends Bid {
  static decode(bytes: Buffer) {
    const dataLengthBuffer = Buffer.alloc(4);
    bytes.copy(dataLengthBuffer, 0, 0, 4);

    const dataLength = DataLength.decode(dataLengthBuffer);

    const accountDataBuffer = Buffer.alloc(Object.keys(dataLength).length);
    bytes.copy(accountDataBuffer, 0, 4, Object.keys(dataLength).length);
    return deserialize(BettingSchema, BettingAccount, accountDataBuffer);
  }
}

const BettingSchema = new Map([
  [Bid, {kind: 'struct', fields: [
    ['xjust', 'u64'],
    ['side', 'u8'],
    ['pubkey', 'string'],
  ]}],
  [BettingAccount, {kind: 'struct', fields: [
    ['bids', [Bid]]
  ]}]
]);
///.......
const transaction = new Transaction().add(
    SystemProgram.createAccountWithSeed({
      fromPubkey: newBet.publicKey,
      basePubkey: newBet.publicKey,
      seed: 'GREETING_SEED',
      newAccountPubkey: greetedPubkey,
      lamports,
      space: 10200,
      programId: PROGRAM_ID.publicKey,
    }),
  );
  await sendAndConfirmTransaction(connection, transaction, [newBet]);
  console.log("newbet", greetedPubkey.toString());

But when popyki count (even empty) account. i get failed: Failed to serialize or deserialize account data: Unknown'

read account like this:

let mut bet_data = BidData::try_from_slice(&bet_account.data.borrow())?;

if i try

let mut bet_account = BidData::try_from_slice(&bet.data.borrow()[..]).unwrap();

then I get an error: panicked at \'called `Result::unwrap()` on an `Err` value: Custom { kind: InvalidData, error: "Not all bytes read" }\', src/lib.rs:94:83'

1 Answer 1

2

The problem is that, as a variable length data block due to the Vec<Bid> which is not completely populating the account size you have pre-allocated.

What borsh does is look at the size of the account you've allocated and does a check to validate that the data array is completely consumed with data.

On the client side, borsh has a deserializeUnchecked to use instead.

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.