Skip to content
Open
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
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"))'
]
212 changes: 212 additions & 0 deletions integration-tests/public/ensure-test/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
#![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());
}
}
#[cfg(all(test, feature = "e2e-tests"))]
mod e2e_tests {
use super::*;
use ink_e2e::ContractsBackend;
type E2EResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[ink_e2e::test]
async fn e2e_transfer_succeeds(mut client: Client) -> E2EResult<()> {
// Deploy the contract
let mut constructor = EnsureTestRef::new(U256::from(1000));
let contract = client
.instantiate("ensure_test", &ink_e2e::alice(), &mut constructor)
.submit()
.await
.expect("instantiate failed");
let mut call_builder = contract.call_builder::<EnsureTest>();
let transfer = call_builder.transfer(U256::from(500));
let result = client
.call(&ink_e2e::alice(), &transfer)
.submit()
.await
.expect("transfer should succeed");
assert!(result.return_value().is_ok());

Ok(())
}
#[ink_e2e::test]
async fn e2e_transfer_fails_with_value_must_be_positive(
mut client: Client,
) -> E2EResult<()> {
// Deploy contract
let mut constructor = EnsureTestRef::new(U256::from(1000));
let contract = client
.instantiate("ensure_test", &ink_e2e::alice(), &mut constructor)
.submit()
.await
.expect("instantiate failed");
let mut call_builder = contract.call_builder::<EnsureTest>();

// Try to transfer zero - should fail
let transfer = call_builder.transfer(U256::from(0));
let result = client.call(&ink_e2e::alice(), &transfer).dry_run().await?;

// Check it reverted and decode the error
assert!(result.did_revert(), "should revert");
let error_data = result.return_data();
let decoded_error =
<Error as ink::scale::Decode>::decode(&mut &error_data[..])?;
assert_eq!(decoded_error, Error::ValueMustBePositive);

Ok(())
}
#[ink_e2e::test]
async fn e2e_transfer_fails_with_insufficient_balance(
mut client: Client,
) -> E2EResult<()> {
let mut constructor = EnsureTestRef::new(U256::from(100));
let contract = client
.instantiate("ensure_test", &ink_e2e::alice(), &mut constructor)
.submit()
.await
.expect("instantiate failed");
let mut call_builder = contract.call_builder::<EnsureTest>();

// Try to transfer more than balance (200 when balance is 100)
let transfer = call_builder.transfer(U256::from(200));
let result = client.call(&ink_e2e::alice(), &transfer).dry_run().await?;

assert!(result.did_revert());
let error_data = result.return_data();
let decoded_error =
<Error as ink::scale::Decode>::decode(&mut &error_data[..])?;
assert_eq!(decoded_error, Error::InsufficientBalance);

Ok(())
}
#[ink_e2e::test]
async fn e2e_transfer_fails_with_value_too_large(
mut client: Client,
) -> E2EResult<()> {
let mut constructor = EnsureTestRef::new(U256::from(2000));
let contract = client
.instantiate("ensure_test", &ink_e2e::alice(), &mut constructor)
.submit()
.await
.expect("instantiate failed");
let mut call_builder = contract.call_builder::<EnsureTest>();

// Try to transfer more than max (1001 when max is 1000)
let transfer = call_builder.transfer(U256::from(1001));
let result = client.call(&ink_e2e::alice(), &transfer).dry_run().await?;

assert!(result.did_revert());
let error_data = result.return_data();
let decoded_error =
<Error as ink::scale::Decode>::decode(&mut &error_data[..])?;
assert_eq!(decoded_error, Error::ValueTooLarge);

Ok(())
}
}
}
Copy link
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
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
Loading
Loading