Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lang: add additional require_x comparison macros #1622

Merged
merged 6 commits into from
Mar 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@ incremented for features.

* cli: Add `anchor clean` command that's the same as `cargo clean` but preserves keypairs inside `target/deploy` ([#1470](https://github.com/project-serum/anchor/issues/1470)).
* cli: Running `anchor init` now initializes a new git repository for the workspace. This can be disabled with the `--no-git` flag ([#1605](https://github.com/project-serum/anchor/pull/1605)).
* cli: Add support for `anchor idl fetch` to work outside anchor workspace ([#1509](https://github.com/project-serum/anchor/pull/1509)).
* cli: [[test.validator.clone]] also clones the program data account of programs owned by the bpf upgradeable loader ([#1481](https://github.com/project-serum/anchor/issues/1481)).
* lang: Add new `AccountSysvarMismatch` error code and test cases for sysvars ([#1535](https://github.com/project-serum/anchor/pull/1535)).
* lang: Replace `std::io::Cursor` with a custom `Write` impl that uses the Solana mem syscalls ([#1589](https://github.com/project-serum/anchor/pull/1589)).
* lang: Add `require_neq`, `require_keys_neq`, `require_gt`, and `require_gte` comparison macros ([#1622](https://github.com/project-serum/anchor/pull/1622)).
* spl: Add support for revoke instruction ([#1493](https://github.com/project-serum/anchor/pull/1493)).
* cli: Add support for `anchor idl fetch` to work outside anchor workspace ([#1509](https://github.com/project-serum/anchor/pull/1509)).
* ts: Add provider parameter to `Spl.token` factory method ([#1597](https://github.com/project-serum/anchor/pull/1597)).
* cli: [[test.validator.clone]] also clones the program data account of programs owned by the bpf upgradeable loader ([#1481](https://github.com/project-serum/anchor/issues/1481)).

### Fixes

Expand Down
12 changes: 12 additions & 0 deletions lang/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,18 @@ pub enum ErrorCode {
/// 2502 - A require_keys_eq expression was violated
#[msg("A require_keys_eq expression was violated")]
RequireKeysEqViolated,
/// 2503 - A require_neq expression was violated
#[msg("A require_neq expression was violated")]
RequireNeqViolated,
/// 2504 - A require_keys_neq expression was violated
#[msg("A require_keys_neq expression was violated")]
RequireKeysNeqViolated,
/// 2505 - A require_gt expression was violated
#[msg("A require_gt expression was violated")]
RequireGtViolated,
/// 2506 - A require_gte expression was violated
#[msg("A require_gte expression was violated")]
RequireGteViolated,

// Accounts.
/// 3000 - The account discriminator was already set on this account
Expand Down
126 changes: 123 additions & 3 deletions lang/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,9 +239,9 @@ pub mod prelude {
accounts::signer::Signer, accounts::system_account::SystemAccount,
accounts::sysvar::Sysvar, accounts::unchecked_account::UncheckedAccount, constant,
context::Context, context::CpiContext, declare_id, emit, err, error, event, interface,
program, require, require_eq, require_keys_eq,
solana_program::bpf_loader_upgradeable::UpgradeableLoaderState, source, state, zero_copy,
AccountDeserialize, AccountSerialize, Accounts, AccountsExit, AnchorDeserialize,
program, require, require_eq, require_gt, require_gte, require_keys_eq, require_keys_neq,
require_neq, solana_program::bpf_loader_upgradeable::UpgradeableLoaderState, source, state,
zero_copy, AccountDeserialize, AccountSerialize, Accounts, AccountsExit, AnchorDeserialize,
AnchorSerialize, Id, Key, Owner, ProgramData, Result, System, ToAccountInfo,
ToAccountInfos, ToAccountMetas,
};
Expand Down Expand Up @@ -397,6 +397,36 @@ macro_rules! require_eq {
};
}

/// Ensures two NON-PUBKEY values are not equal.
///
/// Use [require_keys_neq](crate::prelude::require_keys_neq)
/// to compare two pubkeys.
///
/// Can be used with or without a custom error code.
///
/// # Example
/// ```rust,ignore
/// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
/// require_neq!(ctx.accounts.data.data, 0);
/// ctx.accounts.data.data = data;
/// Ok(());
/// }
/// ```
#[macro_export]
macro_rules! require_neq {
($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
if $value1 == $value2 {
return Err(error!($error_code).with_values(($value1, $value2)));
}
};
($value1: expr, $value2: expr $(,)?) => {
if $value1 == $value2 {
return Err(error!(anchor_lang::error::ErrorCode::RequireNeqViolated)
.with_values(($value1, $value2)));
}
};
}

/// Ensures two pubkeys values are equal.
///
/// Use [require_eq](crate::prelude::require_eq)
Expand Down Expand Up @@ -427,6 +457,96 @@ macro_rules! require_keys_eq {
};
}

/// Ensures two pubkeys are not equal.
///
/// Use [require_neq](crate::prelude::require_neq)
/// to compare two non-pubkey values.
///
/// Can be used with or without a custom error code.
///
/// # Example
/// ```rust,ignore
/// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
/// require_keys_neq!(ctx.accounts.data.authority.key(), ctx.accounts.other.key());
/// ctx.accounts.data.data = data;
/// Ok(())
/// }
/// ```
#[macro_export]
macro_rules! require_keys_neq {
($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
if $value1 == $value2 {
return Err(error!($error_code).with_pubkeys(($value1, $value2)));
}
};
($value1: expr, $value2: expr $(,)?) => {
if $value1 == $value2 {
return Err(
error!(anchor_lang::error::ErrorCode::RequireKeysNeqViolated)
.with_pubkeys(($value1, $value2)),
);
}
};
}

/// Ensures the first NON-PUBKEY value is greater than the second
/// NON-PUBKEY value.
///
/// To include an equality check, use [require_gte](crate::require_gte).
///
/// Can be used with or without a custom error code.
///
/// # Example
/// ```rust,ignore
/// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
/// require_gt!(ctx.accounts.data.data, 0);
/// ctx.accounts.data.data = data;
/// Ok(());
/// }
/// ```
#[macro_export]
macro_rules! require_gt {
($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
if $value1 <= $value2 {
return Err(error!($error_code).with_values(($value1, $value2)));
}
};
($value1: expr, $value2: expr $(,)?) => {
if $value1 <= $value2 {
return Err(error!(anchor_lang::error::ErrorCode::RequireGtViolated)
.with_values(($value1, $value2)));
}
};
}

/// Ensures the first NON-PUBKEY value is greater than or equal
/// to the second NON-PUBKEY value.
///
/// Can be used with or without a custom error code.
///
/// # Example
/// ```rust,ignore
/// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
/// require_gte!(ctx.accounts.data.data, 1);
/// ctx.accounts.data.data = data;
/// Ok(());
/// }
/// ```
#[macro_export]
macro_rules! require_gte {
($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
if $value1 < $value2 {
return Err(error!($error_code).with_values(($value1, $value2)));
}
};
($value1: expr, $value2: expr $(,)?) => {
if $value1 < $value2 {
return Err(error!(anchor_lang::error::ErrorCode::RequireGteViolated)
.with_values(($value1, $value2)));
}
};
}

/// Returns with the given error.
/// Use this with a custom error type.
///
Expand Down
1 change: 1 addition & 0 deletions tests/errors/Anchor.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ errors = "Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"
test = "yarn run mocha -t 1000000 tests/"

[features]
seeds = false
69 changes: 67 additions & 2 deletions tests/errors/programs/errors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,63 @@ mod errors {
Ok(())
}

pub fn require_neq(_ctx: Context<RequireNeq>) -> Result<()> {
require_neq!(500, 500, MyError::ValueMatch);
Ok(())
}

pub fn require_neq_default_error(_ctx: Context<RequireNeq>) -> Result<()> {
require_neq!(500, 500);
Ok(())
}

pub fn require_keys_eq(ctx: Context<RequireKeysEq>) -> Result<()> {
require_keys_eq!(ctx.accounts.some_account.key(), *ctx.program_id, MyError::ValueMismatch);
require_keys_eq!(
ctx.accounts.some_account.key(),
*ctx.program_id,
MyError::ValueMismatch
);
Ok(())
}

pub fn require_keys_eq_default_error(ctx: Context<RequireKeysEq>) -> Result<()> {
require_keys_eq!(ctx.accounts.some_account.key(), *ctx.program_id);
Ok(())
}

pub fn require_keys_neq(ctx: Context<RequireKeysNeq>) -> Result<()> {
require_keys_neq!(
ctx.accounts.some_account.key(),
*ctx.program_id,
MyError::ValueMatch
);
Ok(())
}

pub fn require_keys_neq_default_error(ctx: Context<RequireKeysNeq>) -> Result<()> {
require_keys_neq!(ctx.accounts.some_account.key(), *ctx.program_id);
Ok(())
}

pub fn require_gt(_ctx: Context<RequireGt>) -> Result<()> {
require_gt!(5, 10, MyError::ValueLessOrEqual);
Ok(())
}

pub fn require_gt_default_error(_ctx: Context<RequireGt>) -> Result<()> {
require_gt!(10, 10);
Ok(())
}

pub fn require_gte(_ctx: Context<RequireGt>) -> Result<()> {
require_gte!(5, 10, MyError::ValueLess);
Ok(())
}

pub fn require_gte_default_error(_ctx: Context<RequireGt>) -> Result<()> {
require_gte!(5, 10);
Ok(())
}
}

#[derive(Accounts)]
Expand Down Expand Up @@ -133,9 +181,23 @@ pub struct AccountOwnedByWrongProgramError<'info> {
#[derive(Accounts)]
pub struct RequireEq {}

#[derive(Accounts)]
pub struct RequireNeq {}

#[derive(Accounts)]
pub struct RequireGt {}

#[derive(Accounts)]
pub struct RequireGte {}

#[derive(Accounts)]
pub struct RequireKeysEq<'info> {
pub some_account: UncheckedAccount<'info>
pub some_account: UncheckedAccount<'info>,
}

#[derive(Accounts)]
pub struct RequireKeysNeq<'info> {
pub some_account: UncheckedAccount<'info>,
}

#[error_code]
Expand All @@ -146,4 +208,7 @@ pub enum MyError {
HelloNext,
HelloCustom,
ValueMismatch,
ValueMatch,
ValueLess,
ValueLessOrEqual,
}
Loading