4

I have written a program, where if the value of dog is greater than 0 I want my cat to fail.

use anchor_lang::prelude::*;

// This is your program's public key and it will update
// automatically when you build the project.
declare_id!("3QGcf8dpdhDpTrF1Q7i9QDZH1FtB6KKrYT5ZZJF5C4ZK");

#[program]
mod hello_anchor {
    use super::*;
    pub fn initialize(ctx: Context<Initialize>) -> Result<()> { 
        //msg!("The value after initializing is {} {} {} ", value.dog,value.cat,value.color);// Message will show up in the tx logs
        Ok(())
    }
    pub fn dog(ctx:Context<Value1>,data:u8) -> Result<()> {
        let dognumber =&mut ctx.accounts.dog;
        dognumber.dog = data;
        msg!("value of dog number is {}",dognumber.dog);
        Ok(())
    }
    pub fn cat(ctx:Context<Value2>,data:u8,color:String) -> Result<()> {
        if ctx.accounts.cat.dog == 0{
            let catnumberandcolor  =&mut ctx.accounts.cat;
            catnumberandcolor.cat = data;
            catnumberandcolor.color = color;
            Ok(())
        }
        else{
            break;
        }
    }

    
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    // We must specify the space in order to initialize an account.
    // First 8 bytes are default account discriminator,
    // next 8 bytes come from NewAccount.data being type u64.
    // (u64 = 64 bits unsigned integer = 8 bytes)
    #[account(init, payer = signer, space = 8 + 32)]
    pub world: Account<'info, NewAccount>,
    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct Value1<'info> {
    #[account(mut)]
    pub dog:Account<'info,NewAccount>,
}

#[derive(Accounts)]
pub struct Value2<'info> {
     #[account(mut)]
    pub cat:Account<'info,NewAccount>,
}
#[account]
pub struct NewAccount {
    cat:u8,
    dog:u8,
    color:String,
}

If the value of dog is greater than 0 I want it to fail. Please do let me even know how I can directly get the value of dog upon calling the function dog in the if/else statement.

1 Answer 1

3

Can use: https://docs.rs/anchor-lang/latest/anchor_lang/macro.require_gte.html

Pass it your custom error so it will be easy to understand why it failed in the transaction log.

3
  • I want it to fail purposely or exit the code and not confirm the transaction. Like, break out of the code completely. Commented Sep 14, 2022 at 7:32
  • This is definitely helpfull but I even want the code to crash if if value of dog is greater than 0 Commented Sep 14, 2022 at 7:47
  • 1
    require! will make the txn fail, I think uses panic!
    – Ohad Dahan
    Commented Sep 14, 2022 at 13:47

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.