Skip to content

Commit

Permalink
fix: comments
Browse files Browse the repository at this point in the history
  • Loading branch information
chungquantin committed Oct 10, 2024
1 parent c1a6fea commit c598eae
Show file tree
Hide file tree
Showing 2 changed files with 137 additions and 54 deletions.
52 changes: 27 additions & 25 deletions crates/pop-drink/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,20 @@ fn decode<T: Decode>(data: &[u8]) -> T {

/// Runtime error for testing.
///
/// # Generic Parameters:
/// # Generic Parameters
///
/// - `ModuleError` - Error type of the runtime modules. Reference: https://paritytech.github.io/polkadot-sdk/master/solochain_template_runtime/enum.Error.html.
/// - `ApiError` - Error type of the API, which depends on version.
/// - `MODULE_INDEX` - Index of the variant `Error::Module`. This is based on the index of
/// `ApiError::Module`
/// - `ModuleError` - Error type of the runtime modules. [Reference](https://paritytech.github.io/polkadot-sdk/master/solochain_template_runtime/enum.Error.html).
/// - `ApiError` - Error type of the API, which depends on version. [Reference](https://github.com/r0gue-io/pop-node/tree/main/pop-api).
/// - `MODULE_INDEX` - Index of the variant `Error::Module`. This is based on the index of [`ApiError::Module`](https://github.com/r0gue-io/pop-node/blob/main/primitives/src/lib.rs#L38).
#[derive(Encode, Decode, Debug)]
pub enum Error<ModuleError, ApiError, const MODULE_INDEX: u8>
where
ModuleError: Decode + Encode + Debug,
ApiError: Decode + Encode + Debug + From<u32> + Into<u32>,
{
/// Module errors of the runtime.
/// Error type of the runtime modules. [Reference](https://paritytech.github.io/polkadot-sdk/master/solochain_template_runtime/enum.Error.html).
Module(ModuleError),
/// Every `ApiError`.
/// Every [`ApiError`](https://github.com/r0gue-io/pop-node/blob/52fb7f06a89955d462900e33d2b9c9170c4534a0/primitives/src/lib.rs#L30).
Api(ApiError),
}

Expand All @@ -38,7 +37,7 @@ where
ModuleError: Decode + Encode + Debug,
ApiError: Decode + Encode + Debug + From<u32> + Into<u32>,
{
/// Converts a `Error` into a numerical value of `ApiError`.
/// Converts an `Error` into a numerical value of `ApiError`.
///
/// This conversion is necessary for comparing `Error` instances with other types.
// Compared types must implement `Into<u32>`, as `Error` does not implement `Eq`.
Expand All @@ -64,9 +63,9 @@ where
ModuleError: Decode + Encode + Debug,
ApiError: Decode + Encode + Debug + From<u32> + Into<u32>,
{
/// Converts a numerical value of `ApiError` into a `Error`.
/// Converts a numerical value of `ApiError` into an `Error`.
///
/// This is used to reconstruct and display a `Error` from its numerical representation
/// This is used to reconstruct and display an `Error` from its numerical representation
/// when an error is thrown.
fn from(value: u32) -> Self {
let error = ApiError::from(value);
Expand All @@ -80,16 +79,17 @@ where
}
}

/// A utility macro to assert that an error returned from a smart contract method using API
/// V0.
/// Asserts that a `Result` with an error type convertible to `u32` matches the expected `Error`
/// from pop-drink.
///
/// # Parameters:
/// # Parameters
///
/// - `result` - The result returned by a smart contract method. It is of type `Result<R, E>`, where
/// the error type `E` must implement a conversion to `u32`.
/// - `error` - A `Error` type configured specifically for the API V0.
/// - `result` - The `Result<R, E>` from a smart contract method, where `E` must be convertible to
/// `u32`.
/// - `error` - The expected runtime specific `Error` to assert against the `E` error type from
/// `result`.
///
/// # Example:
/// # Examples
///
/// ```rs
/// use drink::devnet::{
Expand Down Expand Up @@ -123,19 +123,21 @@ macro_rules! assert_err {
};
}

/// A utility macro to assert that an error returned from a smart contract method matches the
/// `Error`.
/// Asserts that a `Result` with an error type convertible to `u32` matches the expected `Error`
/// from pop-drink.
///
/// # Generic parameters:
/// # Generic parameters
///
/// - `R` - Success type returned if Ok().
/// - `E` - Returned `Err()` value of a method result. Must be convertable to `u32`.
/// - `R` - Type returned if `result` is `Ok()`.
/// - `E` - Type returend if `result` is `Err()`. Must be convertible to `u32`.
/// - `Error` - Runtime error type.
///
/// # Parameters:
/// # Parameters
///
/// - `result` - Result returned by a smart contract method.
/// - `expected_error` - `Error` to be asserted.
/// - `result` - The `Result<R, E>` from a smart contract method, where `E` must be convertible to
/// `u32`.
/// - `expected_error` - The expected runtime specific `Error` to assert against the `E` error type
/// from `result`.
#[track_caller]
pub fn assert_err_inner<R, E, Error>(result: Result<R, E>, expected_error: Error)
where
Expand Down
139 changes: 110 additions & 29 deletions crates/pop-drink/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub use sp_io::TestExternalities;

pub mod error;
#[cfg(test)]
pub mod mock;
mod mock;

pub mod devnet {
pub use pop_runtime_devnet::Runtime;
Expand Down Expand Up @@ -43,23 +43,56 @@ pub mod devnet {
}
}

/// Deploys a contract with a given constructo methodr, arguments, salt and initial value. In case
/// of success, returns the address of the deployed contract.
/// Deploys a contract with a given constructor method, arguments, salt and an initial value. In
/// case of success, returns the address of the deployed contract.
///
/// # Generic Parameters:
/// # Generic Parameters
///
/// - `S`: Sandbox defines the API of a sandboxed runtime.
/// - `E`: Decodable error type returned if the contract deployment fails.
/// - `S` - [`Sandbox`](https://github.com/r0gue-io/pop-drink/blob/main/crates/ink-sandbox/src/lib.rs)
/// environment for the Pop Network runtime.
/// - `E` - Decodable error type returned if the contract deployment fails.
///
/// # Parameters:
/// # Parameters
///
/// - `session` - Wrapper around `Sandbox`` that provides a convenient API for interacting with
/// multiple contracts.
/// - `bundle` - A struct representing the result of parsing a `.contract` bundle file.
/// - `method` - The name of the constructor method.
/// - `session` - Wrapper around [`Sandbox`](https://github.com/r0gue-io/pop-drink/blob/main/crates/ink-sandbox/src/lib.rs)
/// that provides methods to interact with multiple contracts. [Reference](https://github.com/r0gue-io/pop-drink/blob/main/crates/drink/drink/src/session.rs).
/// - `bundle` - A struct representing the result of parsing a `.contract` bundle file. [Reference](https://github.com/r0gue-io/pop-drink/blob/main/crates/drink/drink/src/session/bundle.rs).
/// - `method` - The name of the contract constructor method. For trait methods, use
/// `trait_name::method_name` (e.g., `Psp22::transfer`).
/// - `input` - Arguments passed to the constructor method.
/// - `salt` - Additional data used to influence the contract deployment address.
/// - `init_value` - Initial funds allocated for the contract.
/// - `init_value` - Initial funds allocated for the contract. Requires the contract method to be
/// `payable`.
///
/// # Examples
///
/// ```rs
/// /// The contract bundle provider.
/// #[drink::contract_bundle_provider]
/// enum BundleProvider {}
///
/// /// Sandbox environment for Pop Devnet Runtime.
/// pub struct Pop {
/// ext: TestExternalities,
/// }
///
/// // Implement core functionalities for the `Pop` sandbox.
/// drink::impl_sandbox!(Pop, Runtime, ALICE);
///
/// #[drink::test(sandbox = Pop)]
/// fn test_constructor_works() {
/// let local_contract = BundleProvider::local().unwrap();
/// // Contract address is returned if a deployment succeeds.
/// let contract = deploy(
/// &mut session,
/// local_contract,
/// "new",
/// vec![TOKEN.to_string(), MIN_BALANCE.to_string()],
/// vec![],
/// None
/// ).unwrap();
/// }
/// ```
pub fn deploy<S, E>(
session: &mut Session<S>,
bundle: ContractBundle,
Expand All @@ -84,19 +117,50 @@ where

/// Call a contract method and decode the returned data.
///
/// # Generic Parameters:
/// # Generic Parameters
///
/// - `S` - Sandbox defines the API of a sandboxed runtime.
/// - `O` - Decodable output type returned if the contract deployment succeeds.
/// - `E` - Decodable error type returned if the contract deployment fails.
/// - `S` - [`Sandbox`](https://github.com/r0gue-io/pop-drink/blob/main/crates/ink-sandbox/src/lib.rs)
/// environment for the Pop Network runtime.
/// - `O` - Decodable output type returned if the contract execution succeeds.
/// - `E` - Decodable error type returned if the contract execution fails.
///
/// # Parameters:
/// # Parameters
///
/// - `session` - Wrapper around `Sandbox`` that provides a convenient API for interacting with
/// multiple contracts.
/// - `func_name` - The name of the contract method.
/// - `session` - Wrapper around [`Sandbox`](https://github.com/r0gue-io/pop-drink/blob/main/crates/ink-sandbox/src/lib.rs)
/// that provides methods to interact with multiple contracts. [Reference](https://github.com/r0gue-io/pop-drink/blob/main/crates/drink/drink/src/session.rs).
/// - `func_name`: The name of the contract method. For trait methods, use `trait_name::method_name`
/// (e.g., `Psp22::transfer`).
/// - `input` - Arguments passed to the contract method.
/// - `endowment` - Funds allocated for the contract execution.
/// - `endowment` - Funds allocated for the contract execution. Requires the contract method to be
/// `payable`.
///
/// # Examples
///
/// ```rs
/// /// The contract bundle provider.
/// #[drink::contract_bundle_provider]
/// enum BundleProvider {}
///
/// /// Sandbox environment for Pop Devnet Runtime.
/// pub struct Pop {
/// ext: TestExternalities,
/// }
///
/// // Implement core functionalities for the `Pop` sandbox.
/// drink::impl_sandbox!(Pop, Runtime, ALICE);
///
/// /// Call to a contract method `Psp22::transfer` and return error `PSP22Error` if fails.
/// fn transfer(session: &mut Session<Pop>, to: AccountId, amount: Balance) -> Result<(), PSP22Error> {
/// // Convert empty array into string.
/// let empty_array = serde_json::to_string::<[u8; 0]>(&[]).unwrap();
/// call::<Pop, (), PSP22Error>(
/// session,
/// "Psp22::transfer",
/// vec![to.to_string(), amount.to_string(), empty_array],
/// None,
/// )
/// }
/// ```
pub fn call<S, O, E>(
session: &mut Session<S>,
func_name: &str,
Expand All @@ -111,9 +175,8 @@ where
{
match session.call::<String, ()>(func_name, &input, endowment) {
// If the call is reverted, decode the error into the specified error type.
Err(SessionError::CallReverted(error)) => {
Err(E::decode(&mut &error[2..]).expect("Decoding failed"))
},
Err(SessionError::CallReverted(error)) =>
Err(E::decode(&mut &error[2..]).expect("Decoding failed")),
// If the call is successful, decode the last returned value.
Ok(_) => Ok(session
.record()
Expand All @@ -131,14 +194,32 @@ fn account_id_from_slice(s: &[u8; 32]) -> pop_api::primitives::AccountId {

/// Get the last event from pallet contracts.
///
/// # Generic Parameters:
/// # Generic Parameters
///
/// - `S` - [`Sandbox`](https://github.com/r0gue-io/pop-drink/blob/main/crates/ink-sandbox/src/lib.rs)
/// environment for the Pop Network runtime.
///
/// # Parameters
///
/// - `session` - Wrapper around [`Sandbox`](https://github.com/r0gue-io/pop-drink/blob/main/crates/ink-sandbox/src/lib.rs)
/// that provides methods to interact with multiple contracts. [Reference](https://github.com/r0gue-io/pop-drink/blob/main/crates/drink/drink/src/session.rs).
///
/// - `S` - Sandbox defines the API of a sandboxed runtime.
/// # Examples
///
/// # Parameters:
/// ```rs
/// use drink::{assert_ok, devnet::account_id_from_slice, last_contract_event};
///
/// - `session` - Wrapper around `Sandbox`` that provides a convenient API for interacting with
/// multiple contracts.
/// assert_eq!(
/// last_contract_event(&session).unwrap(),
/// Transfer {
/// from: Some(account_id_from_slice(&ALICE)),
/// to: Some(account_id_from_slice(&BOB)),
/// value,
/// }
/// .encode()
/// .as_slice()
/// );
/// ```
pub fn last_contract_event<S>(session: &Session<S>) -> Option<Vec<u8>>
where
S: Sandbox,
Expand Down

0 comments on commit c598eae

Please sign in to comment.