solana-twitter icon indicating copy to clipboard operation
solana-twitter copied to clipboard

Bound trait not satisfied for ErrorCode in anchor 0.22.0 and later

Open wstrinz opened this issue 2 years ago • 0 comments

In episode 4, after adding these guards for the error codes:

    if topic.chars().count() > 50 {
        return Err(ErrorCode::TopicTooLong.into())
    }

    if content.chars().count() > 280 {
        return Err(ErrorCode::ContentTooLong.into())
    }

I get compilation errors that look like

the trait bound `anchor_lang::prelude::ProgramError: From<ErrorCode>` is not satisfied
the following implementations were found:
  <anchor_lang::prelude::ProgramError as From<PubkeyError>>
  <anchor_lang::prelude::ProgramError as From<anchor_lang::error::Error>>
  <anchor_lang::prelude::ProgramError as From<std::io::Error>>
  <anchor_lang::prelude::ProgramError as From<u64>>
required because of the requirements on the impl of `Into<anchor_lang::prelude::ProgramError>` for `ErrorCode`

It seems that anchor 0.22.0 introduced breaking changes to error handling. After following the upgrade instructions from the anchor changelog, I got it to compile by changing the return type to Result<()>, and using the error! macro:

    pub fn send_tweet(ctx: Context<SendTweet>, topic: String, content: String) -> Result<()> {
        let tweet: &mut Account<Tweet> = &mut ctx.accounts.tweet;
        let author: &Signer = &ctx.accounts.author;
        let clock: Clock = Clock::get().unwrap();

        if topic.chars().count() > 50 {
            return Err(error!(ErrorCode::TopicTooLong));
        }

        if content.chars().count() > 280 {
            return Err(error!(ErrorCode::ContentTooLong));
        }

        tweet.author = *author.key;
        tweet.timestamp = clock.unix_timestamp;
        tweet.topic = topic;
        tweet.content = content;

        Ok(())
    }

I'm still working through the later episodes, so this may not be correct at run time, but it seems to compile at least.

wstrinz avatar Jul 23 '22 19:07 wstrinz