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

refactor tests: use macro runtime #2

Merged
merged 5 commits into from
Dec 2, 2024
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
34 changes: 0 additions & 34 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 3 additions & 5 deletions pallets/template/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,20 @@ codec = { features = [
scale-info = { features = [
"derive",
], workspace = true }
pallet-balances.workspace = true
frame = { version = "0.7.0", package = "polkadot-sdk-frame", default-features = false, features = ["experimental", "runtime"] }
frame-benchmarking = { optional = true, workspace = true }
frame-support.workspace = true
frame-system.workspace = true
sp-io = { workspace = true }
sp-runtime = { workspace = true }

[dev-dependencies]
sp-core = { default-features = true, workspace = true }
sp-io = { default-features = true, workspace = true }
sp-runtime = { default-features = true, workspace = true }
pallet-balances = { default-features = true, workspace = true }

[features]
default = ["std"]
std = [
"codec/std",
"frame/std",
"frame-benchmarking?/std",
"frame-support/std",
"frame-system/std",
Expand Down
87 changes: 77 additions & 10 deletions pallets/template/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,100 @@
use super::*;

#[allow(unused)]
use crate::Pallet as Template;
use crate::Pallet as Collectables;
use frame_benchmarking::v2::*;
use frame_support::traits::fungible::Inspect;
use frame_support::traits::fungible::Mutate;
use frame_system::RawOrigin;

#[benchmarks]
mod benchmarks {
use super::*;

#[benchmark]
fn do_something() {
let value = 100u32;
fn create_kitty() {
let caller: T::AccountId = whitelisted_caller();

#[extrinsic_call]
do_something(RawOrigin::Signed(caller), value);
create_kitty(RawOrigin::Signed(caller.clone()));

let count = CountForKitties::<T>::get();
assert_eq!(count, 1);

let owned = KittiesOwned::<T>::get(caller);
assert_eq!(owned.len(), 1);
}

#[benchmark]
fn transfer() {
let caller: T::AccountId = whitelisted_caller();
let recipient: T::AccountId = account("bob", 0, 0);

Pallet::<T>::create_kitty(RawOrigin::Signed(caller.clone()).into()).unwrap();
let kitty_id = KittiesOwned::<T>::get(caller.clone())[0];

#[extrinsic_call]
transfer(
RawOrigin::Signed(caller.clone()),
recipient.clone(),
kitty_id,
);

let recipient_owned = KittiesOwned::<T>::get(recipient.clone());
assert_eq!(recipient_owned.len(), 1);
assert_eq!(recipient_owned[0], kitty_id);

assert_eq!(Something::<T>::get(), Some(value));
let caller_owned = KittiesOwned::<T>::get(caller.clone());
assert_eq!(caller_owned.len(), 0);
}

#[benchmark]
fn cause_error() {
Something::<T>::put(100u32);
fn set_price() {
let caller: T::AccountId = whitelisted_caller();
let price: BalanceOf<T> = 100u32.into();

Pallet::<T>::create_kitty(RawOrigin::Signed(caller.clone()).into()).unwrap();
let kitty_id = KittiesOwned::<T>::get(caller.clone())[0];
assert_eq!(Kitties::<T>::get(kitty_id).unwrap().price, None);

#[extrinsic_call]
cause_error(RawOrigin::Signed(caller));
set_price(RawOrigin::Signed(caller.clone()), kitty_id, Some(price));
assert_eq!(Kitties::<T>::get(kitty_id).unwrap().price, Some(price));
}

#[benchmark]
fn buy_kitty() -> Result<(), BenchmarkError> {
let seller: T::AccountId = whitelisted_caller();
let buyer: T::AccountId = account("bob", 0, 0);

let ed = T::NativeCurrency::minimum_balance();
let price: BalanceOf<T> = 100u32.into();
let balance: BalanceOf<T> = ed + price * 2u32.into();

T::NativeCurrency::mint_into(&buyer, balance)?;
T::NativeCurrency::mint_into(&seller, ed)?;

Pallet::<T>::create_kitty(RawOrigin::Signed(seller.clone()).into())?;
let kitty_id = KittiesOwned::<T>::get(seller.clone())[0];
Pallet::<T>::set_price(
RawOrigin::Signed(seller.clone()).into(),
kitty_id,
Some(price),
)?;

#[extrinsic_call]
buy_kitty(RawOrigin::Signed(buyer.clone()), kitty_id, price);

let kitty = Kitties::<T>::get(kitty_id).unwrap();
assert_eq!(kitty.owner, buyer);
assert_eq!(kitty.price, None);

assert_eq!(Something::<T>::get(), Some(101u32));
Ok(())
}

impl_benchmark_test_suite!(Template, crate::mock::new_test_ext(), crate::mock::Test);
impl_benchmark_test_suite!(
Template,
crate::tests::new_test_ext(),
crate::tests::TestRuntime
);
}
22 changes: 10 additions & 12 deletions pallets/template/src/impls.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use super::*;
use frame::primitives::BlakeTwo256;
use frame::traits::{Currency, ExistenceRequirement::KeepAlive, Hash};
use codec::Encode;
use frame_support::pallet_prelude::*;
use frame_support::traits::fungible::Mutate;
use frame_support::traits::tokens::Preservation;
use sp_io::hashing::blake2_256;

impl<T: Config> Pallet<T> {
pub fn gen_dna() -> [u8; 32] {
Expand All @@ -10,8 +13,8 @@ impl<T: Config> Pallet<T> {
frame_system::Pallet::<T>::extrinsic_index(),
CountForKitties::<T>::get(),
);
let hash: [u8; 32] = BlakeTwo256::hash_of(&unique_payload).into();
return hash;
let serialized_payload = unique_payload.encode();
blake2_256(&serialized_payload)
}

pub fn do_transfer(from: T::AccountId, to: T::AccountId, dna: [u8; 32]) -> DispatchResult {
Expand Down Expand Up @@ -133,7 +136,7 @@ impl<T: Config> Pallet<T> {
pub fn do_set_price(
from: T::AccountId,
kitty_id: [u8; 32],
price: Option<T::Balance>,
price: Option<BalanceOf<T>>,
) -> DispatchResult {
let mut kitty = Kitties::<T>::get(kitty_id).ok_or(Error::<T>::NoKitty)?;
ensure!(kitty.owner == from, Error::<T>::NotOwner);
Expand All @@ -153,7 +156,7 @@ impl<T: Config> Pallet<T> {
pub fn do_buy_kitty(
buyer: T::AccountId,
kitty_id: [u8; 32],
max_price: T::Balance,
max_price: BalanceOf<T>,
) -> DispatchResult {
let buyer_address = buyer.clone();
// Question: Really necessary to check the existence of kitty_id if calling do_transfer (which already do that?)
Expand All @@ -170,12 +173,7 @@ impl<T: Config> Pallet<T> {
None => return Err(Error::<T>::NotForSale.into()),
};

//
// TODO:inspect pallet, look for transfer function
// let saldo = pallet_balances::Pallet::<T>::free_balance(&buyer);
// pallet_balances::Pallet::<T>::transfer(
pallet_balances::Pallet::<T>::transfer(&buyer, &kitty.owner, price, KeepAlive)?;
// T::NativeBalance::transfer(&buyer, &kitty.owner, price, Preservation::Preserve)?;
T::NativeCurrency::transfer(&buyer, &kitty.owner, price, Preservation::Preserve)?;

// maybe refactor to accept &mut buyer? ownership move cause `buyer_address`
Self::do_transfer(kitty.owner, buyer.clone(), kitty_id)?;
Expand Down
Loading
Loading