Learning Rust and Anchor here. I'm trying to return a ProgramError for a specific scenario in this program, but when using the into() method inside #[program] an error msg is shown.
I've checked the documentation:
- https://doc.rust-lang.org/rust-by-example/conversion/from_into.html
- https://doc.rust-lang.org/std/convert/trait.Into.html
Here's the error message:
the trait bound
anchor_lang::prelude::ProgramError: From<ErrorCode>is not satisfied the following other types implement traitFrom<T>: <anchor_lang::prelude::ProgramError as From>
<anchor_lang::prelude::ProgramError as From<anchor_lang::error::Error>> <anchor_lang::prelude::ProgramError as Fromstd::io::Error> <anchor_lang::prelude::ProgramError as From> required forErrorCodeto implementInto<anchor_lang::prelude::ProgramError>
Here the program code.
#[program]
pub mod solana_twitter {
use super::*;
pub fn send_tweet(
// SendTweet was used as generic type to link the context to this function
ctx: Context<SendTweet>,
topic: String,
content: String,
) -> ProgramResult {
let tweet: &mut Account<Tweet> = &mut ctx.accounts.tweet;
// Signer is used to guarantee that the account is owned by the author
let author: &Signer = &ctx.accounts.author;
let clock: Clock = Clock::get().unwrap();
if topic.chars().count() > 50 {
return Err(ErrorCode::TopicTooLong.into());
}
if content.chars().count() > 280 {
return Err(ErrorCode::ContentTooLong.into());
}
tweet.author = *author.key;
tweet.timestamp = clock.unix_timestamp;
tweet.topic = topic;
tweet.content = content;
Ok(())
}
}
The ErrorCode enum.
#[error_code]
pub enum ErrorCode {
#[msg("The provided topic should be 50 characters long maximum.")]
TopicTooLong,
#[msg("The provided content should be 280 characters long maximum.")]
ContentTooLong,
}
You are suppose to use the
anchor_lang::errmacro to wrap the error.it should be
See: https://www.anchor-lang.com/docs/errors
Also I think you should be returning
Result<()>instead ofProgramResult.