Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[Unreleased]

### Added
- Implement `ensure!` macro similar to `frame_support::ensure!` for convenient error checking in ink! contracts - [#2747](https://github.com/use-ink/ink/issues/2747)
- Implements the API for the `pallet-revive` host functions `chain_id`, `balance_of`, `base_fee`, `origin`, `code_size`, `block_hash`, `block_author` - [#2719](https://github.com/use-ink/ink/pull/2719)
- Implement `From<ink::Address>` for "ink-as-dependency" contract refs - [#2728](https://github.com/use-ink/ink/pull/2728)

Expand Down
95 changes: 95 additions & 0 deletions crates/ink/src/ensure.rs
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()));
}
}
1 change: 1 addition & 0 deletions crates/ink/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub mod codegen;
pub use ink_env::reflect;

mod contract_ref;
mod ensure;
mod env_access;
mod message_builder;
pub mod precompiles;
Expand Down
31 changes: 31 additions & 0 deletions integration-tests/public/ensure-test/Cargo.toml
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"))'
]
112 changes: 112 additions & 0 deletions integration-tests/public/ensure-test/lib.rs
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());
}
}
}
Copy link
Copy Markdown
Collaborator

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.

Copy link
Copy Markdown
Contributor Author

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.

12 changes: 2 additions & 10 deletions integration-tests/public/erc1155/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use ink::{
Address,
U256,
prelude::vec::Vec,
ensure,
};

// This is the return value that we expect if a smart contract supports receiving ERC-1155
Expand Down Expand Up @@ -48,16 +49,7 @@ pub enum Error {
// The ERC-1155 result types.
pub type Result<T> = core::result::Result<T, Error>;

/// Evaluate `$x:expr` and if not true return `Err($y:expr)`.
///
/// Used as `ensure!(expression_to_ensure, expression_to_return_on_false)`.
macro_rules! ensure {
( $condition:expr, $error:expr $(,)? ) => {{
if !$condition {
return ::core::result::Result::Err(::core::convert::Into::into($error))
}
}};
}


/// The interface for an ERC-1155 compliant contract.
///
Expand Down
10 changes: 4 additions & 6 deletions integration-tests/public/erc20/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod erc20 {
use ink::{
U256,
storage::Mapping,
ensure,
};

/// A simple ERC-20 contract.
Expand Down Expand Up @@ -177,9 +178,7 @@ mod erc20 {
) -> Result<()> {
let caller = self.env().caller();
let allowance = self.allowance_impl(&from, &caller);
if allowance < value {
return Err(Error::InsufficientAllowance)
}
ensure!(allowance >= value, Error::InsufficientAllowance);
self.transfer_from_to(&from, &to, value)?;
// We checked that allowance >= value
#[allow(clippy::arithmetic_side_effects)]
Expand All @@ -203,9 +202,8 @@ mod erc20 {
value: U256,
) -> Result<()> {
let from_balance = self.balance_of_impl(from);
if from_balance < value {
return Err(Error::InsufficientBalance)
}
ensure!(from_balance >= value, Error::InsufficientBalance);

// We checked that from_balance >= value
#[allow(clippy::arithmetic_side_effects)]
self.balances.insert(from, &(from_balance - value));
Expand Down
15 changes: 4 additions & 11 deletions integration-tests/public/fallible-setter/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub enum Error {
#[ink::contract]
pub mod fallible_setter {
use super::Error;
use ink::ensure;

#[ink(storage)]
pub struct FallibleSetter {
Expand All @@ -24,9 +25,7 @@ pub mod fallible_setter {
/// Returns an error if `init_value > 100`.
#[ink(constructor)]
pub fn new(init_value: u8) -> Result<Self, Error> {
if init_value > 100 {
return Err(Error::TooLarge)
}
ensure!(init_value <= 100, Error::TooLarge);
Ok(Self { value: init_value })
}

Expand All @@ -36,14 +35,8 @@ pub mod fallible_setter {
/// - `init_value > 100`
#[ink(message)]
pub fn try_set(&mut self, value: u8) -> Result<(), Error> {
if self.value == value {
return Err(Error::NoChange);
}

if value > 100 {
return Err(Error::TooLarge);
}

ensure!(self.value != value, Error::NoChange);
ensure!(value <= 100, Error::TooLarge);
self.value = value;
Ok(())
}
Expand Down
Loading
Loading