-
Notifications
You must be signed in to change notification settings - Fork 477
Add ensure! macro to ink! and replace manual error checks in integration test contracts #2753
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
Open
CECILIA-MULANDI
wants to merge
5
commits into
use-ink:master
Choose a base branch
from
CECILIA-MULANDI:cecilia-implement-ensure-macro
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c48eb5c
Add ensure! macro to ink! and replace manual error checks in integrat…
CECILIA-MULANDI e9f58ec
Add CHANGELOG entry for ensure! macro
CECILIA-MULANDI bd15298
Fix formatting in lib.rs
CECILIA-MULANDI d5df2f4
Fix formatting in ensure-test contract
CECILIA-MULANDI 2b04709
Add E2E tests for ensure! macro
CECILIA-MULANDI File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| // Copyright (C) Use Ink (UK) Ltd. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| /// Evaluate `$condition:expr` and if not true return `Err($error:expr)`. | ||
| /// | ||
| /// This macro is similar to `frame_support::ensure!` and provides a convenient | ||
| /// way to check conditions and return errors in ink! contracts. | ||
| /// | ||
| /// # Example | ||
| /// | ||
| /// # use ink::ensure; | ||
| /// # #[derive(Debug, PartialEq, Eq)] | ||
| /// # #[ink::error] | ||
| /// # pub enum Error { | ||
| /// # InsufficientBalance, | ||
| /// # } | ||
| /// # pub type Result<T> = core::result::Result<T, Error>; | ||
| /// # | ||
| /// # fn example(balance: u32, amount: u32) -> Result<()> { | ||
| /// ensure!(balance >= amount, Error::InsufficientBalance); | ||
| /// // ... rest of the function | ||
| /// # Ok(()) | ||
| /// # } | ||
| /// ``` | ||
| #[macro_export] | ||
| macro_rules! ensure { | ||
| ( $condition:expr, $error:expr $(,)? ) => {{ | ||
| if !$condition { | ||
| return ::core::result::Result::Err(::core::convert::Into::into($error)); | ||
| } | ||
| }}; | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
|
|
||
| #[derive(Debug, PartialEq, Eq)] | ||
| enum TestError { | ||
| TooSmall, | ||
| TooLarge, | ||
| } | ||
| type TestResult<T> = core::result::Result<T, TestError>; | ||
|
|
||
| #[test] | ||
| fn ensure_works_when_condition_is_true() { | ||
| fn test_function(value: u32) -> TestResult<()> { | ||
| crate::ensure!(value > 0, TestError::TooSmall); | ||
| crate::ensure!(value < 100, TestError::TooLarge); | ||
| Ok(()) | ||
| } | ||
| // This should succeed when the conditions are met | ||
| assert_eq!(test_function(50), Ok(())); | ||
| } | ||
| #[test] | ||
| fn ensure_returns_error_when_condition_is_false() { | ||
| fn test_function(value: u32) -> TestResult<()> { | ||
| crate::ensure!(value > 10, TestError::TooSmall); | ||
| Ok(()) | ||
| } | ||
| // This should return error when condition fails | ||
| assert_eq!(test_function(5), Err(TestError::TooSmall)); | ||
| } | ||
| #[test] | ||
| fn ensure_works_with_trailing_comma() { | ||
| fn test_function(value: u32) -> TestResult<()> { | ||
| crate::ensure!(value > 0, TestError::TooSmall,); | ||
| Ok(()) | ||
| } | ||
|
|
||
| assert!(test_function(1).is_ok()); | ||
| assert_eq!(test_function(0), Err(TestError::TooSmall)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn ensure_works_with_string_error() { | ||
| fn test_function(value: u32) -> Result<(), String> { | ||
| crate::ensure!(value > 0, "Value must be positive".to_string()); | ||
| Ok(()) | ||
| } | ||
|
|
||
| assert!(test_function(1).is_ok()); | ||
| assert_eq!(test_function(0), Err("Value must be positive".to_string())); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| [package] | ||
| name = "ensure-test" | ||
| version = "6.0.0-beta.1" | ||
| authors = ["Use Ink <ink@use.ink>"] | ||
| edition = "2024" | ||
| publish = false | ||
|
|
||
| [dependencies] | ||
| ink = { path = "../../../crates/ink", default-features = false } | ||
|
|
||
| [dev-dependencies] | ||
| ink_e2e = { path = "../../../crates/e2e" } | ||
|
|
||
| [lib] | ||
| path = "lib.rs" | ||
|
|
||
| [features] | ||
| default = ["std"] | ||
| std = [ | ||
| "ink/std", | ||
| ] | ||
| ink-as-dependency = [] | ||
| e2e-tests = [] | ||
|
|
||
| [package.metadata.ink-lang] | ||
| abi = "ink" | ||
| [lints.rust.unexpected_cfgs] | ||
| level = "warn" | ||
| check-cfg = [ | ||
| 'cfg(ink_abi, values("ink", "sol", "all"))' | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| #![cfg_attr(not(feature = "std"), no_std, no_main)] | ||
|
|
||
| #[ink::contract] | ||
| mod ensure_test { | ||
| use ink::{ | ||
| U256, | ||
| ensure, | ||
| }; | ||
|
|
||
| /// A simple contract to test the ensure! macro. | ||
| #[ink(storage)] | ||
| #[derive(Default)] | ||
| pub struct EnsureTest { | ||
| balance: U256, | ||
| } | ||
|
|
||
| /// Error types for testing ensure! | ||
| #[derive(Debug, PartialEq, Eq)] | ||
| #[ink::error] | ||
| pub enum Error { | ||
| InsufficientBalance, | ||
| ValueTooLarge, | ||
| ValueMustBePositive, | ||
| } | ||
|
|
||
| /// Result type. | ||
| pub type Result<T> = core::result::Result<T, Error>; | ||
|
|
||
| impl EnsureTest { | ||
| /// Creates a new contract with initial balance. | ||
| #[ink(constructor)] | ||
| pub fn new(initial_balance: U256) -> Self { | ||
| Self { | ||
| balance: initial_balance, | ||
| } | ||
| } | ||
|
|
||
| /// Get the current balance. | ||
| #[ink(message)] | ||
| pub fn balance(&self) -> U256 { | ||
| self.balance | ||
| } | ||
|
|
||
| /// Transfer tokens - uses ensure! to check balance. | ||
| #[ink(message)] | ||
| pub fn transfer(&mut self, amount: U256) -> Result<()> { | ||
| // Test ensure! with positive value check | ||
| ensure!(amount > U256::from(0), Error::ValueMustBePositive); | ||
|
|
||
| // Test ensure! with balance check | ||
| ensure!(self.balance >= amount, Error::InsufficientBalance); | ||
|
|
||
| // Test ensure! with maximum value check | ||
| ensure!(amount <= U256::from(1000), Error::ValueTooLarge); | ||
|
|
||
| self.balance -= amount; | ||
| Ok(()) | ||
| } | ||
|
|
||
| /// Deposit tokens - uses ensure! with trailing comma. | ||
| #[ink(message)] | ||
| pub fn deposit(&mut self, amount: U256) -> Result<()> { | ||
| ensure!(amount > U256::from(0), Error::ValueMustBePositive,); | ||
| self.balance += amount; | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[ink::test] | ||
| fn ensure_works_with_positive_value() { | ||
| let mut contract = EnsureTest::new(U256::from(100)); | ||
| assert!(contract.transfer(U256::from(50)).is_ok()); | ||
| } | ||
|
|
||
| #[ink::test] | ||
| fn ensure_returns_error_for_zero_value() { | ||
| let mut contract = EnsureTest::new(U256::from(100)); | ||
| assert_eq!( | ||
| contract.transfer(U256::from(0)), | ||
| Err(Error::ValueMustBePositive) | ||
| ); | ||
| } | ||
|
|
||
| #[ink::test] | ||
| fn ensure_returns_error_for_insufficient_balance() { | ||
| let mut contract = EnsureTest::new(U256::from(50)); | ||
| assert_eq!( | ||
| contract.transfer(U256::from(100)), | ||
| Err(Error::InsufficientBalance) | ||
| ); | ||
| } | ||
|
|
||
| #[ink::test] | ||
| fn ensure_returns_error_for_value_too_large() { | ||
| let mut contract = EnsureTest::new(U256::from(2000)); | ||
| assert_eq!( | ||
| contract.transfer(U256::from(1001)), | ||
| Err(Error::ValueTooLarge) | ||
| ); | ||
| } | ||
|
|
||
| #[ink::test] | ||
| fn ensure_works_with_trailing_comma() { | ||
| let mut contract = EnsureTest::new(U256::from(100)); | ||
| assert!(contract.deposit(U256::from(50)).is_ok()); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you for the PR! Can you add some E2E tests here? They should check for the error codes/messages as well.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi, i've added them.