diff --git a/pallets/acurast/src/benchmarking.rs b/pallets/acurast/src/benchmarking.rs index fef529bb..55009a00 100644 --- a/pallets/acurast/src/benchmarking.rs +++ b/pallets/acurast/src/benchmarking.rs @@ -1,15 +1,15 @@ -use acurast_common::{AttestationChain, JobRegistration, Script}; use frame_benchmarking::{account, benchmarks, whitelist_account}; use frame_support::{ assert_ok, - sp_runtime::traits::{AccountIdConversion, Get, StaticLookup}, - traits::{Currency, OriginTrait}, + sp_runtime::traits::{AccountIdConversion, Get}, + traits::OriginTrait, BoundedVec, }; use frame_system::RawOrigin; use hex_literal::hex; use sp_std::prelude::*; +use acurast_common::{AttestationChain, JobRegistration, Script}; pub use pallet::Config; use crate::utils::validate_and_extract_attestation; @@ -30,15 +30,7 @@ const SCRIPT_BYTES: [u8; 53] = hex!("697066733A2F2F00000000000000000000000000000 pub trait BenchmarkHelper { fn registration_extra() -> T::RegistrationExtra; -} - -impl BenchmarkHelper for () -where - T::RegistrationExtra: Default, -{ - fn registration_extra() -> T::RegistrationExtra { - Default::default() - } + fn funded_account(index: u32) -> T::AccountId; } pub fn assert_last_event(generic_event: ::RuntimeEvent) { @@ -89,46 +81,8 @@ pub fn attestation_chain() -> AttestationChain { } } -fn token_22_funded_account() -> T::AccountId -where - T: pallet_assets::Config, - ::AssetId: From, - ::Balance: From, -{ - use pallet_assets::Pallet as Assets; - let caller: T::AccountId = account("token_account", 0, SEED); - whitelist_account!(caller); - let pallet_account: T::AccountId = ::PalletId::get().into_account_truncating(); - let pallet_origin: T::RuntimeOrigin = RawOrigin::Signed(pallet_account.clone()).into(); - - T::Currency::make_free_balance_be(&caller, u32::MAX.into()); - - // might fail if asset is already created in genesis config. Fail doesn't affect later mint - let _create_token_call = Assets::::create( - pallet_origin.clone(), - T::AssetId::from(22).into(), - T::Lookup::unlookup(pallet_account.clone()), - 10u32.into(), - ); - - let mint_token_call = Assets::::mint( - pallet_origin, - T::AssetId::from(22).into(), - T::Lookup::unlookup(caller.clone()), - INITIAL_BALANCE.into(), - ); - assert_ok!(mint_token_call); - - caller -} - -fn register_job(submit: bool) -> (T::AccountId, JobRegistrationFor) -where - T: pallet_assets::Config, - ::AssetId: From, - ::Balance: From, -{ - let caller: T::AccountId = token_22_funded_account::(); +fn register_job(submit: bool) -> (T::AccountId, JobRegistrationFor) { + let caller: T::AccountId = ::BenchmarkHelper::funded_account(0); whitelist_account!(caller); let job = job_registration::(::BenchmarkHelper::registration_extra()); @@ -144,9 +98,7 @@ where benchmarks! { where_clause { where - T: pallet_assets::Config + pallet_timestamp::Config, - ::AssetId: From, - ::Balance: From, + T: pallet_timestamp::Config, ::AccountId: From<[u8; 32]>, ::Moment: From, } diff --git a/pallets/acurast/src/mock.rs b/pallets/acurast/src/mock.rs index dad01bf7..44d32ba6 100644 --- a/pallets/acurast/src/mock.rs +++ b/pallets/acurast/src/mock.rs @@ -1,15 +1,17 @@ -use acurast_common::{JobModules, Schedule}; -use frame_support::{ - pallet_prelude::GenesisBuild, parameter_types, traits::AsEnsureOriginWithArg, - traits::Everything, PalletId, -}; +use frame_support::{pallet_prelude::GenesisBuild, parameter_types, traits::Everything, PalletId}; use hex_literal::hex; use sp_io; -use sp_runtime::traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, ConstU128, ConstU32}; +use sp_runtime::traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256}; use sp_runtime::{generic, AccountId32}; +use acurast_common::{JobModules, Schedule}; + +#[cfg(feature = "runtime-benchmarks")] +use crate::benchmarking::BenchmarkHelper; use crate::{AttestationChain, JobRegistration, RevocationListUpdateBarrier, Script, SerialNumber}; +pub const SEED: u32 = 1337; + type AccountId = AccountId32; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -77,7 +79,6 @@ frame_support::construct_runtime!( System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Assets: pallet_assets::{Pallet, Config, Event, Storage}, ParachainInfo: parachain_info::{Pallet, Storage, Config}, Acurast: crate::{Pallet, Call, Storage, Event} } @@ -147,29 +148,6 @@ impl pallet_balances::Config for Test { type ReserveIdentifier = [u8; 8]; } -impl pallet_assets::Config for Test { - type RuntimeEvent = RuntimeEvent; - type Balance = Balance; - type AssetId = parachains_common::AssetIdForTrustBackedAssets; - type AssetIdParameter = codec::Compact; - type Currency = Balances; - type CreateOrigin = AsEnsureOriginWithArg>; - type ForceOrigin = frame_system::EnsureRoot; - type AssetDeposit = ConstU128<0>; - type AssetAccountDeposit = ConstU128<0>; - type MetadataDepositBase = ConstU128<{ UNIT }>; - type MetadataDepositPerByte = ConstU128<{ 10 * MICROUNIT }>; - type ApprovalDeposit = ConstU128<{ 10 * MICROUNIT }>; - type StringLimit = ConstU32<50>; - type Freezer = (); - type Extra = (); - type WeightInfo = (); - type RemoveItemsLimit = (); - type CallbackHandle = (); - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); -} - impl parachain_info::Config for Test {} impl crate::Config for Test { @@ -187,6 +165,27 @@ impl crate::Config for Test { type BenchmarkHelper = (); } +#[cfg(feature = "runtime-benchmarks")] +impl BenchmarkHelper for () +where + T::RegistrationExtra: Default, + T::AccountId: Into, +{ + fn registration_extra() -> T::RegistrationExtra { + Default::default() + } + + fn funded_account(index: u32) -> T::AccountId { + let caller: T::AccountId = frame_benchmarking::account("token_account", index, SEED); + >::make_free_balance_be( + &caller.clone().into(), + u32::MAX.into(), + ); + + caller + } +} + pub fn events() -> Vec { let evt = System::events() .into_iter() @@ -328,10 +327,6 @@ pub fn processor_account_id() -> AccountId { hex!("b8bc25a2b4c0386b8892b43e435b71fe11fa50533935f027949caf04bcce4694").into() } -pub fn pallet_assets_account() -> ::AccountId { - ::PalletId::get().into_account_truncating() -} - pub fn alice_account_id() -> AccountId { [0; 32].into() } diff --git a/pallets/assets-manager/Cargo.toml b/pallets/assets-manager/Cargo.toml index 76162d6c..6716dc1b 100644 --- a/pallets/assets-manager/Cargo.toml +++ b/pallets/assets-manager/Cargo.toml @@ -21,7 +21,6 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features = # Benchmarks frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.41", optional = true, default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.41", optional = true, default-features = false } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.41", optional = true, default-features = false } pallet-balances = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true, branch = "polkadot-v0.9.41" } # Substrate @@ -33,6 +32,7 @@ scale-info = { version = "2.2.0", default-features = false, features = [ sp-arithmetic = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.41", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.41", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.41" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.41", default-features = false } pallet-assets = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.41" } # Polkadot @@ -44,7 +44,6 @@ acurast-common = { path = "../acurast/common", default-features = false } [dev-dependencies] sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.41", default-features = false } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.41", default-features = false } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.41" } [features] @@ -57,6 +56,7 @@ std = [ "frame-benchmarking/std", "sp-std/std", "sp-runtime/std", + "sp-core/std", "pallet-assets/std", "xcm-builder/std", "xcm-executor/std", @@ -67,7 +67,6 @@ std = [ runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "sp-io", - "sp-core", "pallet-balances/runtime-benchmarks", "pallet-assets/runtime-benchmarks", ] diff --git a/pallets/assets-manager/src/lib.rs b/pallets/assets-manager/src/lib.rs index 7dc5a29f..29212237 100644 --- a/pallets/assets-manager/src/lib.rs +++ b/pallets/assets-manager/src/lib.rs @@ -8,13 +8,13 @@ mod stub; #[cfg(test)] mod tests; +mod migration; + #[cfg(feature = "runtime-benchmarks")] pub mod benchmarking; pub mod weights; -pub mod traits; - use sp_runtime::traits::StaticLookup; pub use pallet::*; @@ -27,15 +27,17 @@ type AccountIdLookupOf = <::Lookup as StaticLookup #[frame_support::pallet] pub mod pallet { use super::*; - use crate::traits::AssetValidator; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; use xcm::latest::MultiLocation; use xcm::prelude::{Abstract, AssetId, Concrete, GeneralIndex, PalletInstance, Parachain, X3}; use xcm_executor::traits::Convert; + pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); + #[pallet::pallet] #[pallet::without_storage_info] + #[pallet::storage_version(STORAGE_VERSION)] pub struct Pallet(PhantomData<(T, I)>); #[pallet::config] @@ -115,6 +117,13 @@ pub mod pallet { InvalidAssetIndex, } + #[pallet::hooks] + impl, I: 'static> Hooks> for Pallet { + fn on_runtime_upgrade() -> Weight { + crate::migration::migrate_to_v2::() + } + } + #[pallet::call] impl, I: 'static> Pallet where @@ -240,15 +249,6 @@ pub mod pallet { } } - impl + pallet_assets::Config, I: 'static> AssetValidator for Pallet { - type Error = Error; - - fn validate(asset: &AssetId) -> Result<(), Self::Error> { - Self::reverse_asset_index(asset).ok_or(Error::::AssetNotIndexed)?; - Ok(()) - } - } - impl + pallet_assets::Config, I: 'static> Convert for Pallet { @@ -262,26 +262,4 @@ pub mod pallet { } } } - - impl + pallet_assets::Config, I: 'static> acurast_common::AssetTransfer - for Pallet - { - type AssetId = AssetId; - type AccountId = T::AccountId; - type Balance = T::Balance; - type Error = DispatchError; - - fn transfer( - asset: Self::AssetId, - source: &Self::AccountId, - dest: &Self::AccountId, - amount: Self::Balance, - ) -> Result<(), Self::Error> { - let id = - >::get(&asset).ok_or(Error::::AssetNotIndexed)?; - let _: Self::Balance = - as frame_support::traits::tokens::fungibles::Transfer>::transfer(id, source, dest, amount, true)?; - Ok(()) - } - } } diff --git a/pallets/assets-manager/src/migration.rs b/pallets/assets-manager/src/migration.rs new file mode 100644 index 00000000..ddc1cf59 --- /dev/null +++ b/pallets/assets-manager/src/migration.rs @@ -0,0 +1,18 @@ +use frame_support::{traits::GetStorageVersion, weights::Weight}; +use sp_core::Get; + +use super::*; + +pub fn migrate_to_v2, I: 'static>() -> Weight { + let onchain_version = Pallet::::on_chain_storage_version(); + if onchain_version < crate::STORAGE_VERSION { + let mut count = 0u32; + count += AssetIndex::::clear(100, None).loops; + count += ReverseAssetIndex::::clear(100, None).loops; + + STORAGE_VERSION.put::>(); + T::DbWeight::get().reads_writes((count + 1).into(), (count + 1).into()) + } else { + Weight::zero() + } +} diff --git a/pallets/assets-manager/src/traits.rs b/pallets/assets-manager/src/traits.rs deleted file mode 100644 index 97ef9e17..00000000 --- a/pallets/assets-manager/src/traits.rs +++ /dev/null @@ -1,15 +0,0 @@ -use sp_runtime::DispatchError; - -pub trait AssetValidator { - type Error: Into; - - fn validate(asset: &AssetId) -> Result<(), Self::Error>; -} - -impl AssetValidator for () { - type Error = DispatchError; - - fn validate(_: &AssetId) -> Result<(), Self::Error> { - Err(DispatchError::Other("")) - } -} diff --git a/pallets/hyperdrive/src/lib.rs b/pallets/hyperdrive/src/lib.rs index 023dbdac..4b8c3f5f 100644 --- a/pallets/hyperdrive/src/lib.rs +++ b/pallets/hyperdrive/src/lib.rs @@ -37,7 +37,6 @@ pub mod pallet { use sp_std::vec; use pallet_acurast_marketplace::types::RegistrationExtra; - use pallet_acurast_marketplace::Reward; use crate::weights::WeightInfo; @@ -88,12 +87,11 @@ pub mod pallet { + Zero + From + CheckedRem; - type Reward: Parameter + Member + Reward; type Balance: Member + Parameter + AtLeast32BitUnsigned - + From // required to translate Tezos Ints of unknown precision (Alternative: use Tezos SDK types in clients of this pallet) + + From + Default + Copy + MaybeSerializeDeserialize diff --git a/pallets/hyperdrive/src/mock.rs b/pallets/hyperdrive/src/mock.rs index bc159248..b1c54c47 100644 --- a/pallets/hyperdrive/src/mock.rs +++ b/pallets/hyperdrive/src/mock.rs @@ -19,7 +19,7 @@ use sp_runtime::{ }; use sp_std::prelude::*; -use pallet_acurast_marketplace::{RegistrationExtra, Reward}; +use pallet_acurast_marketplace::RegistrationExtra; use crate::tezos::TezosParser; use crate::types::RawAction; @@ -90,8 +90,7 @@ impl crate::Config for Test { type TargetChainOwner = TargetChainStateOwner; type TargetChainHash = H256; type TargetChainBlockNumber = u64; - type Reward = MockAsset; - type Balance = AssetAmount; + type Balance = Balance; type RegistrationExtra = RegistrationExtra::AccountId>; type TargetChainHashing = Keccak256; @@ -131,33 +130,7 @@ pub fn events() -> Vec { evt } -pub type AssetId = u32; -pub type AssetAmount = u128; - -#[derive(RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo, Clone, PartialEq, Eq)] -pub struct MockAsset { - pub id: AssetId, - pub amount: AssetAmount, -} - -impl Reward for MockAsset { - type AssetId = AssetId; - type AssetAmount = AssetAmount; - type Error = (); - - fn with_amount(&mut self, amount: Self::AssetAmount) -> Result<&Self, Self::Error> { - self.amount = amount; - Ok(self) - } - - fn try_get_asset_id(&self) -> Result { - Ok(self.id) - } - - fn try_get_amount(&self) -> Result { - Ok(self.amount) - } -} +pub type Balance = u128; impl ActionExecutor for () { fn execute(_: ParsedAction) -> DispatchResultWithPostInfo { diff --git a/pallets/hyperdrive/src/tezos.rs b/pallets/hyperdrive/src/tezos.rs index 88249ee4..ecd451fc 100644 --- a/pallets/hyperdrive/src/tezos.rs +++ b/pallets/hyperdrive/src/tezos.rs @@ -578,7 +578,7 @@ mod tests { JobIdSequence, JobRegistration< ::AccountId, - RegistrationExtra::AccountId>, + RegistrationExtra::AccountId>, >, ) = parse_job_registration_payload::< _, diff --git a/pallets/marketplace/src/benchmarking.rs b/pallets/marketplace/src/benchmarking.rs index 8cf6d0ec..beb3a5bb 100644 --- a/pallets/marketplace/src/benchmarking.rs +++ b/pallets/marketplace/src/benchmarking.rs @@ -1,13 +1,8 @@ -use frame_benchmarking::{account, benchmarks, whitelist_account}; -use frame_support::{ - assert_ok, - sp_runtime::traits::{AccountIdConversion, Get, StaticLookup}, - traits::Currency, -}; +use frame_benchmarking::{benchmarks, whitelist_account}; +use frame_support::assert_ok; use frame_system::RawOrigin; use sp_core::*; -use sp_runtime::BoundedVec; -use sp_runtime::{traits::ConstU32, DispatchError}; +use sp_runtime::DispatchError; use sp_std::prelude::*; pub use pallet::Config; @@ -24,6 +19,7 @@ use super::*; pub trait BenchmarkHelper { /// Extends the job requirements, defined by benchmarking code in this pallet, with the containing struct RegistrationExtra. fn registration_extra(r: JobRequirementsFor) -> ::RegistrationExtra; + fn funded_account(index: u32, amount: T::Balance) -> T::AccountId; } pub fn assert_last_event(generic_event: ::RuntimeEvent) { @@ -39,30 +35,18 @@ pub fn assert_last_acurast_event( pub fn advertisement( fee_per_millisecond: u128, storage_capacity: u32, -) -> AdvertisementFor -where - RewardFor: From, - ::AssetId: From, - ::AssetAmount: From, -{ - let mut pricing: BoundedVec< - PricingVariant<::AssetId, ::AssetAmount>, - ConstU32, - > = Default::default(); - let r = pricing.try_push(PricingVariant { - reward_asset: 0.into(), - fee_per_millisecond: fee_per_millisecond.into(), - fee_per_storage_byte: 5.into(), - base_fee_per_execution: 0.into(), - scheduling_window: SchedulingWindow::Delta(2_628_000_000), // 1 month - }); - assert!(r.is_ok(), "Expected Ok(_). Got {:#?}", r); +) -> AdvertisementFor { Advertisement { - pricing, + pricing: Pricing { + fee_per_millisecond: fee_per_millisecond.into(), + fee_per_storage_byte: 5u8.into(), + base_fee_per_execution: 0u8.into(), + scheduling_window: SchedulingWindow::End(1671886800000), + }, allowed_consumers: None, storage_capacity, max_memory: 80_000, - network_request_quota: 5, + network_request_quota: 50, available_modules: JobModules::default(), } } @@ -71,15 +55,14 @@ pub fn job_registration_with_reward( script: Script, duration: u64, reward_value: u128, -) -> JobRegistrationFor -where - RewardFor: From, -{ + instant_match_processor: Option>, +) -> JobRegistrationFor { + let reward: ::Balance = reward_value.into(); let r = JobRequirements { slots: 1, - reward: asset(reward_value).into(), + reward: reward.into(), min_reputation: Some(0), - instant_match: None, + instant_match: instant_match_processor.map(|m| vec![m]), }; let r: ::RegistrationExtra = ::BenchmarkHelper::registration_extra(r); let r: ::RegistrationExtra = r.into(); @@ -95,7 +78,7 @@ where max_start_delay: 5000, }, memory: 5_000u32, - network_requests: 5, + network_requests: 1, storage: 20_000u32, required_modules: JobModules::default(), extra: r, @@ -106,49 +89,11 @@ pub fn script() -> Script { SCRIPT_BYTES.to_vec().try_into().unwrap() } -fn token_22_funded_account(index: u32) -> T::AccountId -where - T: pallet_assets::Config, - ::AssetId: From, - ::Balance: From, -{ - use pallet_assets::Pallet as Assets; - let caller: T::AccountId = account("token_account", index, SEED); - whitelist_account!(caller); - let pallet_account: T::AccountId = ::PalletId::get().into_account_truncating(); - let pallet_origin: T::RuntimeOrigin = RawOrigin::Signed(pallet_account.clone()).into(); - - T::Currency::make_free_balance_be(&caller, u32::MAX.into()); - - // might fail if asset is already created in genesis config. Fail doesn't affect later mint - let _create_token_call = Assets::::create( - pallet_origin.clone(), - ::AssetId::from(22).into(), - T::Lookup::unlookup(pallet_account.clone()), - 10u32.into(), - ); - - let mint_token_call = Assets::::mint( - pallet_origin, - ::AssetId::from(22).into(), - T::Lookup::unlookup(caller.clone()), - INITIAL_BALANCE.into(), - ); - assert_ok!(mint_token_call); - - caller -} - fn advertise_helper(submit: bool) -> (T::AccountId, AdvertisementFor) where - T: pallet_assets::Config, - ::AssetId: From, - ::AssetAmount: From, - ::AssetId: From, - ::Balance: From, - RewardFor: From, + T: pallet_balances::Config, { - let caller: T::AccountId = token_22_funded_account::(0); + let caller: T::AccountId = ::BenchmarkHelper::funded_account(0, u32::MAX.into()); whitelist_account!(caller); let ad = advertisement::(10000, 5); @@ -166,17 +111,12 @@ where fn register_helper(submit: bool) -> (T::AccountId, JobRegistrationFor) where - T: pallet_assets::Config, - ::AssetId: From, - ::AssetAmount: From, - ::AssetId: From, - ::Balance: From, - RewardFor: From, + T: pallet_balances::Config, { - let caller: T::AccountId = token_22_funded_account::(0); + let caller: T::AccountId = ::BenchmarkHelper::funded_account(0, u32::MAX.into()); whitelist_account!(caller); - let job = job_registration_with_reward::(script(), 2, 20100); + let job = job_registration_with_reward::(script(), 2, 20100, None); if submit { let register_call = @@ -190,20 +130,25 @@ where fn acknowledge_match_helper( ) -> Result<(T::AccountId, JobId), DispatchError> where - T: pallet_assets::Config, - ::AssetId: From, - ::AssetId: From, - ::Balance: From, - RewardFor: From, + T: pallet_balances::Config, { - let consumer: T::AccountId = token_22_funded_account::(0); - let processor: T::AccountId = token_22_funded_account::(1); - let ad = advertisement::(1, 1000); + let consumer: T::AccountId = ::BenchmarkHelper::funded_account(0, u32::MAX.into()); + let processor: T::AccountId = + ::BenchmarkHelper::funded_account(1, u32::MAX.into()); + let ad = advertisement::(1, 1_000_000); assert_ok!(AcurastMarketplace::::advertise( RawOrigin::Signed(processor.clone()).into(), ad.clone(), )); - let job = job_registration_with_reward::(script(), 100, 1000); + let job = job_registration_with_reward::( + script(), + 100, + 1_000_000, + Some(PlannedExecution { + source: processor.clone(), + start_delay: 0, + }), + ); assert_ok!(Acurast::::register( RawOrigin::Signed(consumer.clone()).into(), job.clone() @@ -220,12 +165,7 @@ where benchmarks! { where_clause { where - T: pallet_assets::Config + pallet_acurast::Config, - RewardFor: From, - ::AssetId: From, - ::AssetAmount: From, - ::AssetId: From, - ::Balance: From, + T: pallet_acurast::Config + pallet_balances::Config , } advertise { diff --git a/pallets/marketplace/src/functions.rs b/pallets/marketplace/src/functions.rs index c388fa59..e8d31622 100644 --- a/pallets/marketplace/src/functions.rs +++ b/pallets/marketplace/src/functions.rs @@ -1,5 +1,4 @@ use frame_support::{ensure, pallet_prelude::DispatchResult}; -use pallet_acurast_assets_manager::traits::AssetValidator; use reputation::BetaParameters; use sp_core::Get; @@ -56,16 +55,12 @@ impl Pallet { }, ); // update separate pricing index - for pricing in &advertisement.pricing { - T::AssetValidator::validate(&pricing.reward_asset).map_err(|e| e.into())?; - >::insert(processor, &pricing.reward_asset, pricing); - - >::mutate(processor, &pricing.reward_asset, |r| { - if r.is_none() { - *r = Some(BetaParameters::default()); - } - }); - } + >::insert(processor, advertisement.pricing.clone()); + >::mutate(processor, |r| { + if r.is_none() { + *r = Some(BetaParameters::default()); + } + }); Ok(().into()) } diff --git a/pallets/marketplace/src/lib.rs b/pallets/marketplace/src/lib.rs index ca6fedd9..b64f8776 100644 --- a/pallets/marketplace/src/lib.rs +++ b/pallets/marketplace/src/lib.rs @@ -45,15 +45,15 @@ pub mod pallet { use sp_runtime::{FixedU128, Permill, SaturatedConversion}; use sp_std::iter::once; use sp_std::prelude::*; + use xcm::v3::AssetId; use pallet_acurast::utils::ensure_source_verified; use pallet_acurast::{ AllowedSourcesUpdate, JobHooks, JobId, JobIdSequence, JobRegistrationFor, MultiOrigin, Schedule, StoredJobRegistration, }; - use pallet_acurast_assets_manager::traits::AssetValidator; - use crate::payments::{Reward, RewardFor}; + use crate::payments::RewardFor; use crate::traits::*; use crate::types::*; use crate::utils::*; @@ -82,8 +82,7 @@ pub mod pallet { /// would be considered outide of the agreed schedule despite being within schedule. #[pallet::constant] type ReportTolerance: Get; - type AssetId: Parameter + IsType< as Reward>::AssetId>; - type AssetAmount: Parameter + type Balance: Parameter + CheckedAdd + CheckedSub + CheckedMul @@ -96,12 +95,11 @@ pub mod pallet { + Default + Ord + Clone - + IsType< as Reward>::AssetAmount>; + + IsType>; type ManagerProvider: ManagerProvider; type ProcessorLastSeenProvider: ProcessorLastSeenProvider; /// Logic for locking and paying tokens for job execution type RewardManager: RewardManager; - type AssetValidator: AssetValidator; /// Hook to act on marketplace related state transitions. type MarketplaceHooks: MarketplaceHooks; type WeightInfo: WeightInfo; @@ -110,7 +108,7 @@ pub mod pallet { type BenchmarkHelper: crate::benchmarking::BenchmarkHelper; } - pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); + pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(3); #[pallet::pallet] #[pallet::without_storage_info] @@ -136,40 +134,43 @@ pub mod pallet { pub type StoredAdvertisementRestriction = StorageMap<_, Blake2_128, T::AccountId, AdvertisementRestriction>; - /// The storage for advertisements' pricing variants. They are stored as a map [`AccountId`] `(source)` -> [`AssetId`] -> [`PricingVariant`] since only one + /// The storage for advertisements' pricings. They are stored as a map [`AccountId`] `(source)` -> [`Pricing`] since only one /// advertisement per client, and at most one pricing for each distinct `AssetID` is allowed. #[pallet::storage] #[pallet::getter(fn stored_advertisement_pricing)] pub type StoredAdvertisementPricing = - StorageDoubleMap<_, Blake2_128, T::AccountId, Blake2_128, T::AssetId, PricingVariantFor>; + StorageMap<_, Blake2_128, T::AccountId, PricingFor>; /// The storage for remaining capacity for each source. Can be negative if capacity is reduced beyond the number of jobs currently assigned. #[pallet::storage] #[pallet::getter(fn stored_storage_capacity)] pub type StoredStorageCapacity = StorageMap<_, Blake2_128, T::AccountId, i64>; - /// Reputation as a map [`AccountId`] `(source)` -> [`AssetId`] -> [`BetaParameters`]. + /// Reputation as a map [`AccountId`] `(source)` -> [`BetaParameters`]. #[pallet::storage] #[pallet::getter(fn stored_reputation)] - pub type StoredReputation = StorageDoubleMap< - _, - Blake2_128Concat, - T::AccountId, - Blake2_128Concat, - T::AssetId, - BetaParameters, - >; + pub type StoredReputation = + StorageMap<_, Blake2_128Concat, T::AccountId, BetaParameters>; + + /// Deprecated: Number of total jobs assigned as a map [`AssetId`] -> `Balance` + #[pallet::storage] + #[deprecated(since = "V2", note = "please use `StoredTotalAssignedV3` instead")] + pub type StoredTotalAssignedV2 = StorageMap<_, Blake2_128Concat, AssetId, u128>; - /// Number of total jobs assigned as a map [`AssetId`] -> `AssetAmount` + /// Deprecated: Number of total jobs assigned. #[pallet::storage] #[pallet::getter(fn total_assigned)] - pub type StoredTotalAssigned = - StorageMap<_, Blake2_128Concat, ::AssetId, u128>; + pub type StoredTotalAssignedV3 = StorageValue<_, u128>; - /// Average job reward as a map [`AssetId`] -> `AssetAmount` + /// Deprecated: Average job reward as a map [`AssetId`] -> `Balance` + #[deprecated(since = "V2", note = "please use `StoredAverageRewardV3` instead")] + #[pallet::storage] + pub type StoredAverageRewardV2 = StorageMap<_, Blake2_128Concat, AssetId, u128>; + + /// Average job reward. #[pallet::storage] #[pallet::getter(fn average_reward)] - pub type StoredAverageReward = StorageMap<_, Blake2_128Concat, ::AssetId, u128>; + pub type StoredAverageRewardV3 = StorageValue<_, u128>; /// Job matches as a map [`AccountId`] `(source)` -> [`JobId`] -> `SlotId` #[pallet::storage] @@ -211,12 +212,8 @@ pub mod pallet { #[pallet::error] pub enum Error { - /// The job registration's reward type is not supported. - JobRegistrationUnsupportedReward, /// Generic overflow during a calculating with checked operatios. CalculationOverflow, - /// The reward could not be converted to different amount. - RewardConversionFailed, /// The job registration must specify non-zero `duration`. JobRegistrationZeroDuration, /// The job registration must specify a schedule that contains a maximum of [MAX_EXECUTIONS_PER_JOB] executions. @@ -243,8 +240,6 @@ pub mod pallet { AdvertisementNotFound, /// Advertisement not found when attempt to delete it. AdvertisementPricingNotFound, - /// Fulfill was executed for a not registered job. - EmptyPricing, /// The allowed consumers list for a registration exeeded the max length. TooManyAllowedConsumers, /// The allowed consumers list for a registration cannot be empty if provided. @@ -257,14 +252,8 @@ pub mod pallet { FailedToPay, /// Asset is not allowed by `AssetBarrier`. AssetNotAllowedByBarrier, - /// Invalid asset ID. - InvalidAssetId, - /// Invalid asset amount. - InvalidAssetAmount, /// Capacity not known for a source. SEVERE error CapacityNotFound, - /// Matching is empty. - EmptyMatching, /// Match is invalid due to the start time already passed. OverdueMatch, /// Match is invalid due to incorrect source count. @@ -273,8 +262,6 @@ pub mod pallet { DuplicateSourceInMatch, /// Match is invalid due to an unverfied source while `allow_only_verified_sources` is true. UnverifiedSourceInMatch, - /// Multiple different reward assets are currently not supported in a single matching. - MultipleRewardAssetsInMatch, /// Match is invalid due to a source's maximum memory exceeded. SchedulingWindowExceededInMatch, /// Match is invalid due to a source's maximum memory exceeded. @@ -325,7 +312,6 @@ pub mod pallet { Error::IncorrectSourceCountInMatch => true, Error::DuplicateSourceInMatch => true, Error::UnverifiedSourceInMatch => true, - Error::MultipleRewardAssetsInMatch => true, Error::SchedulingWindowExceededInMatch => true, Error::MaxMemoryExceededInMatch => true, Error::NetworkRequestQuotaExceededInMatch => true, @@ -352,7 +338,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { fn on_runtime_upgrade() -> frame_support::weights::Weight { - crate::migration::migrate_to_v2::() + crate::migration::migrate_to_v2::() + crate::migration::migrate_to_v3::() } } @@ -370,7 +356,6 @@ pub mod pallet { advertisement: AdvertisementFor, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; - ensure!((&advertisement).pricing.len() > 0, Error::::EmptyPricing); Self::do_advertise(&who, &advertisement)?; @@ -393,7 +378,7 @@ pub mod pallet { Error::::CannotDeleteAdvertisementWhileMatched ); - let _ = >::clear_prefix(&who, MAX_PRICING_VARIANTS, None); + let _ = >::remove(&who); >::remove(&who); >::remove(&who); @@ -414,7 +399,7 @@ pub mod pallet { // pay part of accumulated remaining reward (unspent to consumer) to matcher // pay only after all other steps succeeded without errors because paying reward is not revertable - T::RewardManager::pay_matcher_reward(&remaining_reward, &who)?; + T::RewardManager::pay_matcher_reward(remaining_reward, &who)?; Ok(().into()) } @@ -540,7 +525,7 @@ pub mod pallet { match T::ManagerProvider::manager_of(&who) { Ok(manager) => { - T::RewardManager::pay_reward(&assignment.fee_per_execution, &manager)?; + T::RewardManager::pay_reward(assignment.fee_per_execution.clone(), &manager)?; match execution_result { ExecutionResult::Success(operation_hash) => Self::deposit_event( @@ -589,26 +574,11 @@ pub mod pallet { let extra: ::RegistrationExtra = registration.extra.clone().into(); let requirements: JobRequirementsFor = extra.into(); - // parse reward into asset_id and amount - let reward_asset: ::AssetId = requirements - .reward - .try_get_asset_id() - .map_err(|_| Error::::JobRegistrationUnsupportedReward)? - .into(); - - T::AssetValidator::validate(&reward_asset).map_err(|e| e.into())?; - - let reward_amount: ::AssetAmount = requirements - .reward - .try_get_amount() - .map_err(|_| Error::::JobRegistrationUnsupportedReward)? - .into(); - // skip reputation update if reward is 0 + let reward_amount: ::Balance = requirements.reward.into(); if reward_amount > 0u8.into() { - let average_reward = >::get(&reward_asset).unwrap_or(0); - let total_assigned = - >::get(&reward_asset).unwrap_or_default(); + let average_reward = >::get().unwrap_or(0); + let total_assigned = >::get().unwrap_or_default(); let total_reward = average_reward .checked_mul(total_assigned - 1u128) @@ -618,14 +588,14 @@ pub mod pallet { .checked_add(reward_amount.clone().into()) .ok_or(Error::::CalculationOverflow)?; - let mut beta_params = >::get(&who, &reward_asset) - .ok_or(Error::::ReputationNotFound)?; + let mut beta_params = + >::get(&who).ok_or(Error::::ReputationNotFound)?; beta_params = BetaReputation::update( beta_params, assignment.sla.met, assignment.sla.total - assignment.sla.met, - reward_amount.clone().into(), + reward_amount.into(), average_reward, ) .ok_or(Error::::CalculationOverflow)?; @@ -634,10 +604,9 @@ pub mod pallet { .checked_div(total_assigned) .ok_or(Error::::CalculationOverflow)?; - >::insert(reward_asset.clone(), new_average_reward); + >::set(Some(new_average_reward)); >::insert( &who, - &reward_asset, BetaParameters { r: beta_params.r, s: beta_params.s, @@ -729,11 +698,10 @@ pub mod pallet { // lock only after all other steps succeeded without errors because locking reward is not revertable if let MultiOrigin::Acurast(who) = who { // reward is understood per slot and execution - let mut reward = requirements.reward; - reward - .with_amount(Self::total_reward_amount(registration)?.into()) - .map_err(|_| Error::::RewardConversionFailed)?; - T::RewardManager::lock_reward(&reward, &who)?; + T::RewardManager::lock_reward( + Self::total_reward_amount(registration)?.into(), + &who, + )?; } Ok(().into()) @@ -782,12 +750,11 @@ pub mod pallet { } impl Pallet { - /// Checks if a Processor - Job match is possible and returns the job reward. + /// Checks if a Processor - Job match is possible and returns the remaining job reward. fn process_matching<'a>( matching: impl IntoIterator>, ) -> Result, DispatchError> { - // Currently we require all matches to be rewarded with the same asset - let mut remaining_reward: Option<(RewardFor, T::AssetAmount)> = None; + let mut remaining_reward: T::Balance = 0u8.into(); for m in matching { let registration = >::get(&m.job_id.0, &m.job_id.1) @@ -807,22 +774,10 @@ pub mod pallet { Error::::IncorrectSourceCountInMatch ); - // parse reward into asset_id and amount - let reward_asset: ::AssetId = requirements - .reward - .try_get_asset_id() - .map_err(|_| Error::::JobRegistrationUnsupportedReward)? - .into(); - T::AssetValidator::validate(&reward_asset).map_err(|e| e.into())?; - - let reward_amount: ::AssetAmount = requirements - .reward - .try_get_amount() - .map_err(|_| Error::::JobRegistrationUnsupportedReward)? - .into(); + let reward_amount: ::Balance = requirements.reward.into(); // keep track of total fee in assignments to check later if it exceeds reward - let mut total_fee: ::AssetAmount = 0u8.into(); + let mut total_fee: ::Balance = 0u8.into(); // `slot` is used for detecting duplicate source proposed for distinct slots // TODO: add global (configurable) maximum of jobs assigned. This would limit the weight of `propose_matching` to a constant, since it depends on the number of active matches. @@ -844,11 +799,8 @@ pub mod pallet { ); } - let pricing = >::get( - &planned_execution.source, - &reward_asset, - ) - .ok_or(Error::::AdvertisementPricingNotFound)?; + let pricing = >::get(&planned_execution.source) + .ok_or(Error::::AdvertisementPricingNotFound)?; // CHECK the scheduling_window allow to schedule this job Self::check_scheduling_window( @@ -898,7 +850,6 @@ pub mod pallet { Self::check_min_reputation( requirements.min_reputation, &planned_execution.source, - &reward_asset, )?; // CHECK schedule @@ -930,9 +881,6 @@ pub mod pallet { .ok_or(Error::::CalculationOverflow)?, ) .ok_or(Error::::CalculationOverflow)?; - let mut fee = requirements.reward.clone(); - fee.with_amount(fee_per_execution.into()) - .map_err(|_| Error::::RewardConversionFailed)?; // ASSIGN if not yet assigned (equals to CHECK that no duplicate source in a single mutate operation) >::try_mutate( @@ -946,7 +894,7 @@ pub mod pallet { *s = Some(Assignment { slot: slot as u8, start_delay: planned_execution.start_delay, - fee_per_execution: fee, + fee_per_execution: fee_per_execution.into(), acknowledged: false, sla: SLA { total: execution_count, @@ -979,36 +927,18 @@ pub mod pallet { // because we cannot assume that asset amount is an unsigned integer for all future ensure!(diff >= 0u32.into(), Error::::InsufficientRewardInMatch); - if let Some(a) = remaining_reward.as_mut() { - ensure!( - a.0 == requirements.reward, - Error::::MultipleRewardAssetsInMatch - ); - - a.1 = - a.1.checked_add(&diff) - .ok_or(Error::::CalculationOverflow)?; - } else { - remaining_reward = Some((requirements.reward, diff)); - } + remaining_reward = remaining_reward + .checked_add(&diff) + .ok_or(Error::::CalculationOverflow)?; - >::mutate(&reward_asset, |t| { + >::mutate(|t| { *t = Some(t.unwrap_or(0u128).saturating_add(1)); }); >::insert(&m.job_id.0, &m.job_id.1, JobStatus::Matched); Self::deposit_event(Event::JobRegistrationMatched(m.clone())); } - // If we arrive here with remaining_reward None, then matching was empty - if let Some(reward) = remaining_reward.as_mut() { - reward - .0 - .with_amount(reward.1.clone().into()) - .map_err(|_| Error::::RewardConversionFailed)?; - return Ok(reward.0.to_owned()); - } else { - return Err(Error::::EmptyMatching.into()); - } + return Ok(remaining_reward.into()); } fn check_scheduling_window( @@ -1071,11 +1001,10 @@ pub mod pallet { fn check_min_reputation( min_reputation: Option, source: &T::AccountId, - reward_asset: &::AssetId, ) -> Result<(), Error> { if let Some(min_reputation) = min_reputation { - let beta_params = >::get(source, reward_asset) - .ok_or(Error::::ReputationNotFound)?; + let beta_params = + >::get(source).ok_or(Error::::ReputationNotFound)?; let reputation = BetaReputation::::normalize(beta_params) .ok_or(Error::::CalculationOverflow)?; @@ -1129,20 +1058,6 @@ pub mod pallet { source: &T::AccountId, consumer: Option<&MultiOrigin>, ) -> Result<(), Error> { - // parse reward into asset_id and amount - let reward_asset: ::AssetId = registration - .reward - .try_get_asset_id() - .map_err(|_| Error::::JobRegistrationUnsupportedReward)? - .into(); - T::AssetValidator::validate(&reward_asset).map_err(|_| Error::::InvalidAssetId)?; - - let reward_amount: ::AssetAmount = registration - .reward - .try_get_amount() - .map_err(|_| Error::::JobRegistrationUnsupportedReward)? - .into(); - // CHECK attestation ensure!( !registration.allow_only_verified_sources @@ -1160,7 +1075,7 @@ pub mod pallet { ); } - let pricing = >::get(&source, &reward_asset) + let pricing = >::get(&source) .ok_or(Error::::AdvertisementPricingNotFound)?; if let Some(schedule) = ®istration.schedule { @@ -1185,7 +1100,7 @@ pub mod pallet { // CHECK price not exceeding reward ensure!( - fee_per_execution <= reward_amount, + fee_per_execution <= registration.reward.clone().into(), Error::::InsufficientRewardInMatch ); } @@ -1224,7 +1139,7 @@ pub mod pallet { } // CHECK reputation sufficient - Self::check_min_reputation(registration.min_reputation, &source, &reward_asset)?; + Self::check_min_reputation(registration.min_reputation, &source)?; Ok(()) } @@ -1288,16 +1203,11 @@ pub mod pallet { /// Calculates the total reward amount. fn total_reward_amount( registration: &JobRegistrationFor, - ) -> Result> { + ) -> Result> { let e: ::RegistrationExtra = registration.extra.clone().into(); let requirements: JobRequirementsFor = e.into(); - let reward_amount: T::AssetAmount = requirements - .reward - .try_get_amount() - .map_err(|_| Error::::JobRegistrationUnsupportedReward)? - .into(); - + let reward_amount: ::Balance = requirements.reward.into(); Ok(reward_amount .checked_mul(&((requirements.slots as u128).into())) .ok_or(Error::::CalculationOverflow)? @@ -1309,8 +1219,8 @@ pub mod pallet { fn fee_per_execution( schedule: &Schedule, storage: u32, - pricing: &PricingVariantFor, - ) -> Result> { + pricing: &PricingFor, + ) -> Result> { Ok(pricing .fee_per_millisecond .checked_mul(&schedule.duration.into()) @@ -1339,7 +1249,7 @@ pub mod pallet { sp_api::decl_runtime_apis! { /// API to interact with Acurast marketplace pallet. - pub trait MarketplaceRuntimeApi { + pub trait MarketplaceRuntimeApi { fn filter_matching_sources( registration: PartialJobRegistration, sources: Vec, diff --git a/pallets/marketplace/src/migration.rs b/pallets/marketplace/src/migration.rs index 143962f5..6ab4759d 100644 --- a/pallets/marketplace/src/migration.rs +++ b/pallets/marketplace/src/migration.rs @@ -1,3 +1,5 @@ +#![allow(deprecated)] + use frame_support::{traits::GetStorageVersion, weights::Weight}; use pallet_acurast::JobModules; use sp_core::Get; @@ -45,3 +47,24 @@ pub fn migrate_to_v2() -> Weight { Weight::zero() } } + +pub fn migrate_to_v3() -> Weight { + let onchain_version = Pallet::::on_chain_storage_version(); + if onchain_version < crate::STORAGE_VERSION { + let mut count = 0u32; + count += StoredJobStatus::::clear(10_000, None).loops; + count += StoredAdvertisementRestriction::::clear(10_000, None).loops; + count += StoredAdvertisementPricing::::clear(10_000, None).loops; + count += StoredStorageCapacity::::clear(10_000, None).loops; + count += StoredReputation::::clear(10_000, None).loops; + count += StoredTotalAssignedV2::::clear(10_000, None).loops; + count += StoredAverageRewardV2::::clear(10_000, None).loops; + count += StoredMatches::::clear(10_000, None).loops; + count += StoredMatchesReverseIndex::::clear(10_000, None).loops; + + STORAGE_VERSION.put::>(); + T::DbWeight::get().reads_writes((count + 1).into(), (count + 1).into()) + } else { + Weight::zero() + } +} diff --git a/pallets/marketplace/src/mock.rs b/pallets/marketplace/src/mock.rs index f260bd4e..26cb8461 100644 --- a/pallets/marketplace/src/mock.rs +++ b/pallets/marketplace/src/mock.rs @@ -1,13 +1,8 @@ -use frame_support::{ - pallet_prelude::GenesisBuild, - parameter_types, - traits::{AsEnsureOriginWithArg, Everything}, - PalletId, -}; +use frame_support::{pallet_prelude::GenesisBuild, parameter_types, traits::Everything, PalletId}; use sp_core::*; use sp_io; -use sp_runtime::traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, ConstU128, ConstU32}; -use sp_runtime::{bounded_vec, BoundedVec, DispatchError}; +use sp_runtime::traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256}; +use sp_runtime::DispatchError; use sp_runtime::{generic, Percent}; use sp_std::prelude::*; @@ -67,7 +62,6 @@ impl ExtBuilder { pallet_balances::GenesisConfig:: { balances: vec![ (alice_account_id(), INITIAL_BALANCE), - (pallet_assets_account(), INITIAL_BALANCE), (pallet_fees_account(), INITIAL_BALANCE), (bob_account_id(), INITIAL_BALANCE), (processor_account_id(), INITIAL_BALANCE), @@ -76,19 +70,6 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); - // give alice an initial balance of token 22 (backed by statemint) to pay for a job - // get the MockAsset representing token 22 with owned_asset() - pallet_assets::GenesisConfig:: { - assets: vec![(22, pallet_assets_account(), false, 1_000)], - metadata: vec![(22, "test_payment".into(), "tpt".into(), 12.into())], - accounts: vec![ - (22, alice_account_id(), INITIAL_BALANCE), - (22, bob_account_id(), INITIAL_BALANCE), - ], - } - .assimilate_storage(&mut t) - .unwrap(); - let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext @@ -110,7 +91,6 @@ frame_support::construct_runtime!( System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Assets: pallet_assets::{Pallet, Config, Event, Storage}, ParachainInfo: parachain_info::{Pallet, Storage, Config}, Acurast: pallet_acurast::{Pallet, Call, Storage, Event}, AcurastMarketplace: crate::{Pallet, Call, Storage, Event}, @@ -124,7 +104,7 @@ parameter_types! { parameter_types! { pub const MinimumPeriod: u64 = 2000; pub AllowedRevocationListUpdate: Vec = vec![alice_account_id(), ::PalletId::get().into_account_truncating()]; - pub const ExistentialDeposit: AssetAmount = EXISTENTIAL_DEPOSIT; + pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT; } parameter_types! { pub const MaxReserves: u32 = 50; @@ -147,7 +127,7 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; + type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); type DbWeight = (); @@ -169,7 +149,7 @@ impl pallet_timestamp::Config for Test { impl pallet_balances::Config for Test { /// The type for recording an account's balance. - type Balance = AssetAmount; + type Balance = Balance; type DustRemoval = (); /// The ubiquitous event type. type RuntimeEvent = RuntimeEvent; @@ -181,29 +161,6 @@ impl pallet_balances::Config for Test { type ReserveIdentifier = [u8; 8]; } -impl pallet_assets::Config for Test { - type RuntimeEvent = RuntimeEvent; - type Balance = AssetAmount; - type AssetId = AssetId; - type AssetIdParameter = codec::Compact; - type Currency = Balances; - type CreateOrigin = AsEnsureOriginWithArg>; - type ForceOrigin = frame_system::EnsureRoot; - type AssetDeposit = ConstU128<0>; - type AssetAccountDeposit = ConstU128<0>; - type MetadataDepositBase = ConstU128<{ UNIT }>; - type MetadataDepositPerByte = ConstU128<{ 10 * MICROUNIT }>; - type ApprovalDeposit = ConstU128<{ 10 * MICROUNIT }>; - type StringLimit = ConstU32<50>; - type Freezer = (); - type Extra = (); - type WeightInfo = (); - type RemoveItemsLimit = (); - type CallbackHandle = (); - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); -} - impl parachain_info::Config for Test {} impl pallet_acurast::Config for Test { @@ -228,11 +185,21 @@ impl pallet_acurast::benchmarking::BenchmarkHelper for TestBenchmarkHelper fn registration_extra() -> ::RegistrationExtra { JobRequirements { slots: 1, - reward: asset(1), + reward: 1, min_reputation: None, instant_match: None, } } + + fn funded_account(index: u32) -> AccountId { + let caller: AccountId = frame_benchmarking::account("token_account", index, SEED); + >::make_free_balance_be( + &caller, + u32::MAX.into(), + ); + + caller + } } impl mock_pallet::Config for Test { @@ -243,7 +210,7 @@ impl mock_pallet::Config for Test { pub mod mock_pallet { use frame_support::pallet_prelude::*; - use crate::stub::MockAsset; + use crate::stub::Balance; #[pallet::config] pub trait Config: frame_system::Config + crate::Config { @@ -256,19 +223,19 @@ pub mod mock_pallet { #[pallet::event] #[pallet::generate_deposit(pub (super) fn deposit_event)] pub enum Event { - Locked(MockAsset), - PayReward(MockAsset), - PayMatcherReward(MockAsset), + Locked(Balance), + PayReward(Balance), + PayMatcherReward(Balance), } } pub struct MockRewardManager {} impl RewardManager for MockRewardManager { - type Reward = MockAsset; + type Reward = Balance; fn lock_reward( - reward: &Self::Reward, + reward: Self::Reward, _owner: &::AccountId, ) -> Result<(), DispatchError> { mock_pallet::Pallet::deposit_event(mock_pallet::Event::::Locked(reward.clone())); @@ -276,7 +243,7 @@ impl RewardManager for MockRewardManager { } fn pay_reward( - reward: &Self::Reward, + reward: Self::Reward, _target: &::AccountId, ) -> Result<(), DispatchError> { mock_pallet::Pallet::deposit_event(mock_pallet::Event::::PayReward(reward.clone())); @@ -284,7 +251,7 @@ impl RewardManager for MockRewardManager { } fn pay_matcher_reward( - reward: &Self::Reward, + reward: Self::Reward, _matcher: &::AccountId, ) -> Result<(), DispatchError> { mock_pallet::Pallet::deposit_event(mock_pallet::Event::::PayMatcherReward( @@ -319,11 +286,9 @@ impl Config for Test { type RegistrationExtra = JobRequirementsFor; type PalletId = AcurastPalletId; type ReportTolerance = ReportTolerance; - type AssetId = AssetId; - type AssetAmount = AssetAmount; + type Balance = Balance; type ManagerProvider = ManagerOf; type RewardManager = MockRewardManager; - type AssetValidator = PassAllAssets; type ProcessorLastSeenProvider = ProcessorLastSeenProvider; type MarketplaceHooks = (); type WeightInfo = weights::Weights; @@ -336,6 +301,13 @@ impl crate::benchmarking::BenchmarkHelper for TestBenchmarkHelper { fn registration_extra(r: JobRequirementsFor) -> ::RegistrationExtra { r } + + fn funded_account(index: u32, amount: Balance) -> AccountId { + let caller: AccountId = frame_benchmarking::account("token_account", index, SEED); + >::make_free_balance_be(&caller, amount); + + caller + } } pub fn events() -> Vec { @@ -349,10 +321,6 @@ pub fn events() -> Vec { evt } -pub fn pallet_assets_account() -> ::AccountId { - ::PalletId::get().into_account_truncating() -} - pub fn pallet_fees_account() -> ::AccountId { FeeManagerImpl::pallet_id().into_account_truncating() } @@ -364,16 +332,13 @@ pub fn advertisement( max_memory: u32, network_request_quota: u8, ) -> AdvertisementFor { - let pricing: BoundedVec, ConstU32> = - bounded_vec![PricingVariant { - reward_asset: 0, + Advertisement { + pricing: Pricing { fee_per_millisecond, fee_per_storage_byte, base_fee_per_execution: 0, scheduling_window: SchedulingWindow::Delta(2_628_000_000), // 1 month - }]; - Advertisement { - pricing, + }, allowed_consumers: None, storage_capacity, max_memory, diff --git a/pallets/marketplace/src/payments.rs b/pallets/marketplace/src/payments.rs index 12629e50..7a9d89a4 100644 --- a/pallets/marketplace/src/payments.rs +++ b/pallets/marketplace/src/payments.rs @@ -1,75 +1,43 @@ -use crate::{Config, Error}; +use crate::Config; use core::marker::PhantomData; +use frame_support::traits::tokens::Balance; use frame_support::{ pallet_prelude::Member, sp_runtime::{ traits::{AccountIdConversion, Get}, DispatchError, Percent, }, - Never, PalletId, Parameter, + PalletId, Parameter, }; -use pallet_acurast_assets_manager::traits::AssetValidator; use xcm::prelude::AssetId; pub type RewardFor = <::RewardManager as RewardManager>::Reward; -/// Trait representing the reward for the execution of a job. -pub trait Reward { - type AssetId; - type AssetAmount; - type Error; - - /// Creates new reward with given amount. - fn with_amount(&mut self, amount: Self::AssetAmount) -> Result<&Self, Self::Error>; - /// Returns the reward asset id. - fn try_get_asset_id(&self) -> Result; - /// Returns the reward amount. - fn try_get_amount(&self) -> Result; -} - -impl Reward for () { - type AssetId = Never; - type AssetAmount = Never; - type Error = (); - - fn with_amount(&mut self, _amount: Self::AssetAmount) -> Result<&Self, Self::Error> { - Err(()) - } - - fn try_get_asset_id(&self) -> Result { - Err(()) - } - - fn try_get_amount(&self) -> Result { - Err(()) - } -} - /// Trait used to manage lock up and payments of rewards. pub trait RewardManager { - type Reward: Parameter + Member + Reward; + type Reward: Parameter; - fn lock_reward(reward: &Self::Reward, owner: &T::AccountId) -> Result<(), DispatchError>; - fn pay_reward(reward: &Self::Reward, target: &T::AccountId) -> Result<(), DispatchError>; + fn lock_reward(reward: Self::Reward, owner: &T::AccountId) -> Result<(), DispatchError>; + fn pay_reward(reward: Self::Reward, target: &T::AccountId) -> Result<(), DispatchError>; fn pay_matcher_reward( - reward: &Self::Reward, + reward: Self::Reward, matcher: &T::AccountId, ) -> Result<(), DispatchError>; } impl RewardManager for () { - type Reward = (); + type Reward = u128; - fn lock_reward(_reward: &Self::Reward, _owner: &T::AccountId) -> Result<(), DispatchError> { + fn lock_reward(_reward: Self::Reward, _owner: &T::AccountId) -> Result<(), DispatchError> { Ok(()) } - fn pay_reward(_reward: &Self::Reward, _target: &T::AccountId) -> Result<(), DispatchError> { + fn pay_reward(_reward: Self::Reward, _target: &T::AccountId) -> Result<(), DispatchError> { Ok(()) } fn pay_matcher_reward( - _reward: &Self::Reward, + _reward: Self::Reward, _matcher: &T::AccountId, ) -> Result<(), DispatchError> { Ok(()) @@ -96,124 +64,70 @@ impl IsNativeAsset for AssetId { } } -pub struct AssetRewardManager( - PhantomData<(Asset, AssetSplit, Currency, AssetTransfer)>, +pub struct AssetRewardManager( + PhantomData<(Reward, AssetSplit, Currency)>, ); -impl RewardManager - for AssetRewardManager +impl RewardManager + for AssetRewardManager where - T: Config + frame_system::Config, - DispatchError: From<<::AssetValidator as AssetValidator>::Error>, - Asset: Parameter + Member + Reward, + T: Config + frame_system::Config, + Reward: Balance, AssetSplit: FeeManager, - Currency: frame_support::traits::Currency, - AssetTransfer: pallet_acurast::AssetTransfer< - AccountId = T::AccountId, - AssetId = Asset::AssetId, - Balance = Currency::Balance, - Error = DispatchError, - >, + Currency: frame_support::traits::Currency, + Currency::Balance: Member, { - type Reward = Asset; - - fn lock_reward(reward: &Self::Reward, owner: &T::AccountId) -> Result<(), DispatchError> { - let asset_id = reward - .try_get_asset_id() - .map_err(|_| Error::::InvalidAssetId)?; - - T::AssetValidator::validate(&asset_id)?; - - let amount = reward - .try_get_amount() - .map_err(|_| Error::::InvalidAssetAmount)?; + type Reward = Reward; + fn lock_reward(reward: Self::Reward, owner: &T::AccountId) -> Result<(), DispatchError> { let pallet_account: T::AccountId = ::PalletId::get().into_account_truncating(); - if asset_id.is_native_asset() { - Currency::transfer( - owner, - &pallet_account, - amount, - frame_support::traits::ExistenceRequirement::KeepAlive, - )?; - } else { - AssetTransfer::transfer(asset_id, owner, &pallet_account, amount)?; - } + Currency::transfer( + owner, + &pallet_account, + reward, + frame_support::traits::ExistenceRequirement::KeepAlive, + )?; Ok(()) } - fn pay_reward(reward: &Self::Reward, target: &T::AccountId) -> Result<(), DispatchError> { + fn pay_reward(reward: Self::Reward, target: &T::AccountId) -> Result<(), DispatchError> { let pallet_account: T::AccountId = ::PalletId::get().into_account_truncating(); - let asset_id = reward - .try_get_asset_id() - .map_err(|_| Error::::InvalidAssetId)?; - - let amount = reward - .try_get_amount() - .map_err(|_| Error::::InvalidAssetAmount)?; - // Extract fee from the processor reward let fee_percentage = AssetSplit::get_fee_percentage(); // TODO: fee will be indexed by version in the future - let fee = fee_percentage.mul_floor(amount); + let fee = fee_percentage.mul_floor(reward); // Subtract the fee from the reward - let reward_after_fee = amount - fee; + let reward_after_fee = reward - fee; // Transfer fees to Acurast fees manager account let fee_pallet_account: T::AccountId = AssetSplit::pallet_id().into_account_truncating(); - if asset_id.is_native_asset() { - Currency::transfer( - &pallet_account, - &fee_pallet_account, - fee, - frame_support::traits::ExistenceRequirement::KeepAlive, - )?; - Currency::transfer( - &pallet_account, - target, - reward_after_fee, - frame_support::traits::ExistenceRequirement::KeepAlive, - )?; - } else { - AssetTransfer::transfer(asset_id.clone(), &pallet_account, &fee_pallet_account, fee)?; - AssetTransfer::transfer(asset_id, &pallet_account, target, reward_after_fee)?; - } + Currency::transfer( + &pallet_account, + &fee_pallet_account, + fee, + frame_support::traits::ExistenceRequirement::KeepAlive, + )?; + Currency::transfer( + &pallet_account, + target, + reward_after_fee, + frame_support::traits::ExistenceRequirement::KeepAlive, + )?; Ok(()) } fn pay_matcher_reward( - remaining_reward: &Self::Reward, + remaining_reward: Self::Reward, matcher: &T::AccountId, ) -> Result<(), DispatchError> { let matcher_fee_percentage = AssetSplit::get_matcher_percentage(); // TODO: fee will be indexed by version in the future - let amount = remaining_reward - .try_get_amount() - .map_err(|_| Error::::InvalidAssetAmount)?; - let mut r = remaining_reward.clone(); - r.with_amount(matcher_fee_percentage.mul_floor(amount)) - .map_err(|_| Error::::InvalidAssetAmount)?; - - >::pay_reward(&r, matcher) - } -} - -impl AssetValidator - for AssetRewardManager -where - AssetTransfer: AssetValidator, - DispatchError: From, -{ - type Error = DispatchError; - - fn validate(asset: &AssetId) -> Result<(), Self::Error> { - if asset.is_native_asset() { - Ok(()) - } else { - Ok(AssetTransfer::validate(asset)?) - } + >::pay_reward( + matcher_fee_percentage.mul_floor(remaining_reward), + matcher, + ) } } diff --git a/pallets/marketplace/src/rpc.rs b/pallets/marketplace/src/rpc.rs index ee74d432..8960f480 100644 --- a/pallets/marketplace/src/rpc.rs +++ b/pallets/marketplace/src/rpc.rs @@ -2,7 +2,7 @@ use std::{marker::PhantomData, sync::Arc}; -use crate::{MarketplaceRuntimeApi, PartialJobRegistration, Reward, RuntimeApiError}; +use crate::{MarketplaceRuntimeApi, PartialJobRegistration, RuntimeApiError}; use codec::Codec; use jsonrpsee::{ core::{async_trait, RpcResult}, @@ -22,10 +22,7 @@ const MARKETPLACE_ERROR: i32 = 8011; #[rpc(client, server)] pub trait MarketplaceApi< BlockHash, - AssetId, - AssetAmount, - Error, - R: Reward + MaybeSerializeDeserialize, + Reward: MaybeSerializeDeserialize, AccountId: MaybeSerializeDeserialize, > { @@ -34,7 +31,7 @@ pub trait MarketplaceApi< #[method(name = "filterMatchingSources")] fn filter_matching_sources( &self, - registration: PartialJobRegistration, + registration: PartialJobRegistration, sources: Vec, consumer: Option>, latest_seen_after: Option, @@ -58,27 +55,18 @@ impl Marketplace { } #[async_trait] -impl - MarketplaceApiServer, AssetId, AssetAmount, Error, R, AccountId> - for Marketplace +impl MarketplaceApiServer, Reward, AccountId> + for Marketplace where Block: BlockT, Client: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, - Client::Api: MarketplaceRuntimeApi, - AssetId: MaybeSerializeDeserialize + Codec + Send + Sync + 'static, - AssetAmount: MaybeSerializeDeserialize + Codec + Send + Sync + 'static, - Error: MaybeSerializeDeserialize + Codec + Send + Sync + 'static, - R: Reward - + MaybeSerializeDeserialize - + Codec - + Send - + Sync - + 'static, + Client::Api: MarketplaceRuntimeApi, + Reward: MaybeSerializeDeserialize + Codec + Send + Sync + 'static, AccountId: MaybeSerializeDeserialize + Codec + Send + Sync + 'static, { fn filter_matching_sources( &self, - registration: PartialJobRegistration, + registration: PartialJobRegistration, sources: Vec, consumer: Option>, latest_seen_after: Option, diff --git a/pallets/marketplace/src/stub.rs b/pallets/marketplace/src/stub.rs index 7e559268..473f6246 100644 --- a/pallets/marketplace/src/stub.rs +++ b/pallets/marketplace/src/stub.rs @@ -1,62 +1,23 @@ #![allow(dead_code)] -use frame_support::pallet_prelude::*; use hex_literal::hex; -use sp_core::*; use sp_runtime::AccountId32; -use sp_std::prelude::*; use pallet_acurast::{AttestationChain, Script, SerialNumber}; -use pallet_acurast_assets_manager::traits::AssetValidator; use crate::*; pub type AccountId = AccountId32; pub type BlockNumber = u32; -pub type AssetId = u32; -pub type AssetAmount = u128; - -#[derive(RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo, Clone, PartialEq, Eq)] -pub struct MockAsset { - pub id: AssetId, - pub amount: AssetAmount, -} - -impl Reward for MockAsset { - type AssetId = AssetId; - type AssetAmount = AssetAmount; - type Error = (); - - fn with_amount(&mut self, amount: Self::AssetAmount) -> Result<&Self, Self::Error> { - self.amount = amount; - Ok(self) - } - - fn try_get_asset_id(&self) -> Result { - Ok(self.id) - } - - fn try_get_amount(&self) -> Result { - Ok(self.amount) - } -} - -pub struct PassAllAssets {} -impl AssetValidator for PassAllAssets { - type Error = DispatchError; - - fn validate(_: &AssetId) -> Result<(), Self::Error> { - Ok(()) - } -} +pub type Balance = u128; pub const SEED: u32 = 1337; pub const INITIAL_BALANCE: u128 = UNIT * 10; -pub const EXISTENTIAL_DEPOSIT: AssetAmount = MILLIUNIT; -pub const UNIT: AssetAmount = 1_000_000; -pub const MILLIUNIT: AssetAmount = UNIT / 1_000; -pub const MICROUNIT: AssetAmount = UNIT / 1_000_000; +pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT; +pub const UNIT: Balance = 1_000_000; +pub const MILLIUNIT: Balance = UNIT / 1_000; +pub const MICROUNIT: Balance = UNIT / 1_000_000; pub const SCRIPT_BYTES: [u8; 53] = hex!("697066733A2F2F00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); pub const SCRIPT_RANDOM_VALUE_BYTES: [u8; 53] = hex!("697066733a2f2f516d644a4e764d4c66766a7a4a6e48514a6d73454243384b554431667954757346726b5841463559615a6f755432"); pub const OPERATION_HASH: [u8; 32] = @@ -164,10 +125,3 @@ pub fn account_id(i: u8) -> AccountId { pub fn script_random_value() -> Script { SCRIPT_RANDOM_VALUE_BYTES.to_vec().try_into().unwrap() } - -pub fn asset(value: u128) -> MockAsset { - MockAsset { - id: 0, - amount: value, - } -} diff --git a/pallets/marketplace/src/tests.rs b/pallets/marketplace/src/tests.rs index ef76e2b0..fa9d2d0f 100644 --- a/pallets/marketplace/src/tests.rs +++ b/pallets/marketplace/src/tests.rs @@ -21,7 +21,6 @@ fn test_match() { // 1000 is the smallest amount accepted by T::AssetTransactor::lock_asset for the asset used let ad = advertisement(1000, 1, 100_000, 50_000, 8); - let asset_id = ad.pricing[0].reward_asset; let registration1 = JobRegistrationFor:: { script: script(), allowed_sources: None, @@ -39,7 +38,7 @@ fn test_match() { required_modules: JobModules::default(), extra: JobRequirements { slots: 1, - reward: asset(3_000_000 * 2), + reward: 3_000_000 * 2, min_reputation: None, instant_match: None, }, @@ -61,7 +60,7 @@ fn test_match() { required_modules: JobModules::default(), extra: JobRequirements { slots: 1, - reward: asset(3_000_000 * 2), + reward: 3_000_000 * 2, min_reputation: None, instant_match: None, }, @@ -96,11 +95,8 @@ fn test_match() { AcurastMarketplace::stored_advertisement(processor_account_id()) ); assert_eq!( - Some(ad.pricing[0].clone()), - AcurastMarketplace::stored_advertisement_pricing( - processor_account_id(), - asset_id.clone() - ) + Some(ad.pricing.clone()), + AcurastMarketplace::stored_advertisement_pricing(processor_account_id()) ); assert_ok!(Acurast::register( @@ -176,13 +172,12 @@ fn test_match() { ExecutionResult::Success(operation_hash()) )); // average reward only updated at end of job - assert_eq!(None, AcurastMarketplace::average_reward(asset_id.clone()),); + assert_eq!(None, AcurastMarketplace::average_reward()); // reputation still ~50% assert_eq!( Permill::from_parts(509_803), BetaReputation::::normalize( - AcurastMarketplace::stored_reputation(processor_account_id(), asset_id.clone()) - .unwrap() + AcurastMarketplace::stored_reputation(processor_account_id()).unwrap() ) .unwrap() ); @@ -190,10 +185,7 @@ fn test_match() { Some(Assignment { slot: 0, start_delay: 0, - fee_per_execution: MockAsset { - id: 0, - amount: 5_020_000 - }, + fee_per_execution: 5_020_000, acknowledged: true, sla: SLA { total: 2, met: 1 }, pub_keys: PubKeys::default(), @@ -233,21 +225,14 @@ fn test_match() { None, AcurastMarketplace::stored_matches(processor_account_id(), job_id1.clone()), ); - assert_eq!( - Some(2), - AcurastMarketplace::total_assigned(asset_id.clone()) - ); + assert_eq!(Some(2), AcurastMarketplace::total_assigned()); // average reward only updated at end of job - assert_eq!( - Some(3000000), - AcurastMarketplace::average_reward(asset_id.clone()) - ); + assert_eq!(Some(3000000), AcurastMarketplace::average_reward()); // reputation increased assert_eq!( Permill::from_parts(763_424), BetaReputation::::normalize( - AcurastMarketplace::stored_reputation(processor_account_id(), asset_id.clone()) - .unwrap() + AcurastMarketplace::stored_reputation(processor_account_id()).unwrap() ) .unwrap() ); @@ -273,47 +258,32 @@ fn test_match() { ad.clone(), processor_account_id() )), - RuntimeEvent::MockPallet(mock_pallet::Event::Locked(MockAsset { - id: 0, - amount: 12_000_000 - })), + RuntimeEvent::MockPallet(mock_pallet::Event::Locked(12_000_000)), RuntimeEvent::Acurast(pallet_acurast::Event::JobRegistrationStored( registration1.clone(), job_id1.clone(), )), - RuntimeEvent::MockPallet(mock_pallet::Event::Locked(MockAsset { - id: 0, - amount: 12_000_000 - })), + RuntimeEvent::MockPallet(mock_pallet::Event::Locked(12_000_000)), RuntimeEvent::Acurast(pallet_acurast::Event::JobRegistrationStored( registration2.clone(), job_id2.clone(), )), RuntimeEvent::AcurastMarketplace(crate::Event::JobRegistrationMatched(job_match1)), RuntimeEvent::AcurastMarketplace(crate::Event::JobRegistrationMatched(job_match2)), - RuntimeEvent::MockPallet(mock_pallet::Event::PayMatcherReward(MockAsset { - id: 0, - amount: 3_920_000 // this is before splitting of the configured percentage that actually is transferred to the matcher - })), + RuntimeEvent::MockPallet(mock_pallet::Event::PayMatcherReward(3_920_000)), // this is before splitting of the configured percentage that actually is transferred to the matcher RuntimeEvent::AcurastMarketplace(crate::Event::JobRegistrationAssigned( job_id1.clone(), processor_account_id(), Assignment { slot: 0, start_delay: 0, - fee_per_execution: MockAsset { - id: 0, - amount: 5_020_000 - }, + fee_per_execution: 5_020_000, acknowledged: true, sla: SLA { total: 2, met: 0 }, pub_keys: PubKeys::default(), } )), - RuntimeEvent::MockPallet(mock_pallet::Event::PayReward(MockAsset { - id: 0, - amount: 5_020_000 - })), + RuntimeEvent::MockPallet(mock_pallet::Event::PayReward(5_020_000)), RuntimeEvent::AcurastMarketplace(crate::Event::ExecutionSuccess( job_id1.clone(), operation_hash() @@ -324,19 +294,13 @@ fn test_match() { Assignment { slot: 0, start_delay: 0, - fee_per_execution: MockAsset { - id: 0, - amount: 5_020_000 - }, + fee_per_execution: 5_020_000, acknowledged: true, sla: SLA { total: 2, met: 1 }, pub_keys: PubKeys::default(), } )), - RuntimeEvent::MockPallet(mock_pallet::Event::PayReward(MockAsset { - id: 0, - amount: 5_020_000 - })), + RuntimeEvent::MockPallet(mock_pallet::Event::PayReward(5_020_000)), RuntimeEvent::AcurastMarketplace(crate::Event::ExecutionSuccess( job_id1.clone(), operation_hash() @@ -347,10 +311,7 @@ fn test_match() { Assignment { slot: 0, start_delay: 0, - fee_per_execution: MockAsset { - id: 0, - amount: 5_020_000 - }, + fee_per_execution: 5_020_000, acknowledged: true, sla: SLA { total: 2, met: 2 }, pub_keys: PubKeys::default(), @@ -385,7 +346,7 @@ fn test_no_match_schedule_overlap() { required_modules: JobModules::default(), extra: JobRequirements { slots: 1, - reward: asset(3_000_000 * 2), + reward: 3_000_000 * 2, min_reputation: None, instant_match: None, }, @@ -408,7 +369,7 @@ fn test_no_match_schedule_overlap() { required_modules: JobModules::default(), extra: JobRequirements { slots: 1, - reward: asset(3_000_000 * 2), + reward: 3_000_000 * 2, min_reputation: None, instant_match: None, }, @@ -481,27 +442,18 @@ fn test_no_match_schedule_overlap() { ad.clone(), processor_account_id() )), - RuntimeEvent::MockPallet(mock_pallet::Event::Locked(MockAsset { - id: 0, - amount: 12_000_000 - })), + RuntimeEvent::MockPallet(mock_pallet::Event::Locked(12_000_000)), RuntimeEvent::Acurast(pallet_acurast::Event::JobRegistrationStored( registration1.clone(), job_id1.clone() )), - RuntimeEvent::MockPallet(mock_pallet::Event::Locked(MockAsset { - id: 0, - amount: 18_000_000 - })), + RuntimeEvent::MockPallet(mock_pallet::Event::Locked(18_000_000)), RuntimeEvent::Acurast(pallet_acurast::Event::JobRegistrationStored( registration2.clone(), (job_id1.0.clone(), &job_id1.1 + 1) )), RuntimeEvent::AcurastMarketplace(crate::Event::JobRegistrationMatched(m)), - RuntimeEvent::MockPallet(mock_pallet::Event::PayMatcherReward(MockAsset { - id: 0, - amount: 1_960_000 // this is before splitting of the configured percentage that actually is transferred to the matcher - })), + RuntimeEvent::MockPallet(mock_pallet::Event::PayMatcherReward(1_960_000)), // no match event for second ] ); @@ -531,7 +483,7 @@ fn test_no_match_insufficient_reputation() { required_modules: JobModules::default(), extra: JobRequirements { slots: 1, - reward: asset(3_000_000 * 2), + reward: 3_000_000 * 2, min_reputation: Some(1_000_000), instant_match: None, }, @@ -581,10 +533,7 @@ fn test_no_match_insufficient_reputation() { ad.clone(), processor_account_id() )), - RuntimeEvent::MockPallet(mock_pallet::Event::Locked(MockAsset { - id: 0, - amount: 12_000_000 - })), + RuntimeEvent::MockPallet(mock_pallet::Event::Locked(12_000_000)), RuntimeEvent::Acurast(pallet_acurast::Event::JobRegistrationStored( registration1.clone(), job_id.clone() @@ -618,7 +567,7 @@ fn test_more_reports_than_expected() { required_modules: JobModules::default(), extra: JobRequirements { slots: 1, - reward: asset(3_000_000 * 2), + reward: 3_000_000 * 2, min_reputation: None, instant_match: None, }, @@ -706,38 +655,26 @@ fn test_more_reports_than_expected() { ad.clone(), processor_account_id() )), - RuntimeEvent::MockPallet(mock_pallet::Event::Locked(MockAsset { - id: 0, - amount: 12_000_000 - })), + RuntimeEvent::MockPallet(mock_pallet::Event::Locked(12_000_000)), RuntimeEvent::Acurast(pallet_acurast::Event::JobRegistrationStored( registration.clone(), job_id.clone() )), RuntimeEvent::AcurastMarketplace(crate::Event::JobRegistrationMatched(m)), - RuntimeEvent::MockPallet(mock_pallet::Event::PayMatcherReward(MockAsset { - id: 0, - amount: 1_960_000 // this is before splitting of the configured percentage that actually is transferred to the matcher - })), + RuntimeEvent::MockPallet(mock_pallet::Event::PayMatcherReward(1_960_000)), RuntimeEvent::AcurastMarketplace(crate::Event::JobRegistrationAssigned( job_id.clone(), processor_account_id(), Assignment { slot: 0, start_delay: 0, - fee_per_execution: MockAsset { - id: 0, - amount: 5_020_000 - }, + fee_per_execution: 5_020_000, acknowledged: true, sla: SLA { total: 2, met: 0 }, pub_keys: PubKeys::default(), } )), - RuntimeEvent::MockPallet(mock_pallet::Event::PayReward(MockAsset { - id: 0, - amount: 5_020_000 - })), + RuntimeEvent::MockPallet(mock_pallet::Event::PayReward(5_020_000)), RuntimeEvent::AcurastMarketplace(crate::Event::ExecutionSuccess( job_id.clone(), operation_hash() @@ -748,19 +685,13 @@ fn test_more_reports_than_expected() { Assignment { slot: 0, start_delay: 0, - fee_per_execution: MockAsset { - id: 0, - amount: 5_020_000 - }, + fee_per_execution: 5_020_000, acknowledged: true, sla: SLA { total: 2, met: 1 }, pub_keys: PubKeys::default(), } )), - RuntimeEvent::MockPallet(mock_pallet::Event::PayReward(MockAsset { - id: 0, - amount: 5_020_000 - })), + RuntimeEvent::MockPallet(mock_pallet::Event::PayReward(5_020_000)), RuntimeEvent::AcurastMarketplace(crate::Event::ExecutionSuccess( job_id.clone(), operation_hash() @@ -771,10 +702,7 @@ fn test_more_reports_than_expected() { Assignment { slot: 0, start_delay: 0, - fee_per_execution: MockAsset { - id: 0, - amount: 5_020_000 - }, + fee_per_execution: 5_020_000, acknowledged: true, sla: SLA { total: 2, met: 2 }, pub_keys: PubKeys::default(), diff --git a/pallets/marketplace/src/types.rs b/pallets/marketplace/src/types.rs index e86bc2d5..df42a6fe 100644 --- a/pallets/marketplace/src/types.rs +++ b/pallets/marketplace/src/types.rs @@ -12,7 +12,6 @@ use serde::{Deserialize, Serialize}; use crate::payments::RewardFor; use crate::Config; -pub const MAX_PRICING_VARIANTS: u32 = 100; pub const MAX_EXECUTIONS_PER_JOB: u64 = 10000; pub const EXECUTION_OPERATION_HASH_MAX_LENGTH: u32 = 256; @@ -41,9 +40,9 @@ impl From> /// The resource advertisement by a source containing pricing and capacity announcements. #[derive(RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo, Clone, PartialEq, Eq)] -pub struct Advertisement> { +pub struct Advertisement> { /// The reward token accepted. Understood as one-of per job assigned. - pub pricing: BoundedVec, ConstU32>, + pub pricing: Pricing, /// Maximum memory in bytes not to be exceeded during any job's execution. pub max_memory: u32, /// Maximum network requests per second not to be exceeded. @@ -58,8 +57,7 @@ pub struct Advertisement = Advertisement< ::AccountId, - ::AssetId, - ::AssetAmount, + ::Balance, ::MaxAllowedConsumers, >; @@ -91,23 +89,21 @@ pub enum SchedulingWindow { Delta(u64), } -/// Pricing variant listing cost per resource unit and slash on SLA violation. +/// Pricing listing cost per resource unit and slash on SLA violation. /// Specified in specific asset that is payed out or deducted from stake on complete fulfillment. #[derive(RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo, Clone, PartialEq, Eq)] -pub struct PricingVariant { - /// The rewarded asset. Only one per [PricingVariant]. - pub reward_asset: AssetId, +pub struct Pricing { /// Fee per millisecond in [reward_asset]. - pub fee_per_millisecond: AssetAmount, + pub fee_per_millisecond: Reward, /// Fee per storage byte in [reward_asset]. - pub fee_per_storage_byte: AssetAmount, + pub fee_per_storage_byte: Reward, /// A fixed base fee for each execution (for each slot and at each interval) in [reward_asset]. - pub base_fee_per_execution: AssetAmount, + pub base_fee_per_execution: Reward, /// The scheduling window in which to accept matches for this pricing. pub scheduling_window: SchedulingWindow, } -pub type PricingVariantFor = PricingVariant<::AssetId, ::AssetAmount>; +pub type PricingFor = Pricing<::Balance>; /// A proposed [Match] becomes an [Assignment] once it's acknowledged. /// diff --git a/pallets/processor-manager/src/mock.rs b/pallets/processor-manager/src/mock.rs index c46ad5ed..77c5e143 100644 --- a/pallets/processor-manager/src/mock.rs +++ b/pallets/processor-manager/src/mock.rs @@ -1,5 +1,4 @@ use frame_support::{ - pallet_prelude::GenesisBuild, sp_runtime::{ generic, traits::{AccountIdLookup, BlakeTwo256, ConstU128, ConstU32}, @@ -7,7 +6,6 @@ use frame_support::{ }, traits::{ fungible::{Inspect, Mutate}, - fungibles::{InspectEnumerable, Transfer}, nonfungibles::{Create, InspectEnumerable as NFTInspectEnumerable}, AsEnsureOriginWithArg, Everything, }, @@ -29,7 +27,6 @@ impl ExtBuilder { pallet_balances::GenesisConfig:: { balances: vec![ (alice_account_id(), INITIAL_BALANCE), - (pallet_assets_account(), INITIAL_BALANCE), (bob_account_id(), INITIAL_BALANCE), (processor_account_id(), INITIAL_BALANCE), ], @@ -37,19 +34,6 @@ impl ExtBuilder { .assimilate_storage(&mut t) .unwrap(); - // give alice an initial balance of token 22 (backed by statemint) to pay for a job - // get the MockAsset representing token 22 with owned_asset() - pallet_assets::GenesisConfig:: { - assets: vec![(22, pallet_assets_account(), false, 1_000)], - metadata: vec![(22, "test_payment".into(), "tpt".into(), 12.into())], - accounts: vec![ - (22, alice_account_id(), INITIAL_BALANCE), - (22, bob_account_id(), INITIAL_BALANCE), - ], - } - .assimilate_storage(&mut t) - .unwrap(); - let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext @@ -70,7 +54,6 @@ frame_support::construct_runtime!( { System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Assets: pallet_assets::{Pallet, Config, Event, Storage}, Uniques: pallet_uniques::{Pallet, Storage, Event, Call}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, AcurastProcessorManager: crate::{Pallet, Call, Storage, Event}, @@ -118,40 +101,6 @@ impl pallet_balances::Config for Test { type ReserveIdentifier = [u8; 8]; } -impl pallet_assets::Config for Test { - type RuntimeEvent = RuntimeEvent; - type Balance = Balance; - type AssetId = AssetId; - type AssetIdParameter = codec::Compact; - type Currency = Balances; - type CreateOrigin = AsEnsureOriginWithArg>; - type ForceOrigin = frame_system::EnsureRoot; - type AssetDeposit = ConstU128<0>; - type AssetAccountDeposit = ConstU128<0>; - type MetadataDepositBase = ConstU128<0>; - type MetadataDepositPerByte = ConstU128<0>; - type ApprovalDeposit = ConstU128<0>; - type StringLimit = ConstU32<50>; - type Freezer = (); - type Extra = (); - type WeightInfo = (); - type RemoveItemsLimit = (); - type CallbackHandle = (); - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = TestBenchmarkHelper; -} - -#[cfg(feature = "runtime-benchmarks")] -pub struct TestBenchmarkHelper; -#[cfg(feature = "runtime-benchmarks")] -impl pallet_assets::BenchmarkHelper<::AssetIdParameter> - for TestBenchmarkHelper -{ - fn create_asset_id_parameter(id: u32) -> ::AssetIdParameter { - codec::Compact(id.into()) - } -} - impl pallet_uniques::Config for Test { type RuntimeEvent = RuntimeEvent; type CollectionId = u128; @@ -237,20 +186,6 @@ impl ProcessorAssetRecovery for AcurastProcessorAssetRecovery { let burned = Balances::burn_from(processor, usable_balance)?; Balances::mint_into(destination_account, burned)?; } - - let ids = Assets::asset_ids(); - for id in ids { - let balance = Assets::balance(id, processor); - if balance > 0 { - ::AccountId>>::transfer( - id, - &processor, - &destination_account, - balance, - false, - )?; - } - } Ok(()) } } diff --git a/pallets/processor-manager/src/stub.rs b/pallets/processor-manager/src/stub.rs index 10dc86c6..1e1c3a93 100644 --- a/pallets/processor-manager/src/stub.rs +++ b/pallets/processor-manager/src/stub.rs @@ -3,7 +3,7 @@ use codec::Encode; use frame_support::{ parameter_types, - sp_runtime::{traits::AccountIdConversion, AccountId32, MultiSignature}, + sp_runtime::{AccountId32, MultiSignature}, weights::Weight, PalletId, }; @@ -41,10 +41,6 @@ parameter_types! { pub const ReportTolerance: u64 = 12000; } -pub fn pallet_assets_account() -> AccountId { - AcurastPalletId::get().into_account_truncating() -} - pub fn processor_account_id() -> AccountId { hex!("b8bc25a2b4c0386b8892b43e435b71fe11fa50533935f027949caf04bcce4694").into() } diff --git a/pallets/processor-manager/src/tests.rs b/pallets/processor-manager/src/tests.rs index b9df0e95..1c1ec2be 100644 --- a/pallets/processor-manager/src/tests.rs +++ b/pallets/processor-manager/src/tests.rs @@ -254,13 +254,6 @@ fn test_recover_funds_succeed_1() { 10_000_000 )); assert_eq!(Balances::balance(&alice_account_id()), 90_000_000); - assert_ok!(Assets::transfer( - RuntimeOrigin::signed(alice_account_id()), - codec::Compact(22), - processor_account.clone().into(), - 1_000_000 - )); - assert_eq!(1_000_000, Assets::balance(22, &processor_account)); let call = AcurastProcessorManager::recover_funds( RuntimeOrigin::signed(alice_account_id()), @@ -270,7 +263,6 @@ fn test_recover_funds_succeed_1() { assert_ok!(call); assert_eq!(Balances::balance(&alice_account_id()), 99_999_000); // 1_000 of existensial balance remains on the processor - assert_eq!(Assets::balance(22, &processor_account), 0); assert_eq!( events().last().unwrap(), diff --git a/pallets/proxy/src/benchmarking.rs b/pallets/proxy/src/benchmarking.rs index 4994c429..8542d4b5 100644 --- a/pallets/proxy/src/benchmarking.rs +++ b/pallets/proxy/src/benchmarking.rs @@ -1,16 +1,16 @@ -use super::*; - -use acurast_common::{AllowedSourcesUpdate, JobRegistration}; use frame_benchmarking::{benchmarks, whitelisted_caller}; use frame_support::traits::Get; use frame_system::RawOrigin; + +use acurast_common::{AllowedSourcesUpdate, JobRegistration}; use pallet_acurast_marketplace::Advertisement; +use super::*; + pub trait BenchmarkHelper { fn create_job_registration() -> JobRegistration; fn create_allowed_sources_update(index: u32) -> AllowedSourcesUpdate; - fn create_advertisement( - ) -> Advertisement; + fn create_advertisement() -> Advertisement; } benchmarks! { diff --git a/pallets/proxy/src/lib.rs b/pallets/proxy/src/lib.rs index 85709e35..6fbae47f 100644 --- a/pallets/proxy/src/lib.rs +++ b/pallets/proxy/src/lib.rs @@ -43,8 +43,7 @@ pub mod pallet { #[pallet::constant] type MaxAllowedSources: Get; type MaxAllowedConsumers: Get + Parameter; - type AssetId: Parameter + Member; - type AssetAmount: Parameter; + type Balance: Parameter; type XcmSender: SendXcm; type AcurastPalletId: Get; type AcurastMarketplacePalletId: Get; @@ -78,8 +77,7 @@ pub mod pallet { #[codec(index = 0u8)] Advertise { - advertisement: - Advertisement, + advertisement: Advertisement, }, } @@ -225,12 +223,7 @@ pub mod pallet { #[pallet::weight(T::WeightInfo::advertise())] pub fn advertise( origin: OriginFor, - advertisement: Advertisement< - T::AccountId, - T::AssetId, - T::AssetAmount, - T::MaxAllowedConsumers, - >, + advertisement: Advertisement, ) -> DispatchResult { let caller = ensure_signed(origin)?; let proxy_call = ProxyCall::Advertise { advertisement }; diff --git a/pallets/proxy/src/mock.rs b/pallets/proxy/src/mock.rs index a9425cc9..109b390a 100644 --- a/pallets/proxy/src/mock.rs +++ b/pallets/proxy/src/mock.rs @@ -1,24 +1,19 @@ use std::marker::PhantomData; -use acurast_common::Schedule; use frame_support::traits::OriginTrait; -use pallet_acurast_marketplace::Reward; -use scale_info::TypeInfo; -use sp_core::*; -use sp_std::prelude::*; use xcm::latest::{Junction, MultiLocation, OriginKind}; use xcm::prelude::*; use xcm_executor::traits::ConvertOrigin; -pub type AcurastAssetId = AssetId; -pub type InternalAssetId = u32; -pub type AcurastAssetAmount = u128; - +use acurast_common::Schedule; use acurast_runtime::AccountId as AcurastAccountId; use pallet_acurast::{JobModules, JobRegistration, CU32}; -use pallet_acurast_marketplace::{ - types::MAX_PRICING_VARIANTS, Advertisement, JobRequirements, PricingVariant, SchedulingWindow, -}; +use pallet_acurast_marketplace::{Advertisement, JobRequirements, Pricing, SchedulingWindow}; + +#[cfg(feature = "runtime-benchmarks")] +pub const SEED: u32 = 1337; + +pub type Balance = u128; pub const SCRIPT_BYTES: [u8; 53] = hex_literal::hex!("697066733A2F2F00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); @@ -28,17 +23,8 @@ pub fn alice_account_id() -> AcurastAccountId { pub fn bob_account_id() -> AcurastAccountId { [1; 32].into() } -pub fn owned_asset(amount: u128) -> AcurastAsset { - AcurastAsset(MultiAsset { - id: Concrete(MultiLocation { - parents: 1, - interior: X3(Parachain(1000), PalletInstance(50), GeneralIndex(22)), - }), - fun: Fungible(amount), - }) -} pub fn registration( -) -> JobRegistration> { +) -> JobRegistration> { JobRegistration { script: SCRIPT_BYTES.to_vec().try_into().unwrap(), allowed_sources: None, @@ -56,37 +42,22 @@ pub fn registration( required_modules: JobModules::default(), extra: JobRequirements { slots: 1, - reward: owned_asset(20000), + reward: 20000, min_reputation: None, instant_match: None, }, } } -pub fn asset(id: u32) -> AssetId { - AssetId::Concrete(MultiLocation::new( - 1, - X3( - Parachain(1000), - PalletInstance(50), - GeneralIndex(id as u128), - ), - )) -} pub fn advertisement( fee_per_millisecond: u128, -) -> Advertisement> { - let pricing: frame_support::BoundedVec< - PricingVariant, - ConstU32, - > = bounded_vec![PricingVariant { - reward_asset: asset(22), - fee_per_millisecond, - fee_per_storage_byte: 0, - base_fee_per_execution: 0, - scheduling_window: SchedulingWindow::Delta(2_628_000_000), // 1 month - }]; +) -> Advertisement> { Advertisement { - pricing, + pricing: Pricing { + fee_per_millisecond, + fee_per_storage_byte: 0, + base_fee_per_execution: 0, + scheduling_window: SchedulingWindow::Delta(2_628_000_000), // 1 month + }, allowed_consumers: None, storage_capacity: 5, max_memory: 5000, @@ -95,45 +66,13 @@ pub fn advertisement( } } -#[derive(Clone, Eq, PartialEq, Debug, Encode, Decode, TypeInfo)] -pub struct AcurastAsset(pub MultiAsset); - -impl Reward for AcurastAsset { - type AssetId = AcurastAssetId; - type AssetAmount = AcurastAssetAmount; - type Error = (); - - fn with_amount(&mut self, amount: Self::AssetAmount) -> Result<&Self, Self::Error> { - self.0 = MultiAsset { - id: self.0.id.clone(), - fun: Fungible(amount), - }; - Ok(self) - } - - fn try_get_asset_id(&self) -> Result { - Ok(self.0.id.clone()) - } - - fn try_get_amount(&self) -> Result { - match self.0.fun { - Fungible(amount) => Ok(amount), - _ => Err(()), - } - } -} - pub mod acurast_runtime { use frame_support::{ construct_runtime, parameter_types, sp_runtime::{testing::Header, traits::AccountIdLookup, AccountId32}, - traits::{AsEnsureOriginWithArg, Everything, Nothing}, + traits::{Everything, Nothing}, PalletId, }; - pub use pallet_acurast::{self, CU32}; - use pallet_acurast_assets_manager::traits::AssetValidator; - pub use pallet_acurast_marketplace; - use pallet_acurast_marketplace::{AssetRewardManager, JobRequirements}; use pallet_xcm::XcmPassthrough; use polkadot_parachain::primitives::Sibling; use sp_core::*; @@ -148,7 +87,11 @@ pub mod acurast_runtime { }; use xcm_executor::XcmExecutor; - use super::{AcurastAsset, AcurastAssetAmount, AcurastAssetId, InternalAssetId}; + pub use pallet_acurast::{self, CU32}; + pub use pallet_acurast_marketplace; + use pallet_acurast_marketplace::{AssetRewardManager, JobRequirements}; + + use super::Balance; pub type AccountId = AccountId32; pub type LocalOriginToLocation = SignedToAccountId32; @@ -171,19 +114,8 @@ pub mod acurast_runtime { XcmPassthrough, ); - pub struct PassAllAssets {} - impl AssetValidator for PassAllAssets { - type Error = DispatchError; - - fn validate(_: &AssetId) -> Result<(), Self::Error> { - Ok(()) - } - } - pub const MILLISECS_PER_BLOCK: u64 = 12000; pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; - pub const UNIT: AcurastAssetAmount = 1_000_000; - pub const MICROUNIT: AcurastAssetAmount = 1; construct_runtime!( pub enum Runtime where @@ -194,8 +126,6 @@ pub mod acurast_runtime { System: frame_system::{Pallet, Call, Storage, Config, Event} = 0, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Assets: pallet_assets::{Pallet, Storage, Event, Config}, // hide calls since they get proxied by `pallet_acurast_assets` - AcurastAssets: pallet_acurast_assets_manager::{Pallet, Storage, Event, Config, Call}, ParachainInfo: parachain_info::{Pallet, Storage, Config}, MsgQueue: super::mock_msg_queue::{Pallet, Storage, Event}, PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin}, @@ -214,7 +144,7 @@ pub mod acurast_runtime { pub const BlockHashCount: u64 = 250; } parameter_types! { - pub ExistentialDeposit: AcurastAssetAmount = 1; + pub ExistentialDeposit: Balance = 1; pub const MaxLocks: u32 = 50; pub const MaxReserves: u32 = 50; } @@ -261,7 +191,7 @@ pub mod acurast_runtime { } impl pallet_balances::Config for Runtime { - type Balance = AcurastAssetAmount; + type Balance = Balance; type DustRemoval = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; @@ -290,7 +220,7 @@ pub mod acurast_runtime { type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; + type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); @@ -308,55 +238,8 @@ pub mod acurast_runtime { type WeightInfo = (); } - impl pallet_assets::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Balance = AcurastAssetAmount; - type AssetId = InternalAssetId; - type AssetIdParameter = codec::Compact; - type Currency = Balances; - type CreateOrigin = AsEnsureOriginWithArg>; - type ForceOrigin = frame_system::EnsureRoot; - type AssetDeposit = frame_support::traits::ConstU128<0>; - type AssetAccountDeposit = frame_support::traits::ConstU128<0>; - type MetadataDepositBase = frame_support::traits::ConstU128<{ UNIT }>; - type MetadataDepositPerByte = frame_support::traits::ConstU128<{ 10 * MICROUNIT }>; - type ApprovalDeposit = frame_support::traits::ConstU128<{ 10 * MICROUNIT }>; - type StringLimit = frame_support::traits::ConstU32<50>; - type Freezer = (); - type Extra = (); - type WeightInfo = (); - type RemoveItemsLimit = (); - type CallbackHandle = (); - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = TestBenchmarkHelper; - } - - impl pallet_acurast_assets_manager::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type ManagerOrigin = frame_system::EnsureRoot; - type WeightInfo = (); - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = TestBenchmarkHelper; - } - #[cfg(feature = "runtime-benchmarks")] pub struct TestBenchmarkHelper; - #[cfg(feature = "runtime-benchmarks")] - impl pallet_assets::BenchmarkHelper<::AssetIdParameter> - for TestBenchmarkHelper - { - fn create_asset_id_parameter( - id: u32, - ) -> ::AssetIdParameter { - codec::Compact(id.into()) - } - } - #[cfg(feature = "runtime-benchmarks")] - impl pallet_acurast_assets_manager::benchmarking::BenchmarkHelper for TestBenchmarkHelper { - fn manager_account() -> ::AccountId { - [0; 32].into() - } - } pub struct FeeManagerImpl; @@ -376,7 +259,7 @@ pub mod acurast_runtime { impl pallet_acurast::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type RegistrationExtra = JobRequirements; + type RegistrationExtra = JobRequirements; type MaxAllowedSources = frame_support::traits::ConstU32<1000>; type MaxCertificateRevocationListUpdates = frame_support::traits::ConstU32<10>; type PalletId = AcurastPalletId; @@ -394,14 +277,22 @@ pub mod acurast_runtime { fn registration_extra() -> ::RegistrationExtra { JobRequirements { slots: 1, - reward: AcurastAsset(MultiAsset { - id: super::asset(1), - fun: Fungible(1), - }), + reward: 1, min_reputation: None, instant_match: None, } } + + fn funded_account(index: u32) -> super::AcurastAccountId { + let caller: super::AcurastAccountId = + frame_benchmarking::account("token_account", index, super::SEED); + >::make_free_balance_be( + &caller, + u32::MAX.into(), + ); + + caller + } } pub struct ManagerOf; @@ -428,15 +319,12 @@ pub mod acurast_runtime { type RuntimeEvent = RuntimeEvent; type MaxAllowedConsumers = CU32<4>; type MaxProposedMatches = frame_support::traits::ConstU32<10>; - type RegistrationExtra = JobRequirements; + type RegistrationExtra = JobRequirements; type PalletId = AcurastPalletId; type ReportTolerance = ReportTolerance; - type AssetId = AcurastAssetId; - type AssetAmount = AcurastAssetAmount; + type Balance = Balance; type ManagerProvider = ManagerOf; - type RewardManager = - AssetRewardManager; - type AssetValidator = PassAllAssets; + type RewardManager = AssetRewardManager; type ProcessorLastSeenProvider = ProcessorLastSeenProvider; type MarketplaceHooks = (); type WeightInfo = pallet_acurast_marketplace::weights::Weights; @@ -451,6 +339,14 @@ pub mod acurast_runtime { ) -> ::RegistrationExtra { r } + + fn funded_account(index: u32, amount: Balance) -> super::AcurastAccountId { + let caller: super::AcurastAccountId = + frame_benchmarking::account("token_account", index, super::SEED); + >::make_free_balance_be(&caller, amount); + + caller + } } impl pallet_xcm::Config for Runtime { @@ -506,7 +402,7 @@ pub mod proxy_runtime { use pallet_acurast::CU32; use pallet_acurast_marketplace::JobRequirements; - use crate::mock::{AcurastAsset, AcurastAssetAmount, AcurastAssetId}; + use crate::mock::Balance; #[cfg(feature = "runtime-benchmarks")] use super::{advertisement, alice_account_id, registration}; @@ -584,7 +480,7 @@ pub mod proxy_runtime { pub const MaxAssetsIntoHolding: u32 = 64; } parameter_types! { - pub ExistentialDeposit: AcurastAssetAmount = 1; + pub ExistentialDeposit: Balance = 1; pub const MaxLocks: u32 = 50; pub const MaxReserves: u32 = 50; } @@ -630,7 +526,7 @@ pub mod proxy_runtime { type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; + type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); @@ -640,7 +536,7 @@ pub mod proxy_runtime { } impl pallet_balances::Config for Runtime { - type Balance = AcurastAssetAmount; + type Balance = Balance; type DustRemoval = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; @@ -683,11 +579,10 @@ pub mod proxy_runtime { impl crate::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type RegistrationExtra = JobRequirements; + type RegistrationExtra = JobRequirements; type MaxAllowedSources = ConstU32<10>; type MaxAllowedConsumers = CU32<10>; - type AssetId = AcurastAssetId; - type AssetAmount = AcurastAssetAmount; + type Balance = Balance; type XcmSender = XcmRouter; type AcurastPalletId = AcurastPalletId; type AcurastMarketplacePalletId = AcurastMarketplacePalletId; @@ -720,8 +615,7 @@ pub mod proxy_runtime { fn create_advertisement() -> pallet_acurast_marketplace::Advertisement< ::AccountId, - ::AssetId, - ::AssetAmount, + ::Balance, ::MaxAllowedConsumers, > { advertisement(10) @@ -755,7 +649,7 @@ pub mod relay_chain { }; use xcm_executor::{Config, XcmExecutor}; - use crate::mock::AcurastAssetAmount; + use crate::mock::Balance; pub type AccountId = AccountId32; pub type SovereignAccountOf = ( @@ -837,7 +731,7 @@ pub mod relay_chain { pub const FirstMessageFactorPercent: u64 = 100; } parameter_types! { - pub ExistentialDeposit: AcurastAssetAmount = 1; + pub ExistentialDeposit: Balance = 1; pub const MaxLocks: u32 = 50; pub const MaxReserves: u32 = 50; } @@ -864,7 +758,7 @@ pub mod relay_chain { type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; + type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); @@ -876,7 +770,7 @@ pub mod relay_chain { impl parachain_info::Config for Runtime {} impl pallet_balances::Config for Runtime { - type Balance = AcurastAssetAmount; + type Balance = Balance; type DustRemoval = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; diff --git a/pallets/proxy/src/tests.rs b/pallets/proxy/src/tests.rs index 09d7a38b..996c45f2 100644 --- a/pallets/proxy/src/tests.rs +++ b/pallets/proxy/src/tests.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use frame_support::{pallet_prelude::GenesisBuild, sp_runtime::traits::AccountIdConversion}; +use frame_support::sp_runtime::traits::AccountIdConversion; use hex_literal::hex; use polkadot_parachain::primitives::Id as ParaId; use xcm_simulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; @@ -82,7 +82,6 @@ pub fn acurast_ext(para_id: u32) -> sp_io::TestExternalities { pallet_balances::GenesisConfig:: { balances: vec![ (alice_account_id(), INITIAL_BALANCE), - (pallet_assets_account(), INITIAL_BALANCE), (pallet_fees_account(), INITIAL_BALANCE), (bob_account_id(), INITIAL_BALANCE), (processor_account_id(), INITIAL_BALANCE), @@ -91,26 +90,6 @@ pub fn acurast_ext(para_id: u32) -> sp_io::TestExternalities { .assimilate_storage(&mut t) .unwrap(); - // give alice an initial balance of token 22 (backed by statemint) to pay for a job - // get the MultiAsset representing token 22 with owned_asset() - pallet_assets::GenesisConfig:: { - assets: vec![(22, pallet_assets_account(), false, 1_000)], - metadata: vec![(22, "test_payment".into(), "tpt".into(), 12.into())], - accounts: vec![ - (22, alice_account_id(), INITIAL_BALANCE), - (22, bob_account_id(), INITIAL_BALANCE), - ], - } - .assimilate_storage(&mut t) - .unwrap(); - - // make asset 22 a valid asset via Genesis - pallet_acurast_assets_manager::GenesisConfig:: { - assets: vec![(22, 1000, 50, 22)], - } - .assimilate_storage(&mut t) - .unwrap(); - let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| { System::set_block_number(1); @@ -167,9 +146,6 @@ pub fn para_account_id(id: u32) -> relay_chain::AccountId { pub fn processor_account_id() -> AcurastAccountId { hex!("b8bc25a2b4c0386b8892b43e435b71fe11fa50533935f027949caf04bcce4694").into() } -pub fn pallet_assets_account() -> ::AccountId { - ::PalletId::get().into_account_truncating() -} pub fn pallet_fees_account() -> ::AccountId { FeeManagerImpl::pallet_id().into_account_truncating() }