1

I'm doing unit test for my non anchor project and I'm trying to send transaction with data to contract. Here is the code:

#[derive(BorshDeserialize, BorshSerialize)]
    struct InitState<'a> {
        variant: &'a u8,
    }
    let param_init_state = InitState {
        variant: &4,
    };
let mut transaction = Transaction::new_with_payer(
        &[Instruction::new_with_borsh(
            program_id,
            &param_init_state,
            vec![
                AccountMeta::new(payer.pubkey(), true),
                AccountMeta::new(*state_account.key, false),
                AccountMeta::new(system_program::ID, false),
            ],
        )],
        Some(&payer.pubkey()),
    );

    transaction.sign(&[&payer], recent_blockhash);

    match banks_client.process_transaction(transaction).await {
        Ok(()) => (),
        Err(e) => panic!("{}", e),
    }

In solana tutorial, they use try_from_slice_unchecked(input)?; to read instruction data but it does not work for me. The compiler return Custom { kind: InvalidInput, error: "Unexpected length of input" } error if I use another way:

#[derive(BorshDeserialize, Debug)]
struct GachaMarketplacePayload {
    nft_contract: Pubkey, // program id,
    token_id: Pubkey,     // ATA
    price: u128,
    file_name: String,
    description: String,
    cash_back: u8,
    qty: u8,
    fee: u128,
    item_id: u128,
    variant: u8,
}
        let payload = GachaMarketplacePayload::try_from_slice(input).unwrap();

2 Answers 2

1
 #[derive(BorshDeserialize, BorshSerialize)]
 struct InitState<'a> {
     variant: &'a u8,
 }
 let param_init_state = InitState {
     variant: &4,
 };
 let mut transaction = Transaction::new_with_payer(
     &[Instruction::new_with_borsh(
         program_id,
         &param_init_state,
         vec![
             AccountMeta::new(payer.pubkey(), true),
             AccountMeta::new(*state_account.key, false),
             AccountMeta::new(system_program::ID, false),
         ],
     )],
     Some(&payer.pubkey()),
 );

 transaction.sign(&[&payer], recent_blockhash);

 match banks_client.process_transaction(transaction).await {
     Ok(()) => (),
     Err(e) => panic!("{}", e),
1
  • Hi @shahoria Asif Rabby, I don't understand what you mean. I see no different code from mine.
    – marethyu
    Commented Jan 11, 2023 at 9:59
0

The param in the instruction have to match the payload for try_from_slice

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.