diff --git a/Cargo.lock b/Cargo.lock index 34bb28439..9b3edee8f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10464,6 +10464,7 @@ dependencies = [ "sp-keyring 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.36)", "sp-keystore 0.13.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.36)", "sp-runtime 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.36)", + "sp-std 5.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.36)", "sp-timestamp", "sp-transaction-storage-proof", "substrate-build-script-utils", diff --git a/pallets/anonymity-mining/src/lib.rs b/pallets/anonymity-mining/src/lib.rs index 20b69c015..166288888 100644 --- a/pallets/anonymity-mining/src/lib.rs +++ b/pallets/anonymity-mining/src/lib.rs @@ -40,7 +40,7 @@ use frame_support::{ }; use orml_traits::MultiCurrency; use pallet_vanchor::VAnchorConfigration; -use sp_std::{convert::TryInto, prelude::*, vec}; +use sp_std::{convert::TryInto, vec}; use webb_primitives::traits::vanchor::{VAnchorInspector, VAnchorInterface}; pub use pallet::*; @@ -61,7 +61,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -133,12 +133,6 @@ pub mod pallet { fn build(&self) {} } - #[pallet::storage] - #[pallet::getter(fn parameters)] - /// Details of the module's parameters - pub(super) type Parameters, I: 'static = ()> = - StorageValue<_, Vec, ValueQuery>; - #[pallet::storage] #[pallet::getter(fn get_pool_weight)] pub type PoolWeight, I: 'static = ()> = StorageValue<_, u64, ValueQuery>; @@ -156,8 +150,6 @@ pub mod pallet { #[pallet::error] pub enum Error { - /// Parameters haven't been initialized - ParametersNotInitialized, /// Error during hashing HashError, } @@ -165,6 +157,7 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { #[pallet::weight(0)] + #[pallet::call_index(0)] pub fn swap( origin: OriginFor, recipient: T::AccountId, diff --git a/pallets/anonymity-mining/src/mock.rs b/pallets/anonymity-mining/src/mock.rs index 17c72a221..64b19856c 100644 --- a/pallets/anonymity-mining/src/mock.rs +++ b/pallets/anonymity-mining/src/mock.rs @@ -1,11 +1,13 @@ use super::*; use crate::{self as pallet_anonymity_mining}; -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{parameter_types, traits::Nothing, PalletId}; use frame_system as system; use orml_currencies::{BasicCurrencyAdapter, NativeCurrencyOf}; +use sp_runtime::traits::ConstU32; //pub use pallet_balances; pub use pallet::*; +use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; use sp_core::H256; use sp_runtime::{ @@ -157,6 +159,7 @@ parameter_types! { scale_info::TypeInfo, Serialize, Deserialize, + MaxEncodedLen, )] pub struct Element([u8; 32]); @@ -172,12 +175,21 @@ impl ElementTrait for Element { } } +parameter_types! { + #[derive(Debug, TypeInfo)] + pub const MaxEdges: u32 = 1000; + #[derive(Debug, TypeInfo)] + pub const MaxDefaultHashes: u32 = 1000; +} + impl pallet_mt::Config for Test { type Currency = Balances; type DataDepositBase = LeafDepositBase; type DataDepositPerByte = LeafDepositPerByte; type DefaultZeroElement = DefaultZeroElement; type Element = Element; + type MaxEdges = MaxEdges; + type MaxDefaultHashes = MaxDefaultHashes; type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; type Hasher = HasherPallet; @@ -199,12 +211,18 @@ parameter_types! { pub const RegistryStringLimit: u32 = 10; } +parameter_types! { + #[derive(Debug, TypeInfo, PartialEq, Clone, Eq)] + pub const MaxAssetIdInPool: u32 = 1000; +} + impl pallet_asset_registry::Config for Test { type AssetId = webb_primitives::AssetId; type AssetNativeLocation = (); type Balance = Balance; type RuntimeEvent = RuntimeEvent; type NativeAssetId = NativeCurrencyId; + type MaxAssetIdInPool = MaxAssetIdInPool; type RegistryOrigin = frame_system::EnsureRoot; type StringLimit = RegistryStringLimit; type WeightInfo = (); @@ -226,6 +244,7 @@ parameter_types! { impl pallet_vanchor_verifier::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; + type MaxParameterLength = ConstU32<1000>; type Verifier = ArkworksVerifierBn254; type WeightInfo = (); } @@ -233,6 +252,7 @@ impl pallet_vanchor_verifier::Config for Test { impl pallet_hasher::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; + type MaxParameterLength = ConstU32<100>; type Hasher = webb_primitives::hashing::ArkworksPoseidonHasherBn254; type WeightInfo = (); } @@ -298,6 +318,8 @@ impl pallet_vanchor::Config for Test { impl pallet_key_storage::Config for Test { type RuntimeEvent = RuntimeEvent; + type MaxPubkeyLength = ConstU32<1000>; + type MaxPubKeyOwners = ConstU32<1000>; type WeightInfo = (); } diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 4ab10157a..5427e3a2b 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -22,7 +22,10 @@ use frame_support::{ }; use frame_system::pallet_prelude::*; use sp_arithmetic::traits::BaseArithmetic; -use sp_std::{convert::TryInto, vec::Vec}; +use sp_std::{ + convert::{TryFrom, TryInto}, + vec::Vec, +}; #[cfg(test)] mod mock; @@ -48,14 +51,17 @@ pub use traits::{Registry, ShareTokenRegistry}; #[frame_support::pallet] pub mod pallet { use super::*; - use frame_support::sp_runtime::traits::AtLeast32BitUnsigned; + use frame_support::{dispatch::fmt::Debug, sp_runtime::traits::AtLeast32BitUnsigned}; pub type AssetDetailsT = AssetDetails< ::AssetId, ::Balance, BoundedVec::StringLimit>, + ::MaxAssetIdInPool, >; + pub type AssetTypeOf = AssetType<::AssetId, ::MaxAssetIdInPool>; + #[pallet::config] pub trait Config: frame_system::Config { type RuntimeEvent: From> + IsType<::RuntimeEvent>; @@ -78,14 +84,18 @@ pub mod pallet { + AtLeast32BitUnsigned + Default + Copy - + MaybeSerializeDeserialize; + + MaybeSerializeDeserialize + + MaxEncodedLen; /// Asset location type - type AssetNativeLocation: Parameter + Member + Default; + type AssetNativeLocation: Parameter + Member + Default + MaxEncodedLen; /// The maximum length of a name or symbol stored on-chain. type StringLimit: Get; + /// The maximum number of assets in a pool + type MaxAssetIdInPool: Get + Clone + Debug + TypeInfo + Eq + PartialEq; + /// Native Asset Id #[pallet::constant] type NativeAssetId: Get; @@ -95,7 +105,6 @@ pub mod pallet { } #[pallet::pallet] - #[pallet::without_storage_info] pub struct Pallet(_); #[pallet::hooks] @@ -127,6 +136,9 @@ pub mod pallet { /// Asset not found in pool AssetNotFoundInPool, + + /// Max number of assets in pool is reached + MaxAssetIdInPoolReached, } #[pallet::storage] @@ -172,8 +184,8 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { - pub asset_names: Vec<(Vec, T::Balance)>, - pub native_asset_name: Vec, + pub asset_names: Vec<(BoundedVec, T::Balance)>, + pub native_asset_name: BoundedVec, pub native_existential_deposit: T::Balance, } @@ -182,7 +194,7 @@ pub mod pallet { fn default() -> Self { GenesisConfig:: { asset_names: vec![], - native_asset_name: b"WEBB".to_vec(), + native_asset_name: b"WEBB".to_vec().try_into().unwrap(), native_existential_deposit: Default::default(), } } @@ -224,14 +236,14 @@ pub mod pallet { Registered { asset_id: T::AssetId, name: BoundedVec, - asset_type: AssetType, + asset_type: AssetTypeOf, }, /// Asset was updated. Updated { asset_id: T::AssetId, name: BoundedVec, - asset_type: AssetType, + asset_type: AssetTypeOf, }, /// Metadata set for an asset. @@ -256,20 +268,19 @@ pub mod pallet { /// /// Emits 'Registered` event when successful. #[pallet::weight(::WeightInfo::register())] + #[pallet::call_index(0)] #[transactional] pub fn register( origin: OriginFor, - name: Vec, - asset_type: AssetType, + name: BoundedVec, + asset_type: AssetTypeOf, existential_deposit: T::Balance, ) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; - let bounded_name = Self::to_bounded_name(name)?; - - ensure!(Self::asset_ids(&bounded_name).is_none(), Error::::AssetAlreadyRegistered); + ensure!(Self::asset_ids(&name).is_none(), Error::::AssetAlreadyRegistered); - Self::register_asset(bounded_name, asset_type, existential_deposit)?; + Self::register_asset(name, asset_type, existential_deposit)?; Ok(()) } @@ -283,12 +294,13 @@ pub mod pallet { // TODO: No tests #[pallet::weight(::WeightInfo::update())] + #[pallet::call_index(1)] #[transactional] pub fn update( origin: OriginFor, asset_id: T::AssetId, - name: Vec, - asset_type: AssetType, + bounded_name: BoundedVec, + asset_type: AssetTypeOf, existential_deposit: Option, ) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; @@ -296,8 +308,6 @@ pub mod pallet { Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { let mut detail = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; - let bounded_name = Self::to_bounded_name(name)?; - if bounded_name != detail.name { // Make sure that there is no such name already registered ensure!( @@ -329,27 +339,26 @@ pub mod pallet { /// /// Emits `MetadataSet` event when successful. #[pallet::weight(::WeightInfo::set_metadata())] + #[pallet::call_index(2)] #[transactional] pub fn set_metadata( origin: OriginFor, asset_id: T::AssetId, - symbol: Vec, + symbol: BoundedVec, decimals: u8, ) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; ensure!(Self::assets(asset_id).is_some(), Error::::AssetNotFound); - let b_symbol = Self::to_bounded_name(symbol)?; - let metadata = AssetMetadata::> { - symbol: b_symbol.clone(), + symbol: symbol.clone(), decimals, }; AssetMetadataMap::::insert(asset_id, metadata); - Self::deposit_event(Event::MetadataSet { asset_id, symbol: b_symbol, decimals }); + Self::deposit_event(Event::MetadataSet { asset_id, symbol, decimals }); Ok(()) } @@ -363,6 +372,7 @@ pub mod pallet { /// /// Emits `LocationSet` event when successful. #[pallet::weight(::WeightInfo::set_location())] + #[pallet::call_index(3)] #[transactional] pub fn set_location( origin: OriginFor, @@ -383,9 +393,10 @@ pub mod pallet { /// Add an asset to an existing pool. #[pallet::weight(0)] + #[pallet::call_index(4)] pub fn add_asset_to_pool( origin: OriginFor, - pool: Vec, + pool: BoundedVec, asset_id: T::AssetId, ) -> DispatchResult { ensure_root(origin)?; @@ -399,9 +410,10 @@ pub mod pallet { /// Remove an asset from an existing pool. #[pallet::weight(0)] + #[pallet::call_index(5)] pub fn delete_asset_from_pool( origin: OriginFor, - pool: Vec, + pool: BoundedVec, asset_id: T::AssetId, ) -> DispatchResult { ensure_root(origin)?; @@ -416,7 +428,7 @@ pub mod pallet { } impl Pallet { - /// Convert Vec to BoundedVec so it respects the max set limit, + /// Convert BoundedVec to BoundedVec so it respects the max set limit, /// otherwise return TooLong error fn to_bounded_name(name: Vec) -> Result, Error> { name.try_into().map_err(|_| Error::::TooLong) @@ -428,7 +440,7 @@ impl Pallet { /// exists. This has to be prior to calling this function. pub fn register_asset( name: BoundedVec, - asset_type: AssetType, + asset_type: AssetTypeOf, existential_deposit: T::Balance, ) -> Result { NextAssetId::::mutate(|value| -> Result { @@ -467,16 +479,14 @@ impl Pallet { /// Create asset for given name or return existing AssetId if such asset /// already exists. pub fn get_or_create_asset( - name: Vec, - asset_type: AssetType, + name: BoundedVec, + asset_type: AssetTypeOf, existential_deposit: T::Balance, ) -> Result { - let bounded_name: BoundedVec = Self::to_bounded_name(name)?; - - if let Some(asset_id) = AssetIds::::get(&bounded_name) { + if let Some(asset_id) = AssetIds::::get(&name) { Ok(asset_id) } else { - Self::register_asset(bounded_name, asset_type, existential_deposit) + Self::register_asset(name, asset_type, existential_deposit) } } @@ -507,7 +517,9 @@ impl Pallet { if !pool.contains(&asset_id) { if Self::assets(asset_id).is_some() { let mut pool_clone = pool.clone(); - pool_clone.push(asset_id); + pool_clone + .try_push(asset_id) + .map_err(|_| Error::::MaxAssetIdInPoolReached)?; AssetType::PoolShare(pool_clone) } else { return Err(Error::::AssetNotRegistered.into()) @@ -550,7 +562,12 @@ impl Pallet { .filter(|id| **id != asset_id) .copied() .collect::>(); - AssetType::PoolShare(filtered_pool) + let bounded_pool = + BoundedVec::::try_from( + filtered_pool, + ) + .map_err(|_| Error::::MaxAssetIdInPoolReached)?; + AssetType::PoolShare(bounded_pool) } else { return Err(Error::::AssetNotFoundInPool.into()) }, @@ -575,6 +592,7 @@ impl Pallet { Vec, T::Balance, BoundedVec, + ::MaxAssetIdInPool, DispatchError, >>::contains_asset(pool_share_id, asset_id) } @@ -585,7 +603,8 @@ impl T::AssetId, Vec, T::Balance, - BoundedVec::StringLimit>, + BoundedVec, + ::MaxAssetIdInPool, DispatchError, > for Pallet { @@ -613,7 +632,8 @@ impl name: &Vec, existential_deposit: T::Balance, ) -> Result { - Self::get_or_create_asset(name.clone(), AssetType::Token, existential_deposit) + let bounded_name = Self::to_bounded_name(name.clone())?; + Self::get_or_create_asset(bounded_name, AssetType::Token, existential_deposit) } } @@ -622,7 +642,8 @@ impl T::AssetId, Vec, T::Balance, - BoundedVec::StringLimit>, + BoundedVec, + ::MaxAssetIdInPool, DispatchError, > for Pallet { @@ -638,9 +659,12 @@ impl assets: &[T::AssetId], existential_deposit: T::Balance, ) -> Result { + let bounded_name = Self::to_bounded_name(name.clone())?; + let bounded_pool = BoundedVec::::try_from(assets.to_vec()) + .map_err(|_| Error::::MaxAssetIdInPoolReached)?; Self::get_or_create_asset( - name.clone(), - AssetType::PoolShare(assets.to_vec()), + bounded_name, + AssetType::PoolShare(bounded_pool), existential_deposit, ) } diff --git a/pallets/asset-registry/src/mock.rs b/pallets/asset-registry/src/mock.rs index b40573190..74e20e83b 100644 --- a/pallets/asset-registry/src/mock.rs +++ b/pallets/asset-registry/src/mock.rs @@ -21,7 +21,7 @@ use frame_support::{ traits::{Everything, GenesisBuild}, }; use frame_system as system; -use polkadot_xcm::v0::MultiLocation; +use polkadot_xcm::v1::MultiLocation; use scale_info::TypeInfo; use sp_core::H256; use sp_runtime::{ @@ -31,7 +31,7 @@ use sp_runtime::{ use sp_std::convert::{TryFrom, TryInto}; use webb_primitives::{AssetId, Balance}; -use crate::{self as asset_registry, Config}; +use crate::{self as asset_registry, BoundedVec, Config}; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -84,13 +84,12 @@ impl system::Config for Test { use codec::{Decode, Encode}; -#[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, TypeInfo)] +#[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, TypeInfo, codec::MaxEncodedLen, Default)] pub struct AssetLocation(pub MultiLocation); -impl Default for AssetLocation { - fn default() -> Self { - AssetLocation(MultiLocation::Null) - } +parameter_types! { + #[derive(Copy, Clone, Debug, PartialEq, Eq, TypeInfo)] + pub const MaxAssetIdInPool: u32 = 100; } impl Config for Test { @@ -99,6 +98,7 @@ impl Config for Test { type Balance = Balance; type RuntimeEvent = RuntimeEvent; type NativeAssetId = NativeAssetId; + type MaxAssetIdInPool = MaxAssetIdInPool; type RegistryOrigin = frame_system::EnsureRoot; type StringLimit = RegistryStringLimit; type WeightInfo = (); @@ -107,13 +107,18 @@ pub type AssetRegistryPallet = crate::Pallet; #[derive(Default)] pub struct ExtBuilder { - assets: Vec<(Vec, Balance)>, + assets: Vec<(BoundedVec, Balance)>, native_asset_name: Option>, } impl ExtBuilder { pub fn with_assets(mut self, assets: Vec<(Vec, Balance)>) -> Self { - self.assets = assets; + let mut bounded_assets: Vec<(BoundedVec, Balance)> = + Default::default(); + for asset in assets { + bounded_assets.push((asset.0.try_into().unwrap(), asset.1)); + } + self.assets = bounded_assets; self } @@ -128,7 +133,7 @@ impl ExtBuilder { if let Some(name) = self.native_asset_name { crate::GenesisConfig:: { asset_names: self.assets, - native_asset_name: name, + native_asset_name: name.try_into().unwrap(), native_existential_deposit: 1_000_000u128, } } else { diff --git a/pallets/asset-registry/src/tests.rs b/pallets/asset-registry/src/tests.rs index a18a0a378..b564b7f4c 100644 --- a/pallets/asset-registry/src/tests.rs +++ b/pallets/asset-registry/src/tests.rs @@ -21,9 +21,9 @@ use crate::{ types::{AssetDetails, AssetMetadata, AssetType}, ShareTokenRegistry, }; -use codec::Encode; + use frame_support::{assert_noop, assert_ok, BoundedVec}; -use polkadot_xcm::v0::{Junction::*, MultiLocation::*}; +use polkadot_xcm::{opaque::latest::Junctions, v1::MultiLocation}; use sp_runtime::DispatchError; use sp_std::convert::TryInto; use webb_primitives::{AssetId, Balance}; @@ -31,25 +31,25 @@ use webb_primitives::{AssetId, Balance}; #[test] fn register_asset_works() { new_test_ext().execute_with(|| { - let too_long = [1u8; ::StringLimit::get() as usize + 1]; + // let too_long = [1u8; ::StringLimit::get() as usize + 1]; let ed = 1_000_000u128; - assert_noop!( - AssetRegistryPallet::register( - RuntimeOrigin::root(), - too_long.to_vec(), - AssetType::Token, - ed - ), - Error::::TooLong - ); + // assert_noop!( + // AssetRegistryPallet::register( + // RuntimeOrigin::root(), + // too_long.to_vec().try_into().unwrap(), + // AssetType::Token, + // ed + // ), + // Error::::TooLong + // ); let name: Vec = b"HDX".to_vec(); assert_ok!(AssetRegistryPallet::register( RuntimeOrigin::root(), - name.clone(), + name.clone().try_into().unwrap(), AssetType::Token, ed )); @@ -68,7 +68,12 @@ fn register_asset_works() { ); assert_noop!( - AssetRegistryPallet::register(RuntimeOrigin::root(), name, AssetType::Token, ed), + AssetRegistryPallet::register( + RuntimeOrigin::root(), + name.try_into().unwrap(), + AssetType::Token, + ed + ), Error::::AssetAlreadyRegistered ); }); @@ -79,20 +84,35 @@ fn create_asset() { new_test_ext().execute_with(|| { let ed = 1_000_000u128; - assert_ok!(AssetRegistryPallet::get_or_create_asset(b"HDX".to_vec(), AssetType::Token, ed)); + assert_ok!(AssetRegistryPallet::get_or_create_asset( + b"HDX".to_vec().try_into().unwrap(), + AssetType::Token, + ed + )); - let dot_asset = - AssetRegistryPallet::get_or_create_asset(b"DOT".to_vec(), AssetType::Token, ed); + let dot_asset = AssetRegistryPallet::get_or_create_asset( + b"DOT".to_vec().try_into().unwrap(), + AssetType::Token, + ed, + ); assert_ok!(dot_asset); let dot_asset_id = dot_asset.ok().unwrap(); - assert_ok!(AssetRegistryPallet::get_or_create_asset(b"BTC".to_vec(), AssetType::Token, ed)); + assert_ok!(AssetRegistryPallet::get_or_create_asset( + b"BTC".to_vec().try_into().unwrap(), + AssetType::Token, + ed + )); let current_asset_id = AssetRegistryPallet::next_asset_id(); // Existing asset should return previously created one. assert_ok!( - AssetRegistryPallet::get_or_create_asset(b"DOT".to_vec(), AssetType::Token, ed), + AssetRegistryPallet::get_or_create_asset( + b"DOT".to_vec().try_into().unwrap(), + AssetType::Token, + ed + ), dot_asset_id ); @@ -112,18 +132,25 @@ fn create_asset() { #[test] fn location_mapping_works() { new_test_ext().execute_with(|| { - let bn = AssetRegistryPallet::to_bounded_name(b"HDX".to_vec()).unwrap(); + let bn = AssetRegistryPallet::to_bounded_name(b"HDX".to_vec().try_into().unwrap()).unwrap(); let ed = 1_000_000u128; - assert_ok!(AssetRegistryPallet::get_or_create_asset(b"HDX".to_vec(), AssetType::Token, ed)); - let asset_id: AssetId = - AssetRegistryPallet::get_or_create_asset(b"HDX".to_vec(), AssetType::Token, ed) - .unwrap(); + assert_ok!(AssetRegistryPallet::get_or_create_asset( + b"HDX".to_vec().try_into().unwrap(), + AssetType::Token, + ed + )); + let asset_id: AssetId = AssetRegistryPallet::get_or_create_asset( + b"HDX".to_vec().try_into().unwrap(), + AssetType::Token, + ed, + ) + .unwrap(); crate::Assets::::insert( asset_id, - AssetDetails::> { + AssetDetails::, MaxAssetIdInPool> { name: bn, asset_type: AssetType::Token, existential_deposit: ed, @@ -131,11 +158,7 @@ fn location_mapping_works() { }, ); - let asset_location = AssetLocation(X3( - Parent, - Parachain(200), - GeneralKey(asset_id.encode().try_into().unwrap()), - )); + let asset_location = AssetLocation(MultiLocation { parents: 1, interior: Junctions::Here }); assert_ok!(AssetRegistryPallet::set_location( RuntimeOrigin::root(), @@ -151,7 +174,7 @@ fn location_mapping_works() { #[test] fn genesis_config_works() { ExtBuilder::default() - .with_native_asset_name(b"NATIVE".to_vec()) + .with_native_asset_name(b"NATIVE".to_vec().try_into().unwrap()) .build() .execute_with(|| { let native: BoundedVec::StringLimit> = @@ -159,7 +182,7 @@ fn genesis_config_works() { assert_eq!(AssetRegistryPallet::asset_ids(native).unwrap(), 0u32); }); ExtBuilder::default() - .with_assets(vec![(b"ONE".to_vec(), 1_000u128)]) + .with_assets(vec![(b"ONE".to_vec().try_into().unwrap(), 1_000u128)]) .build() .execute_with(|| { let native: BoundedVec::StringLimit> = @@ -200,7 +223,7 @@ fn set_metadata_works() { assert_ok!(AssetRegistryPallet::set_metadata( RuntimeOrigin::root(), dot_id, - b"xDOT".to_vec(), + b"xDOT".to_vec().try_into().unwrap(), 12u8 )); @@ -212,7 +235,7 @@ fn set_metadata_works() { assert_ok!(AssetRegistryPallet::set_metadata( RuntimeOrigin::root(), dot_id, - b"xDOT".to_vec(), + b"xDOT".to_vec().try_into().unwrap(), 30u8 )); @@ -221,21 +244,21 @@ fn set_metadata_works() { AssetMetadata { decimals: 30u8, symbol: b_symbol } ); - assert_noop!( - AssetRegistryPallet::set_metadata( - RuntimeOrigin::root(), - dot_id, - b"JUST_TOO_LONG".to_vec(), - 30u8 - ), - Error::::TooLong - ); + // assert_noop!( + // AssetRegistryPallet::set_metadata( + // RuntimeOrigin::root(), + // dot_id, + // b"JUST_TOO_LONG".to_vec().try_into().unwrap(), + // 30u8 + // ), + // Error::::TooLong + // ); assert_noop!( AssetRegistryPallet::set_metadata( RuntimeOrigin::root(), 100, - b"NONE".to_vec(), + b"NONE".to_vec().try_into().unwrap(), 30u8 ), Error::::AssetNotFound @@ -248,12 +271,18 @@ fn update_asset() { new_test_ext().execute_with(|| { let ed = 1_000_000u128; - let btc_asset_id: AssetId = - AssetRegistryPallet::get_or_create_asset(b"BTC".to_vec(), AssetType::Token, ed) - .unwrap(); - let usd_asset_id: AssetId = - AssetRegistryPallet::get_or_create_asset(b"USD".to_vec(), AssetType::Token, ed) - .unwrap(); + let btc_asset_id: AssetId = AssetRegistryPallet::get_or_create_asset( + b"BTC".to_vec().try_into().unwrap(), + AssetType::Token, + ed, + ) + .unwrap(); + let usd_asset_id: AssetId = AssetRegistryPallet::get_or_create_asset( + b"USD".to_vec().try_into().unwrap(), + AssetType::Token, + ed, + ) + .unwrap(); let next_asset_id = AssetRegistryPallet::next_asset_id(); @@ -261,7 +290,7 @@ fn update_asset() { assert_ok!(AssetRegistryPallet::update( RuntimeOrigin::root(), btc_asset_id, - b"superBTC".to_vec(), + b"superBTC".to_vec().try_into().unwrap(), AssetType::Token, None )); @@ -286,7 +315,7 @@ fn update_asset() { (AssetRegistryPallet::update( RuntimeOrigin::root(), usd_asset_id, - b"superBTC".to_vec(), + b"superBTC".to_vec().try_into().unwrap(), AssetType::Token, None )), @@ -298,7 +327,7 @@ fn update_asset() { (AssetRegistryPallet::update( RuntimeOrigin::root(), next_asset_id, - b"VOID".to_vec(), + b"VOID".to_vec().try_into().unwrap(), AssetType::Token, None )), @@ -310,8 +339,8 @@ fn update_asset() { assert_ok!(AssetRegistryPallet::update( RuntimeOrigin::root(), btc_asset_id, - b"BTCUSD".to_vec(), - AssetType::PoolShare(vec![btc_asset_id, usd_asset_id]), + b"BTCUSD".to_vec().try_into().unwrap(), + AssetType::PoolShare(vec![btc_asset_id, usd_asset_id].try_into().unwrap()), None )); @@ -319,8 +348,8 @@ fn update_asset() { assert_ok!(AssetRegistryPallet::update( RuntimeOrigin::root(), btc_asset_id, - b"BTCUSD".to_vec(), - AssetType::PoolShare(vec![btc_asset_id, usd_asset_id]), + b"BTCUSD".to_vec().try_into().unwrap(), + AssetType::PoolShare(vec![btc_asset_id, usd_asset_id].try_into().unwrap()), Some(1_234_567u128) )); @@ -330,7 +359,9 @@ fn update_asset() { AssetRegistryPallet::assets(btc_asset_id).unwrap(), AssetDetails { name: btcusd, - asset_type: AssetType::PoolShare(vec![btc_asset_id, usd_asset_id]), + asset_type: AssetType::PoolShare( + vec![btc_asset_id, usd_asset_id].try_into().unwrap() + ), existential_deposit: 1_234_567u128, locked: false } @@ -341,7 +372,7 @@ fn update_asset() { assert_ok!(AssetRegistryPallet::update( RuntimeOrigin::root(), btc_asset_id, - b"superBTC".to_vec(), + b"superBTC".to_vec().try_into().unwrap(), AssetType::Token, None )); @@ -380,14 +411,14 @@ fn add_asset_to_pool() { let pool_share_id = Registry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![first_token_id]), + AssetType::PoolShare(vec![first_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); assert_ok!(Registry::add_asset_to_pool( RuntimeOrigin::root(), - b"meme".to_vec(), + b"meme".to_vec().try_into().unwrap(), second_token_id )); @@ -396,6 +427,7 @@ fn add_asset_to_pool() { Vec, ::Balance, BoundedVec::StringLimit>, + MaxAssetIdInPool, DispatchError, >>::contains_asset(pool_share_id, second_token_id)) }) @@ -420,14 +452,14 @@ fn delete_asset_from_pool() { let pool_share_id = Registry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![first_token_id, second_token_id]), + AssetType::PoolShare(vec![first_token_id, second_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); assert_ok!(Registry::delete_asset_from_pool( RuntimeOrigin::root(), - b"meme".to_vec(), + b"meme".to_vec().try_into().unwrap(), second_token_id )); @@ -436,6 +468,7 @@ fn delete_asset_from_pool() { Vec, ::Balance, BoundedVec::StringLimit>, + MaxAssetIdInPool, DispatchError, >>::contains_asset(pool_share_id, second_token_id),) }) diff --git a/pallets/asset-registry/src/traits.rs b/pallets/asset-registry/src/traits.rs index 880303777..3499c21e5 100644 --- a/pallets/asset-registry/src/traits.rs +++ b/pallets/asset-registry/src/traits.rs @@ -1,7 +1,18 @@ use crate::*; +use frame_support::dispatch::fmt::Debug; -pub trait Registry { - fn get_by_id(id: AssetId) -> Result, Error>; +pub trait Registry< + AssetId, + AssetName, + Balance, + BoundedString, + MaxAssetIdInPool: Get + Clone + Debug + Eq + PartialEq, + Error, +> +{ + fn get_by_id( + id: AssetId, + ) -> Result, Error>; fn exists(name: AssetId) -> bool; @@ -21,8 +32,14 @@ pub trait Registry { } } -pub trait ShareTokenRegistry: - Registry +pub trait ShareTokenRegistry< + AssetId, + AssetName, + Balance, + BoundedString, + MaxAssetIdInPool: Get + Clone + Debug + Eq + PartialEq, + Error, +>: Registry { fn retrieve_shared_asset(name: &AssetName, assets: &[AssetId]) -> Result; diff --git a/pallets/asset-registry/src/types.rs b/pallets/asset-registry/src/types.rs index ae10b26da..55a0d3de8 100644 --- a/pallets/asset-registry/src/types.rs +++ b/pallets/asset-registry/src/types.rs @@ -1,31 +1,35 @@ -use frame_support::pallet_prelude::*; +use frame_support::{dispatch::fmt::Debug, pallet_prelude::*, BoundedVec}; use scale_info::TypeInfo; -use sp_std::vec::Vec; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; -#[derive(Encode, Decode, Eq, PartialEq, Clone, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Eq, PartialEq, Clone, RuntimeDebug, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub enum AssetType { +pub enum AssetType + Clone + Debug + Eq + PartialEq> { Token, - PoolShare(Vec), + PoolShare(BoundedVec), } -#[derive(Encode, Decode, Eq, PartialEq, Clone, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Eq, PartialEq, Clone, RuntimeDebug, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct AssetDetails { +pub struct AssetDetails< + AssetId, + Balance, + BoundedString, + MaxAssetIdInPool: Get + Clone + Debug + Eq + PartialEq, +> { /// The name of this asset. Limited in length by `StringLimit`. pub name: BoundedString, - pub asset_type: AssetType, + pub asset_type: AssetType, pub existential_deposit: Balance, pub locked: bool, } -#[derive(Clone, Encode, Decode, Eq, PartialEq, Default, RuntimeDebug, TypeInfo)] +#[derive(Clone, Encode, Decode, Eq, PartialEq, Default, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct AssetMetadata { /// The ticker symbol for this asset. Limited in length by `StringLimit`. pub symbol: BoundedString, diff --git a/pallets/hasher/src/lib.rs b/pallets/hasher/src/lib.rs index 00d9ce4c8..3d2b60b38 100644 --- a/pallets/hasher/src/lib.rs +++ b/pallets/hasher/src/lib.rs @@ -60,7 +60,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -77,6 +77,9 @@ pub mod pallet { /// privileged attributes. type ForceOrigin: EnsureOrigin; + /// The max parameter length accepted by the hasher + type MaxParameterLength: Get; + /// Weightinfo for pallet. type WeightInfo: WeightInfo; } @@ -84,7 +87,7 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig, I: 'static = ()> { pub phantom: (PhantomData, PhantomData), - pub parameters: Option>, + pub parameters: Option>, } #[cfg(feature = "std")] @@ -107,7 +110,7 @@ pub mod pallet { #[pallet::getter(fn parameters)] /// Details of the module's parameters pub(super) type Parameters, I: 'static = ()> = - StorageValue<_, Vec, ValueQuery>; + StorageValue<_, BoundedVec, ValueQuery>; #[pallet::event] pub enum Event, I: 'static = ()> {} @@ -126,9 +129,10 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { #[pallet::weight(T::WeightInfo::force_set_parameters(parameters.len() as u32))] + #[pallet::call_index(0)] pub fn force_set_parameters( origin: OriginFor, - parameters: Vec, + parameters: BoundedVec, ) -> DispatchResultWithPostInfo { T::ForceOrigin::ensure_origin(origin)?; Parameters::::try_mutate(|params| { diff --git a/pallets/hasher/src/mock.rs b/pallets/hasher/src/mock.rs index 1d13d651b..200e03854 100644 --- a/pallets/hasher/src/mock.rs +++ b/pallets/hasher/src/mock.rs @@ -6,7 +6,7 @@ use frame_system as system; use sp_core::H256; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, ConstU32, IdentityLookup}, }; use sp_std::convert::{TryFrom, TryInto}; pub use webb_primitives::hasher::{HasherModule, InstanceHasher}; @@ -87,6 +87,7 @@ impl pallet_hasher::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; type Hasher = webb_primitives::hashing::ArkworksPoseidonHasherBn254; + type MaxParameterLength = ConstU32<10000>; type WeightInfo = (); } diff --git a/pallets/hasher/src/tests.rs b/pallets/hasher/src/tests.rs index 299727814..e3432f98f 100644 --- a/pallets/hasher/src/tests.rs +++ b/pallets/hasher/src/tests.rs @@ -23,8 +23,10 @@ fn should_initialize_parameters() { new_test_ext().execute_with(|| { let curve = Curve::Bn254; let params = setup_params::(curve, 5, 3); - let res = - DefaultPalletHasher::force_set_parameters(RuntimeOrigin::root(), params.to_bytes()); + let res = DefaultPalletHasher::force_set_parameters( + RuntimeOrigin::root(), + params.to_bytes().try_into().unwrap(), + ); assert_ok!(res); }); } @@ -34,8 +36,10 @@ fn should_output_correct_hash() { new_test_ext().execute_with(|| { let curve = Curve::Bn254; let params = setup_params::(curve, 5, 3); - let res = - DefaultPalletHasher::force_set_parameters(RuntimeOrigin::root(), params.to_bytes()); + let res = DefaultPalletHasher::force_set_parameters( + RuntimeOrigin::root(), + params.to_bytes().try_into().unwrap(), + ); assert_ok!(res); let left = Fr::one().into_repr().to_bytes_be(); // one let right = Fr::one().double().into_repr().to_bytes_be(); // two @@ -53,8 +57,10 @@ fn should_build_the_same_merkle_tree_solidity() { new_test_ext().execute_with(|| { let curve = Curve::Bn254; let params = setup_params::(curve, 5, 3); - let res = - DefaultPalletHasher::force_set_parameters(RuntimeOrigin::root(), params.to_bytes()); + let res = DefaultPalletHasher::force_set_parameters( + RuntimeOrigin::root(), + params.to_bytes().try_into().unwrap(), + ); assert_ok!(res); let solidity_merkle_tree_hashes = vec![ hex!("2fe54c60d3acabf3343a35b6eba15db4821b340f76e741e2249685ed4899af6c"), diff --git a/pallets/key-storage/src/lib.rs b/pallets/key-storage/src/lib.rs index 35dbf43b6..d911c8987 100644 --- a/pallets/key-storage/src/lib.rs +++ b/pallets/key-storage/src/lib.rs @@ -28,8 +28,11 @@ mod mock; pub mod tests; pub mod weights; -use frame_support::pallet_prelude::DispatchError; -use sp_std::{convert::TryInto, prelude::*}; +use frame_support::{pallet_prelude::DispatchError, BoundedVec}; +use sp_std::{ + convert::{TryFrom, TryInto}, + prelude::*, +}; use webb_primitives::traits::key_storage::*; pub use pallet::*; @@ -43,7 +46,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -53,6 +56,12 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; + /// The max length accepted for Pubkey + type MaxPubkeyLength: Get; + + /// The max number of pubkey owneres we can store + type MaxPubKeyOwners: Get; + /// Weightinfo for pallet. type WeightInfo: WeightInfo; } @@ -77,18 +86,27 @@ pub mod pallet { /// The map of owners to public keys #[pallet::storage] #[pallet::getter(fn public_key_owners)] - pub type PublicKeyOwners, I: 'static = ()> = - StorageValue<_, Vec<(T::AccountId, Vec)>, ValueQuery>; + pub type PublicKeyOwners, I: 'static = ()> = StorageValue< + _, + BoundedVec<(T::AccountId, BoundedVec), T::MaxPubKeyOwners>, + ValueQuery, + >; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event, I: 'static = ()> { /// Public key registration - PublicKeyRegistration { owner: T::AccountId, public_key: Vec }, + PublicKeyRegistration { + owner: T::AccountId, + public_key: BoundedVec, + }, } #[pallet::error] - pub enum Error {} + pub enum Error { + PubKeyOutOfBounds, + MaxPubkeyOwnersExceeded, + } #[pallet::hooks] impl, I: 'static> Hooks> for Pallet {} @@ -96,13 +114,17 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { #[pallet::weight(T::WeightInfo::register(public_key.len() as u32))] + #[pallet::call_index(0)] pub fn register( origin: OriginFor, owner: T::AccountId, - public_key: Vec, + public_key: BoundedVec, ) -> DispatchResultWithPostInfo { ensure_signed(origin)?; - >::register(owner.clone(), public_key.clone())?; + >::register( + owner.clone(), + public_key.clone().into_inner(), + )?; Self::deposit_event(Event::PublicKeyRegistration { owner, public_key }); Ok(().into()) } @@ -111,8 +133,12 @@ pub mod pallet { impl, I: 'static> KeyStorageInterface for Pallet { fn register(owner: T::AccountId, public_key: Vec) -> Result<(), DispatchError> { + let bounded_public_key = BoundedVec::::try_from(public_key.clone()) + .map_err(|_e| Error::::PubKeyOutOfBounds)?; let mut public_key_owners = >::get(); - public_key_owners.push((owner.clone(), public_key.clone())); + public_key_owners + .try_push((owner.clone(), bounded_public_key)) + .map_err(|_e| Error::::MaxPubkeyOwnersExceeded)?; #[cfg(feature = "std")] { println!("Registered public key with owner: {owner:?}, {public_key:?}"); diff --git a/pallets/key-storage/src/mock.rs b/pallets/key-storage/src/mock.rs index 5296fc94e..6d2b3c666 100644 --- a/pallets/key-storage/src/mock.rs +++ b/pallets/key-storage/src/mock.rs @@ -6,7 +6,7 @@ use frame_system as system; use sp_core::H256; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, ConstU32, IdentityLookup}, }; use sp_std::convert::{TryFrom, TryInto}; use webb_primitives::AccountId; @@ -71,6 +71,8 @@ parameter_types! { impl pallet_key_storage::Config for Test { type RuntimeEvent = RuntimeEvent; + type MaxPubkeyLength = ConstU32<100>; + type MaxPubKeyOwners = ConstU32<100>; type WeightInfo = (); } diff --git a/pallets/key-storage/src/tests.rs b/pallets/key-storage/src/tests.rs index b26edb5a9..29668520a 100644 --- a/pallets/key-storage/src/tests.rs +++ b/pallets/key-storage/src/tests.rs @@ -9,7 +9,11 @@ fn should_register_public_key_with_owner() { new_test_ext().execute_with(|| { let owner = account::("", 0, 0); let public_key = [0u8; 32].to_vec(); - let res = KeyStorage::register(RuntimeOrigin::signed(owner.clone()), owner, public_key); + let res = KeyStorage::register( + RuntimeOrigin::signed(owner.clone()), + owner, + public_key.try_into().unwrap(), + ); assert_ok!(res); }); } diff --git a/pallets/linkable-tree/src/lib.rs b/pallets/linkable-tree/src/lib.rs index 2478650bf..650807c8f 100644 --- a/pallets/linkable-tree/src/lib.rs +++ b/pallets/linkable-tree/src/lib.rs @@ -77,7 +77,7 @@ mod benchmarking; use sp_std::convert::TryInto; pub mod types; pub mod weights; -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ensure, pallet_prelude::DispatchError, traits::Get}; use sp_runtime::traits::{AtLeast32Bit, One, Saturating, Zero}; use sp_std::prelude::*; @@ -100,7 +100,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -118,7 +118,8 @@ pub mod pallet { + Default + Copy + From - + From; + + From + + MaxEncodedLen; /// ChainID type for this chain #[pallet::constant] @@ -215,6 +216,7 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { #[pallet::weight(>::WeightInfo::create(*depth as u32, *max_edges))] + #[pallet::call_index(0)] pub fn create( origin: OriginFor, max_edges: u32, diff --git a/pallets/linkable-tree/src/mock.rs b/pallets/linkable-tree/src/mock.rs index 137f688b6..73546a3e5 100644 --- a/pallets/linkable-tree/src/mock.rs +++ b/pallets/linkable-tree/src/mock.rs @@ -5,12 +5,14 @@ use crate as pallet_linkable_tree; use codec::{Decode, Encode}; use sp_core::H256; +use codec::MaxEncodedLen; use frame_support::parameter_types; use frame_system as system; +use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, ConstU32, IdentityLookup}, }; use sp_std::convert::{TryFrom, TryInto}; pub use webb_primitives::{ @@ -106,6 +108,7 @@ impl pallet_hasher::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; type Hasher = webb_primitives::hashing::ArkworksPoseidonHasherBn254; + type MaxParameterLength = ConstU32<10000>; type WeightInfo = (); } @@ -135,6 +138,7 @@ parameter_types! { scale_info::TypeInfo, Serialize, Deserialize, + MaxEncodedLen, )] pub struct Element([u8; 32]); @@ -150,12 +154,21 @@ impl ElementTrait for Element { } } +parameter_types! { + #[derive(Debug, TypeInfo)] + pub const MaxEdges: u32 = 1000; + #[derive(Debug, TypeInfo)] + pub const MaxDefaultHashes: u32 = 1000; +} + impl pallet_mt::Config for Test { type Currency = Balances; type DataDepositBase = LeafDepositBase; type DataDepositPerByte = LeafDepositPerByte; type DefaultZeroElement = DefaultZeroElement; type Element = Element; + type MaxEdges = MaxEdges; + type MaxDefaultHashes = MaxDefaultHashes; type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; type Hasher = HasherPallet; diff --git a/pallets/linkable-tree/src/tests.rs b/pallets/linkable-tree/src/tests.rs index 5bfead12f..99aa9958e 100644 --- a/pallets/linkable-tree/src/tests.rs +++ b/pallets/linkable-tree/src/tests.rs @@ -18,7 +18,10 @@ fn should_create_new_linkable_tree() { new_test_ext().execute_with(|| { let curve = Curve::Bn254; let params = setup_params::(curve, 5, 3); - let _res = HasherPallet::force_set_parameters(RuntimeOrigin::root(), params.to_bytes()); + let _res = HasherPallet::force_set_parameters( + RuntimeOrigin::root(), + params.to_bytes().try_into().unwrap(), + ); let max_edges = M as _; let depth = TREE_DEPTH as u8; @@ -58,7 +61,10 @@ fn should_be_able_to_add_neighbors_and_check_history() { new_test_ext().execute_with(|| { let curve = Curve::Bn254; let params = setup_params::(curve, 5, 3); - let _res = HasherPallet::force_set_parameters(RuntimeOrigin::root(), params.to_bytes()); + let _res = HasherPallet::force_set_parameters( + RuntimeOrigin::root(), + params.to_bytes().try_into().unwrap(), + ); let max_edges = M as _; let depth = TREE_DEPTH as u8; diff --git a/pallets/linkable-tree/src/types.rs b/pallets/linkable-tree/src/types.rs index 4054f2ac7..2a94590b1 100644 --- a/pallets/linkable-tree/src/types.rs +++ b/pallets/linkable-tree/src/types.rs @@ -1,13 +1,13 @@ //! All the traits exposed to be used in other custom pallets use crate::*; -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use webb_primitives::webb_proposals::ResourceId; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; -#[derive(Clone, Encode, Decode, Eq, PartialEq, Default, Debug, TypeInfo)] +#[derive(Clone, Encode, Decode, Eq, PartialEq, Default, Debug, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct EdgeMetadata { /// chain id diff --git a/pallets/mixer/src/lib.rs b/pallets/mixer/src/lib.rs index c80451067..140f2c41e 100644 --- a/pallets/mixer/src/lib.rs +++ b/pallets/mixer/src/lib.rs @@ -101,7 +101,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -228,6 +228,7 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { #[pallet::weight(>::WeightInfo::create(*depth as u32))] + #[pallet::call_index(0)] pub fn create( origin: OriginFor, deposit_size: BalanceOf, @@ -243,6 +244,7 @@ pub mod pallet { #[transactional] #[pallet::weight(>::WeightInfo::deposit())] + #[pallet::call_index(1)] pub fn deposit( origin: OriginFor, tree_id: T::TreeId, @@ -256,6 +258,7 @@ pub mod pallet { #[transactional] #[pallet::weight(>::WeightInfo::withdraw())] + #[pallet::call_index(2)] pub fn withdraw( origin: OriginFor, id: T::TreeId, diff --git a/pallets/mixer/src/mock.rs b/pallets/mixer/src/mock.rs index b453def13..b4b7c1844 100644 --- a/pallets/mixer/src/mock.rs +++ b/pallets/mixer/src/mock.rs @@ -10,10 +10,11 @@ use webb_primitives::verifying::ArkworksVerifierBn254; use frame_support::{parameter_types, traits::Nothing}; use frame_system as system; use orml_currencies::{BasicCurrencyAdapter, NativeCurrencyOf}; +use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, ConstU32, IdentityLookup}, }; use sp_std::convert::{TryFrom, TryInto}; pub use webb_primitives::hasher::{HasherModule, InstanceHasher}; @@ -100,6 +101,7 @@ parameter_types! { impl pallet_hasher::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; + type MaxParameterLength = ConstU32<10000>; type Hasher = webb_primitives::hashing::ArkworksPoseidonHasherBn254; type WeightInfo = (); } @@ -130,6 +132,7 @@ parameter_types! { scale_info::TypeInfo, Deserialize, Serialize, + codec::MaxEncodedLen, )] pub struct Element([u8; 32]); @@ -145,12 +148,21 @@ impl ElementTrait for Element { } } +parameter_types! { + #[derive(Debug, TypeInfo)] + pub const MaxEdges: u32 = 1000; + #[derive(Debug, TypeInfo)] + pub const MaxDefaultHashes: u32 = 1000; +} + impl pallet_mt::Config for Test { type Currency = Balances; type DataDepositBase = LeafDepositBase; type DataDepositPerByte = LeafDepositPerByte; type DefaultZeroElement = DefaultZeroElement; type Element = Element; + type MaxEdges = MaxEdges; + type MaxDefaultHashes = MaxDefaultHashes; type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; type Hasher = HasherPallet; @@ -168,6 +180,7 @@ impl pallet_mt::Config for Test { impl pallet_verifier::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; + type MaxParameterLength = ConstU32<10000>; type Verifier = ArkworksVerifierBn254; type WeightInfo = (); } @@ -183,12 +196,18 @@ pub type AssetId = u32; pub type Amount = i128; pub type Balance = u128; +parameter_types! { + #[derive(Debug, TypeInfo, PartialEq, Clone, Eq)] + pub const MaxAssetIdInPool: u32 = 1000; +} + impl pallet_asset_registry::Config for Test { type AssetId = webb_primitives::AssetId; type AssetNativeLocation = (); - type Balance = u128; + type Balance = Balance; type RuntimeEvent = RuntimeEvent; - type NativeAssetId = NativeAssetId; + type NativeAssetId = NativeCurrencyId; + type MaxAssetIdInPool = MaxAssetIdInPool; type RegistryOrigin = frame_system::EnsureRoot; type StringLimit = RegistryStringLimit; type WeightInfo = (); @@ -239,8 +258,8 @@ pub fn new_test_ext() -> sp_io::TestExternalities { use sp_runtime::traits::Zero; let mut storage = system::GenesisConfig::default().build_storage::().unwrap(); pallet_asset_registry::GenesisConfig:: { - asset_names: vec![], - native_asset_name: b"UNIT".to_vec(), + asset_names: Default::default(), + native_asset_name: b"UNIT".to_vec().try_into().unwrap(), native_existential_deposit: Zero::zero(), } .assimilate_storage(&mut storage) diff --git a/pallets/mixer/src/tests.rs b/pallets/mixer/src/tests.rs index dd983c047..256644b4d 100644 --- a/pallets/mixer/src/tests.rs +++ b/pallets/mixer/src/tests.rs @@ -2,11 +2,11 @@ use arkworks_setups::{common::setup_params, Curve}; use codec::Encode; use frame_benchmarking::account; use frame_support::{assert_err, assert_ok, traits::OnInitialize}; -use sp_runtime::traits::{One, Zero}; -use webb_primitives::{merkle_tree::TreeInspector, AccountId, ElementTrait}; - use orml_traits::MultiCurrency; use pallet_asset_registry::AssetType; +use sp_runtime::traits::{One, Zero}; +use sp_std::convert::TryInto; +use webb_primitives::{merkle_tree::TreeInspector, AccountId, ElementTrait}; use crate::{mock::*, test_utils::*}; @@ -35,7 +35,10 @@ fn setup_environment(curve: Curve) -> Vec { let params3 = hasher_params(); // 1. Setup The Hasher Pallet. - assert_ok!(HasherPallet::force_set_parameters(RuntimeOrigin::root(), params3)); + assert_ok!(HasherPallet::force_set_parameters( + RuntimeOrigin::root(), + params3.try_into().unwrap() + )); // 2. Initialize MerkleTree pallet. >::on_initialize(1); // 3. Setup the VerifierPallet @@ -48,7 +51,7 @@ fn setup_environment(curve: Curve) -> Vec { assert_ok!(VerifierPallet::force_set_parameters( RuntimeOrigin::root(), - vk_bytes.to_vec() + vk_bytes.to_vec().try_into().unwrap() )); // finally return the provingkey bytes @@ -64,7 +67,10 @@ fn setup_environment(curve: Curve) -> Vec { fn should_create_new_mixer() { new_test_ext().execute_with(|| { // init hasher pallet first. - assert_ok!(HasherPallet::force_set_parameters(RuntimeOrigin::root(), hasher_params())); + assert_ok!(HasherPallet::force_set_parameters( + RuntimeOrigin::root(), + hasher_params().try_into().unwrap() + )); // then the merkle tree. >::on_initialize(1); assert_ok!(Mixer::create(RuntimeOrigin::root(), One::one(), 3, 0)); @@ -76,7 +82,10 @@ fn should_be_able_to_deposit() { new_test_ext().execute_with(|| { let _ = setup_environment(Curve::Bn254); // init hasher pallet first. - assert_ok!(HasherPallet::force_set_parameters(RuntimeOrigin::root(), hasher_params())); + assert_ok!(HasherPallet::force_set_parameters( + RuntimeOrigin::root(), + hasher_params().try_into().unwrap() + )); // then the merkle tree. >::on_initialize(1); let deposit_size = One::one(); @@ -522,7 +531,7 @@ fn deposit_with_non_native_asset_should_work() { // create an Asset first assert_ok!( AssetRegistry::get_or_create_asset( - String::from("ETH").into(), + String::from("ETH").into_bytes().try_into().unwrap(), AssetType::Token, Zero::zero() ), diff --git a/pallets/mixer/src/types.rs b/pallets/mixer/src/types.rs index 61f0163cc..14fe68fff 100644 --- a/pallets/mixer/src/types.rs +++ b/pallets/mixer/src/types.rs @@ -1,9 +1,9 @@ //! All the traits exposed to be used in other custom pallets use crate::*; -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; -#[derive(Clone, Encode, Decode, TypeInfo)] +#[derive(Clone, Encode, Decode, TypeInfo, MaxEncodedLen)] pub struct MixerMetadata { /// Balance size of deposit pub deposit_size: Balance, diff --git a/pallets/mt/src/lib.rs b/pallets/mt/src/lib.rs index 411770980..1f61d75f0 100644 --- a/pallets/mt/src/lib.rs +++ b/pallets/mt/src/lib.rs @@ -58,12 +58,15 @@ pub mod weights; pub mod types; use codec::{Decode, Encode}; use frame_support::{ensure, pallet_prelude::DispatchError}; -use sp_std::convert::TryInto; +use sp_std::convert::{TryFrom, TryInto}; use types::TreeMetadata; pub use weights::WeightInfo; -use frame_support::traits::{Currency, Get, ReservableCurrency}; +use frame_support::{ + traits::{Currency, Get, ReservableCurrency}, + BoundedVec, +}; use frame_system::Config as SystemConfig; use sp_runtime::traits::{AtLeast32Bit, One, Saturating, Zero}; use sp_std::prelude::*; @@ -72,7 +75,6 @@ use webb_primitives::{ traits::merkle_tree::{TreeInspector, TreeInterface}, types::{DepositDetails, ElementTrait}, }; - type DepositBalanceOf = <>::Currency as Currency<::AccountId>>::Balance; @@ -81,12 +83,12 @@ pub use pallet::*; #[frame_support::pallet] pub mod pallet { use super::*; - use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*}; + use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*, BoundedVec}; use frame_system::pallet_prelude::*; #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -97,16 +99,16 @@ pub mod pallet { + IsType<::RuntimeEvent>; /// The overarching tree ID type - type TreeId: Encode + Decode + Parameter + AtLeast32Bit + Default + Copy; + type TreeId: Encode + Decode + Parameter + AtLeast32Bit + Default + Copy + MaxEncodedLen; /// The overarching leaf index type - type LeafIndex: Encode + Decode + Parameter + AtLeast32Bit + Default + Copy; + type LeafIndex: Encode + Decode + Parameter + AtLeast32Bit + Default + Copy + MaxEncodedLen; /// The overarching leaf index type - type RootIndex: Encode + Decode + Parameter + AtLeast32Bit + Default + Copy; + type RootIndex: Encode + Decode + Parameter + AtLeast32Bit + Default + Copy + MaxEncodedLen; /// the leaf type - type Element: ElementTrait; + type Element: ElementTrait + MaxEncodedLen; /// the default zero element type DefaultZeroElement: Get; @@ -143,6 +145,12 @@ pub mod pallet { /// The maximum length of a name or symbol stored on-chain. type StringLimit: Get; + /// The maximum count of edges nodes to be stored for a tree detail + type MaxEdges: Get + TypeInfo; + + /// The maximum count of default hashes to store + type MaxDefaultHashes: Get + TypeInfo; + /// WeightInfo for pallet type WeightInfo: WeightInfo; } @@ -166,7 +174,7 @@ pub mod pallet { _, Blake2_128Concat, T::TreeId, - TreeMetadata, + TreeMetadata, OptionQuery, >; @@ -174,7 +182,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn default_hashes)] pub(super) type DefaultHashes, I: 'static = ()> = - StorageValue<_, Vec, ValueQuery>; + StorageValue<_, BoundedVec, ValueQuery>; /// The map of (tree_id, index) to the leaf commitment #[pallet::storage] @@ -237,6 +245,8 @@ pub mod pallet { TreeDoesntExist, /// Invalid length for default hashes ExceedsMaxDefaultHashes, + /// Invalid length for edges + ExceedsMaxEdges, } #[pallet::hooks] @@ -253,7 +263,7 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig, I: 'static = ()> { pub phantom: PhantomData, - pub default_hashes: Option>, + pub default_hashes: Option>, } #[cfg(feature = "std")] @@ -279,6 +289,7 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { #[pallet::weight(T::WeightInfo::create(*depth as u32))] + #[pallet::call_index(0)] pub fn create(origin: OriginFor, depth: u8) -> DispatchResultWithPostInfo { let origin = ensure_signed(origin)?; ensure!(depth <= T::MaxTreeDepth::get() && depth > 0, Error::::InvalidTreeDepth); @@ -296,6 +307,7 @@ pub mod pallet { } #[pallet::weight(T::WeightInfo::insert())] + #[pallet::call_index(1)] pub fn insert( origin: OriginFor, tree_id: T::TreeId, @@ -319,9 +331,10 @@ pub mod pallet { } #[pallet::weight(T::WeightInfo::force_set_default_hashes(default_hashes.len() as u32))] + #[pallet::call_index(2)] pub fn force_set_default_hashes( origin: OriginFor, - default_hashes: Vec, + default_hashes: BoundedVec, ) -> DispatchResultWithPostInfo { T::ForceOrigin::ensure_origin(origin)?; let len_of_hashes = default_hashes.len(); @@ -335,7 +348,8 @@ pub mod pallet { } } - pub fn generate_default_hashes, I: 'static>() -> Vec { + pub fn generate_default_hashes, I: 'static>( + ) -> BoundedVec { let mut temp_hashes: Vec = Vec::with_capacity(T::MaxTreeDepth::get() as usize); let default_zero = T::DefaultZeroElement::get(); temp_hashes.push(default_zero); @@ -349,7 +363,8 @@ pub mod pallet { panic!("Default hashes length is not equal to max tree depth"); } - temp_hashes + BoundedVec::::try_from(temp_hashes) + .expect("Default hashes bound exceeded. This should never happen!") } } @@ -371,7 +386,7 @@ impl, I: 'static> Pallet { #[allow(clippy::type_complexity)] fn get_tree( tree_id: T::TreeId, - ) -> Result, DispatchError> { + ) -> Result, DispatchError> { let tree = Trees::::get(tree_id); ensure!(tree.is_some(), Error::::TreeDoesntExist); Ok(tree.unwrap()) @@ -394,6 +409,10 @@ impl, I: 'static> TreeInterface = Self::default_hashes().into_iter().take(num_of_zero_nodes as _).collect(); + + let bounded_edge_nodes = + BoundedVec::::try_from(default_edge_nodes.clone()) + .map_err(|_e| Error::::ExceedsMaxEdges)?; // Setting up the tree let tree_metadata = TreeMetadata { creator, @@ -402,7 +421,7 @@ impl, I: 'static> TreeInterface::insert(tree_id, tree_metadata); diff --git a/pallets/mt/src/mock.rs b/pallets/mt/src/mock.rs index 51b3a6ba1..11630f65d 100644 --- a/pallets/mt/src/mock.rs +++ b/pallets/mt/src/mock.rs @@ -5,12 +5,14 @@ use crate as pallet_mt; use sp_core::H256; use arkworks_setups::{common::setup_params, Curve}; +use codec::MaxEncodedLen; use frame_support::{parameter_types, traits::GenesisBuild}; use frame_system as system; +use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, ConstU32, IdentityLookup}, }; use sp_std::convert::{TryFrom, TryInto}; pub use webb_primitives::hasher::{HasherModule, InstanceHasher}; @@ -90,6 +92,7 @@ parameter_types! { impl pallet_hasher::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; + type MaxParameterLength = ConstU32<10000>; type Hasher = webb_primitives::hashing::ArkworksPoseidonHasherBn254; type WeightInfo = (); } @@ -120,6 +123,7 @@ parameter_types! { scale_info::TypeInfo, Deserialize, Serialize, + MaxEncodedLen, )] pub struct Element([u8; 32]); @@ -135,6 +139,13 @@ impl ElementTrait for Element { } } +parameter_types! { + #[derive(Debug, TypeInfo)] + pub const MaxEdges: u32 = 1000; + #[derive(Debug, TypeInfo)] + pub const MaxDefaultHashes: u32 = 1000; +} + impl Config for Test { type Currency = Balances; type DataDepositBase = LeafDepositBase; @@ -151,14 +162,16 @@ impl Config for Test { type StringLimit = StringLimit; type TreeDeposit = TreeDeposit; type TreeId = u32; + type MaxEdges = MaxEdges; + type MaxDefaultHashes = MaxDefaultHashes; type Two = Two; type WeightInfo = (); } -pub fn hasher_params() -> Vec { +pub fn hasher_params() -> BoundedVec> { let curve = Curve::Bn254; let params = setup_params::(curve, 5, 3); - params.to_bytes() + BoundedVec::>::try_from(params.to_bytes()).unwrap() } #[derive(Default)] diff --git a/pallets/mt/src/tests.rs b/pallets/mt/src/tests.rs index 1ab50689e..d923b8975 100644 --- a/pallets/mt/src/tests.rs +++ b/pallets/mt/src/tests.rs @@ -43,6 +43,8 @@ fn should_fail_in_case_when_max_default_hashes_is_exceeded() { ::DefaultZeroElement::get(); (max_default_hashes + 1) as usize ] + .try_into() + .unwrap() ), crate::Error::::ExceedsMaxDefaultHashes ); @@ -54,7 +56,7 @@ fn should_successfully_set_default_hashes_to_match_solidity() { new_test_ext().execute_with(|| { assert_ok!(HasherPallet::force_set_parameters(RuntimeOrigin::root(), hasher_params())); assert_ok!(MerkleTree::create(RuntimeOrigin::signed(1), 32)); - let default_hashes: Vec = MerkleTree::default_hashes(); + let default_hashes: Vec = MerkleTree::default_hashes().into_inner(); let solidity_merkle_tree_hashes: Vec = vec![ Element::from_bytes(&hex!( "2fe54c60d3acabf3343a35b6eba15db4821b340f76e741e2249685ed4899af6c" diff --git a/pallets/mt/src/types.rs b/pallets/mt/src/types.rs index d36424531..910deee4c 100644 --- a/pallets/mt/src/types.rs +++ b/pallets/mt/src/types.rs @@ -1,10 +1,11 @@ //! All the traits exposed to be used in other custom pallets use crate::*; -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::BoundedVec; use scale_info::TypeInfo; -#[derive(Default, Clone, Encode, Decode, TypeInfo)] -pub struct TreeMetadata { +#[derive(Default, Clone, Encode, Decode, TypeInfo, MaxEncodedLen)] +pub struct TreeMetadata> { /// Creator account pub creator: Option, /// Is paused @@ -18,5 +19,5 @@ pub struct TreeMetadata { /// The root hash of the tree pub root: Element, /// Edge nodes of tree, used to compute roots on the fly - pub edge_nodes: Vec, + pub edge_nodes: BoundedVec, } diff --git a/pallets/relayer-registry/src/lib.rs b/pallets/relayer-registry/src/lib.rs index 0aee69a79..640ac9da0 100644 --- a/pallets/relayer-registry/src/lib.rs +++ b/pallets/relayer-registry/src/lib.rs @@ -179,6 +179,7 @@ pub mod pallet { /// /// Emits `ResourceSet` if successful. #[pallet::weight(T::WeightInfo::set_resource())] + #[pallet::call_index(0)] pub fn set_resource( origin: OriginFor, resource_id: ResourceId, @@ -222,6 +223,7 @@ pub mod pallet { /// /// Emits `ResourceCleared` if successful. #[pallet::weight(T::WeightInfo::clear_resource())] + #[pallet::call_index(1)] pub fn clear_resource( origin: OriginFor, resource_id: ResourceId, diff --git a/pallets/signature-bridge/src/lib.rs b/pallets/signature-bridge/src/lib.rs index 806d8245f..436bea0e4 100644 --- a/pallets/signature-bridge/src/lib.rs +++ b/pallets/signature-bridge/src/lib.rs @@ -57,7 +57,7 @@ mod tests; mod benchmarking; mod weights; -use codec::{self, Decode, Encode, EncodeLike}; +use codec::{self, Decode, Encode, EncodeLike, MaxEncodedLen}; use frame_support::{ pallet_prelude::{ensure, DispatchResultWithPostInfo}, traits::{EnsureOrigin, Get}, @@ -89,7 +89,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -117,11 +117,24 @@ pub mod pallet { + Default + Copy + From - + From; + + From + + MaxEncodedLen; /// Proposal nonce type - type ProposalNonce: Encode + Decode + Parameter + AtLeast32Bit + Default + Copy; + type ProposalNonce: Encode + + Decode + + Parameter + + AtLeast32Bit + + Default + + Copy + + MaxEncodedLen; /// Maintainer nonce type - type MaintainerNonce: Encode + Decode + Parameter + AtLeast32Bit + Default + Copy; + type MaintainerNonce: Encode + + Decode + + Parameter + + AtLeast32Bit + + Default + + Copy + + MaxEncodedLen; /// Signature verification utility over public key infrastructure type SignatureVerifier: SigningSystem; @@ -141,13 +154,16 @@ pub mod pallet { #[pallet::constant] type BridgeAccountId: Get; + type MaxStringLength: Get; + type WeightInfo: WeightInfo; } /// The parameter maintainer who can change the parameters #[pallet::storage] #[pallet::getter(fn maintainer)] - pub type Maintainer, I: 'static = ()> = StorageValue<_, Vec, ValueQuery>; + pub type Maintainer, I: 'static = ()> = + StorageValue<_, BoundedVec, ValueQuery>; /// All whitelisted chains and their respective transaction counts #[pallet::storage] @@ -175,7 +191,10 @@ pub mod pallet { #[pallet::generate_deposit(pub fn deposit_event)] pub enum Event, I: 'static = ()> { /// Maintainer is set - MaintainerSet { old_maintainer: Vec, new_maintainer: Vec }, + MaintainerSet { + old_maintainer: BoundedVec, + new_maintainer: BoundedVec, + }, /// Chain now available for transfers (chain_id) ChainWhitelisted { chain_id: T::ChainId }, /// Proposal has been approved @@ -219,6 +238,8 @@ pub mod pallet { InvalidProposalData, /// Invalid call - calls must be delegated to handler pallets InvalidCall, + /// The max limit for string is exceeded + StringLimitExceeded, } #[pallet::hooks] @@ -228,12 +249,13 @@ pub mod pallet { impl, I: 'static> Pallet { /// Sets the maintainer. #[pallet::weight(T::WeightInfo::set_maintainer())] + #[pallet::call_index(0)] pub fn set_maintainer( origin: OriginFor, // message contains the nonce as the first 4 bytes and the laste bytes of the message // is the new_maintainer - message: Vec, - signature: Vec, + message: BoundedVec, + signature: BoundedVec, ) -> DispatchResultWithPostInfo { let _origin = ensure_signed(origin)?; let old_maintainer = >::get(); @@ -256,7 +278,10 @@ pub mod pallet { MaintainerNonce::::put(nonce); // set the new maintainer Maintainer::::try_mutate(|maintainer| { - *maintainer = message[4..].to_vec(); + *maintainer = message[4..] + .to_vec() + .try_into() + .map_err(|_| Error::::StringLimitExceeded)?; Self::deposit_event(Event::MaintainerSet { old_maintainer, new_maintainer: message, @@ -267,9 +292,10 @@ pub mod pallet { // Forcefully set the maintainer. #[pallet::weight(T::WeightInfo::force_set_maintainer())] + #[pallet::call_index(1)] pub fn force_set_maintainer( origin: OriginFor, - new_maintainer: Vec, + new_maintainer: BoundedVec, ) -> DispatchResultWithPostInfo { Self::ensure_admin(origin)?; // set the new maintainer @@ -287,6 +313,7 @@ pub mod pallet { /// - O(1) write /// # #[pallet::weight(T::WeightInfo::set_resource())] + #[pallet::call_index(2)] pub fn set_resource(origin: OriginFor, id: ResourceId) -> DispatchResultWithPostInfo { Self::ensure_admin(origin)?; Self::register_resource(id) @@ -301,6 +328,7 @@ pub mod pallet { /// - O(1) removal /// # #[pallet::weight(T::WeightInfo::remove_resource())] + #[pallet::call_index(3)] pub fn remove_resource(origin: OriginFor, id: ResourceId) -> DispatchResultWithPostInfo { Self::ensure_admin(origin)?; Self::unregister_resource(id) @@ -312,6 +340,7 @@ pub mod pallet { /// - O(1) lookup and insert /// # #[pallet::weight(T::WeightInfo::whitelist_chain())] + #[pallet::call_index(4)] pub fn whitelist_chain(origin: OriginFor, id: T::ChainId) -> DispatchResultWithPostInfo { Self::ensure_admin(origin)?; Self::whitelist(id) @@ -340,11 +369,12 @@ pub mod pallet { /// - weight of proposed call, regardless of whether execution is performed /// # #[pallet::weight((T::WeightInfo::set_resource_with_signature(), Pays::Yes))] + #[pallet::call_index(5)] pub fn set_resource_with_signature( origin: OriginFor, src_id: T::ChainId, - proposal_data: Vec, - signature: Vec, + proposal_data: BoundedVec, + signature: BoundedVec, ) -> DispatchResultWithPostInfo { let _ = ensure_signed(origin)?; let r_id = Self::parse_r_id_from_proposal_data(&proposal_data)?; @@ -418,11 +448,12 @@ pub mod pallet { /// - weight of proposed call, regardless of whether execution is performed /// # #[pallet::weight((T::WeightInfo::execute_proposal() , Pays::Yes))] + #[pallet::call_index(6)] pub fn execute_proposal( origin: OriginFor, src_id: T::ChainId, - proposal_data: Vec, - signature: Vec, + proposal_data: BoundedVec, + signature: BoundedVec, ) -> DispatchResultWithPostInfo { let _ = ensure_signed(origin)?; let r_id = Self::parse_r_id_from_proposal_data(&proposal_data)?; diff --git a/pallets/signature-bridge/src/mock.rs b/pallets/signature-bridge/src/mock.rs index 68258a03a..c826fc4ce 100644 --- a/pallets/signature-bridge/src/mock.rs +++ b/pallets/signature-bridge/src/mock.rs @@ -8,7 +8,7 @@ use sp_core::H256; use sp_keystore::{testing::KeyStore, KeystoreExt}; use sp_runtime::{ testing::Header, - traits::{AccountIdConversion, BlakeTwo256, IdentityLookup}, + traits::{AccountIdConversion, BlakeTwo256, ConstU32, IdentityLookup}, }; use sp_std::convert::{TryFrom, TryInto}; use std::{sync::Arc, vec}; @@ -125,6 +125,7 @@ impl Config for Test { type SetResourceProposalFilter = SetResourceProposalFilter; type ExecuteProposalFilter = ExecuteAllProposalsFilter; type MaintainerNonce = u32; + type MaxStringLength = ConstU32<1000>; type Proposal = RuntimeCall; type SignatureVerifier = webb_primitives::signing::SignatureVerifier; type WeightInfo = (); diff --git a/pallets/signature-bridge/src/tests.rs b/pallets/signature-bridge/src/tests.rs index 53cc005cd..7a32e6b5b 100644 --- a/pallets/signature-bridge/src/tests.rs +++ b/pallets/signature-bridge/src/tests.rs @@ -11,12 +11,13 @@ use crate::{ mock::new_test_ext_initialized, {self as pallet_bridge}, }; -use frame_support::{assert_err, assert_ok}; +use frame_support::{assert_err, assert_ok, BoundedVec}; use hex_literal::hex; use sp_core::{ ecdsa::{self, Signature}, keccak_256, Pair, }; +use sp_runtime::traits::ConstU32; use webb_primitives::{ utils::{compute_chain_id_type, derive_resource_id}, webb_proposals::SubstrateTargetSystem, @@ -70,8 +71,8 @@ fn create_proposal_tests() { Bridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - prop_data.clone(), - sig.0.to_vec(), + prop_data.clone().try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), ), Error::::InvalidPermissions ); @@ -79,14 +80,14 @@ fn create_proposal_tests() { // set the new maintainer assert_ok!(Bridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); // Create proposal (& vote) assert_ok!(Bridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - prop_data, - sig.0.to_vec(), + prop_data.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); assert_events(vec![ @@ -189,8 +190,8 @@ fn should_fail_to_set_resource_id_when_nonce_increments_by_more_than_1048() { Bridge::set_resource_with_signature( RuntimeOrigin::signed(RELAYER_A), src_id, - prop_data, - sig.0.to_vec(), + prop_data.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), ), Error::::InvalidNonce ); @@ -212,7 +213,9 @@ fn set_maintainer_should_work() { .to_vec(); new_test_ext_initialized(1u64, r_id, b"System.remark".to_vec()).execute_with(|| { - Maintainer::::put(old_maintainer); + let bounded_old_maintainer: BoundedVec> = + old_maintainer.try_into().unwrap(); + Maintainer::::put(bounded_old_maintainer); let mut message = vec![]; let nonce = 1u32.encode(); message.extend_from_slice(&nonce); @@ -221,7 +224,11 @@ fn set_maintainer_should_work() { let sig: Signature = pair.sign_prehashed(&msg); // set the new maintainer - assert_ok!(Bridge::set_maintainer(RuntimeOrigin::signed(RELAYER_A), message, sig.encode())); + assert_ok!(Bridge::set_maintainer( + RuntimeOrigin::signed(RELAYER_A), + message.try_into().unwrap(), + sig.encode().try_into().unwrap() + )); }) } @@ -248,7 +255,7 @@ fn should_fail_on_invalid_proposal_call() { // set the new maintainer assert_ok!(Bridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); // should fail to execute proposal as invalid call is provided @@ -256,8 +263,8 @@ fn should_fail_on_invalid_proposal_call() { Bridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - prop_data, - sig.0.to_vec(), + prop_data.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), ), Error::::InvalidCall ); diff --git a/pallets/token-wrapper-handler/src/lib.rs b/pallets/token-wrapper-handler/src/lib.rs index db3642a58..4ed6e8140 100644 --- a/pallets/token-wrapper-handler/src/lib.rs +++ b/pallets/token-wrapper-handler/src/lib.rs @@ -106,6 +106,7 @@ pub mod pallet { /// Execute the wrapping fee proposal by calling the update_wrapping_fee /// method. Ensures that only the bridge can call this function. #[pallet::weight(195_000_000)] + #[pallet::call_index(0)] pub fn execute_wrapping_fee_proposal( origin: OriginFor, wrapping_fee_percent: BalanceOf, @@ -119,6 +120,7 @@ pub mod pallet { } #[pallet::weight(195_000_000)] + #[pallet::call_index(1)] pub fn execute_add_token_to_pool_share( origin: OriginFor, name: Vec, @@ -132,6 +134,7 @@ pub mod pallet { } #[pallet::weight(195_000_000)] + #[pallet::call_index(2)] pub fn execute_remove_token_from_pool_share( origin: OriginFor, name: Vec, @@ -147,6 +150,7 @@ pub mod pallet { /// who will be receiving wrapping fee cost for given asset. /// Ensures that only the bridge can call this function. #[pallet::weight(195_000_000)] + #[pallet::call_index(3)] pub fn execute_set_fee_recipient_proposal( origin: OriginFor, pool_share_id: T::AssetId, @@ -162,6 +166,7 @@ pub mod pallet { /// fee recipient to given recipient address from given asset. /// Ensures that only the bridge can call this function. #[pallet::weight(195_000_000)] + #[pallet::call_index(4)] pub fn execute_rescue_tokens_proposal( origin: OriginFor, pool_share_id: T::AssetId, diff --git a/pallets/token-wrapper-handler/src/mock_signature_bridge.rs b/pallets/token-wrapper-handler/src/mock_signature_bridge.rs index e04902d8a..2857fe122 100644 --- a/pallets/token-wrapper-handler/src/mock_signature_bridge.rs +++ b/pallets/token-wrapper-handler/src/mock_signature_bridge.rs @@ -12,7 +12,7 @@ use orml_currencies::{BasicCurrencyAdapter, NativeCurrencyOf}; use sp_core::H256; use sp_runtime::{ testing::Header, - traits::{AccountIdConversion, BlakeTwo256, IdentityLookup}, + traits::{AccountIdConversion, BlakeTwo256, ConstU32, IdentityLookup}, Permill, }; use sp_std::convert::{TryFrom, TryInto}; @@ -85,12 +85,18 @@ pub type Amount = i128; /// Unsigned version of Balance pub type Balance = u128; +parameter_types! { + #[derive(Copy, Clone, Debug, PartialEq, Eq, scale_info::TypeInfo)] + pub const MaxAssetIdInPool: u32 = 100; +} + impl asset_registry::Config for Test { type AssetId = webb_primitives::AssetId; type AssetNativeLocation = (); type Balance = u128; type RuntimeEvent = RuntimeEvent; type NativeAssetId = NativeAssetId; + type MaxAssetIdInPool = MaxAssetIdInPool; type RegistryOrigin = frame_system::EnsureRoot; type StringLimit = RegistryStringLimit; type WeightInfo = (); @@ -229,6 +235,7 @@ impl pallet_signature_bridge::Config for Test { type ChainId = ChainId; type ChainIdentifier = ChainIdentifier; type ChainType = ChainType; + type MaxStringLength = ConstU32<1000>; type RuntimeEvent = RuntimeEvent; type ProposalLifetime = ProposalLifetime; type ProposalNonce = ProposalNonce; diff --git a/pallets/token-wrapper-handler/src/tests_signature_bridge.rs b/pallets/token-wrapper-handler/src/tests_signature_bridge.rs index 78d55e8d4..aa24f5b2a 100644 --- a/pallets/token-wrapper-handler/src/tests_signature_bridge.rs +++ b/pallets/token-wrapper-handler/src/tests_signature_bridge.rs @@ -111,7 +111,7 @@ fn should_update_fee_with_sig_succeed() { let existential_balance: u32 = 1000; let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![]), + AssetType::PoolShare(Default::default()), existential_balance.into(), ) .unwrap(); @@ -126,8 +126,8 @@ fn should_update_fee_with_sig_succeed() { SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - wrapping_fee_proposal_bytes.clone(), - sig.0.to_vec(), + wrapping_fee_proposal_bytes.clone().try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), ), pallet_signature_bridge::Error::::InvalidPermissions ); @@ -135,14 +135,14 @@ fn should_update_fee_with_sig_succeed() { // set the maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - wrapping_fee_proposal_bytes, - sig.0.to_vec(), + wrapping_fee_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); assert_eq!(TokenWrapper::get_wrapping_fee(1000_u128, pool_share_id).unwrap(), 52); @@ -176,7 +176,7 @@ fn should_add_token_with_sig_succeed() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![]), + AssetType::PoolShare(Default::default()), existential_balance.into(), ) .unwrap(); @@ -190,14 +190,14 @@ fn should_add_token_with_sig_succeed() { // set the new maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); // Create proposal (& vote) assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - add_token_proposal_bytes, - sig.0.to_vec(), + add_token_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); // Check that first_token_id is part of pool assert_eq!(AssetRegistry::contains_asset(pool_share_id, first_token_id), true); @@ -235,7 +235,7 @@ fn should_remove_token_with_sig_succeed() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![]), + AssetType::PoolShare(vec![].try_into().unwrap()), existential_balance.into(), ) .unwrap(); @@ -250,15 +250,15 @@ fn should_remove_token_with_sig_succeed() { // set the new maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); // Create proposal (& vote) assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - add_token_proposal_bytes, - sig.0.to_vec(), + add_token_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); // Check that first_token_id is part of pool assert_eq!(AssetRegistry::contains_asset(pool_share_id, first_token_id), true); @@ -272,8 +272,8 @@ fn should_remove_token_with_sig_succeed() { assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - remove_token_proposal_bytes, - sig.0.to_vec(), + remove_token_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); assert_eq!(AssetRegistry::contains_asset(pool_share_id, first_token_id), false); @@ -307,7 +307,7 @@ fn should_fail_to_remove_token_not_in_pool_with_sig() { AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![]), + AssetType::PoolShare(Default::default()), existential_balance.into(), ) .unwrap(); @@ -315,7 +315,7 @@ fn should_fail_to_remove_token_not_in_pool_with_sig() { // set the new maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); let nonce = webb_proposals::Nonce::from(0x0001); let header = make_proposal_header(r_id, REMOVE_TOKEN_FUNCTION_SIG, nonce); @@ -328,8 +328,8 @@ fn should_fail_to_remove_token_not_in_pool_with_sig() { SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - remove_token_proposal_bytes, - sig.0.to_vec(), + remove_token_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), ), asset_registry::Error::::AssetNotFoundInPool ); @@ -377,14 +377,14 @@ fn should_add_many_tokens_with_sig_succeed() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![]), + AssetType::PoolShare(Default::default()), existential_balance.into(), ) .unwrap(); // set the new maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); let nonce = webb_proposals::Nonce::from(0x0001); let header = make_proposal_header(r_id, ADD_TOKEN_FUNCTION_SIG, nonce); @@ -397,8 +397,8 @@ fn should_add_many_tokens_with_sig_succeed() { assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - add_token_proposal_bytes, - sig.0.to_vec(), + add_token_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); let nonce = webb_proposals::Nonce::from(0x0002); let header = make_proposal_header(r_id, ADD_TOKEN_FUNCTION_SIG, nonce); @@ -412,8 +412,8 @@ fn should_add_many_tokens_with_sig_succeed() { assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - add_token_proposal_bytes, - sig.0.to_vec(), + add_token_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); let nonce = webb_proposals::Nonce::from(0x0003); let header = make_proposal_header(r_id, ADD_TOKEN_FUNCTION_SIG, nonce); @@ -427,8 +427,8 @@ fn should_add_many_tokens_with_sig_succeed() { assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - add_token_proposal_bytes, - sig.0.to_vec(), + add_token_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); // Check that first_token_id is part of pool @@ -469,7 +469,7 @@ fn should_fail_to_add_same_token_with_sig() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![]), + AssetType::PoolShare(Default::default()), existential_balance.into(), ) .unwrap(); @@ -484,14 +484,14 @@ fn should_fail_to_add_same_token_with_sig() { // set the new maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); // Create proposal assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - add_token_proposal_bytes, - sig.0.to_vec(), + add_token_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); // Check that first_token_id is part of pool assert_eq!(AssetRegistry::contains_asset(pool_share_id, first_token_id), true); @@ -509,8 +509,8 @@ fn should_fail_to_add_same_token_with_sig() { SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - add_token_proposal_bytes, - sig.0.to_vec(), + add_token_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), ), asset_registry::Error::::AssetExistsInPool ); @@ -544,7 +544,7 @@ fn should_fail_to_add_non_existent_token_with_sig() { AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![]), + AssetType::PoolShare(Default::default()), existential_balance.into(), ) .unwrap(); @@ -559,15 +559,15 @@ fn should_fail_to_add_non_existent_token_with_sig() { // set the new maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); // Create proposal (& vote) assert_err!( SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id, - add_token_proposal_bytes, - sig.0.to_vec(), + add_token_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), ), asset_registry::Error::::AssetNotRegistered ); diff --git a/pallets/token-wrapper/src/lib.rs b/pallets/token-wrapper/src/lib.rs index 381fa0cbc..83fa91b1e 100644 --- a/pallets/token-wrapper/src/lib.rs +++ b/pallets/token-wrapper/src/lib.rs @@ -70,7 +70,7 @@ use frame_support::{ use orml_traits::MultiCurrency; use sp_arithmetic::traits::Saturating; use sp_runtime::traits::AtLeast32Bit; -use sp_std::convert::TryInto; +use sp_std::convert::{TryFrom, TryInto}; use traits::TokenWrapperInterface; use weights::WeightInfo; @@ -89,7 +89,7 @@ pub mod pallet { use frame_system::{ensure_signed, pallet_prelude::*}; #[pallet::pallet] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -113,12 +113,14 @@ pub mod pallet { Vec, Self::Balance, BoundedVec, + Self::MaxAssetIdInPool, DispatchError, > + ShareTokenRegistry< Self::AssetId, Vec, Self::Balance, BoundedVec, + Self::MaxAssetIdInPool, DispatchError, >; @@ -146,12 +148,14 @@ pub mod pallet { /// Fee recipient, account which will be receiving wrapping cost fee. #[pallet::storage] #[pallet::getter(fn fee_recipient)] - pub type FeeRecipient = StorageMap<_, Blake2_128Concat, Vec, T::AccountId>; + pub type FeeRecipient = + StorageMap<_, Blake2_128Concat, BoundedVec, T::AccountId>; /// The proposal nonce used to prevent replay attacks on execute_proposal #[pallet::storage] #[pallet::getter(fn proposal_nonce)] - pub type ProposalNonce = StorageMap<_, Blake2_128Concat, Vec, T::ProposalNonce>; + pub type ProposalNonce = + StorageMap<_, Blake2_128Concat, BoundedVec, T::ProposalNonce>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] @@ -198,11 +202,14 @@ pub mod pallet { NoWrappingFeePercentFound, /// Invalid nonce InvalidNonce, + /// Name exceeds maximum limit + NameExceedsMaximumLimit, } #[pallet::call] impl Pallet { #[pallet::weight(::WeightInfo::set_wrapping_fee())] + #[pallet::call_index(0)] pub fn set_wrapping_fee( origin: OriginFor, fee: BalanceOf, @@ -220,6 +227,7 @@ pub mod pallet { } #[pallet::weight(195_000_000)] + #[pallet::call_index(1)] pub fn set_fee_recipient( origin: OriginFor, pool_share_id: T::AssetId, @@ -237,6 +245,7 @@ pub mod pallet { } #[pallet::weight(::WeightInfo::wrap())] + #[pallet::call_index(2)] pub fn wrap( origin: OriginFor, from_asset_id: T::AssetId, @@ -256,6 +265,7 @@ pub mod pallet { } #[pallet::weight(::WeightInfo::unwrap())] + #[pallet::call_index(3)] pub fn unwrap( origin: OriginFor, from_pool_share_id: T::AssetId, @@ -275,6 +285,7 @@ pub mod pallet { } #[pallet::weight(195_000_000)] + #[pallet::call_index(4)] pub fn rescue_tokens( origin: OriginFor, from_pool_share_id: T::AssetId, @@ -305,7 +316,7 @@ impl Pallet { T::TreasuryId::get().into_account_truncating() } - pub fn get_fee_recipient(name: &Vec) -> T::AccountId { + pub fn get_fee_recipient(name: &BoundedVec) -> T::AccountId { FeeRecipient::::get(name).unwrap_or(Self::treasury_id()) } @@ -349,7 +360,7 @@ impl Pallet { } pub fn validate_and_set_nonce( - name: &Vec, + name: &BoundedVec, nonce: T::ProposalNonce, ) -> Result<(), DispatchError> { // Nonce should be greater than the proposal nonce in storage @@ -387,6 +398,7 @@ impl TokenWrapperInterface, T: Vec, T::Balance, BoundedVec, + T::MaxAssetIdInPool, DispatchError, >>::exists(from_asset_id), Error::::UnregisteredAssetId @@ -398,6 +410,7 @@ impl TokenWrapperInterface, T: Vec, T::Balance, BoundedVec, + T::MaxAssetIdInPool, DispatchError, >>::contains_asset(into_pool_share_id, from_asset_id), Error::::NotFoundInPool @@ -416,6 +429,7 @@ impl TokenWrapperInterface, T: Vec, T::Balance, BoundedVec, + T::MaxAssetIdInPool, DispatchError, >>::get_by_id(into_pool_share_id)?; @@ -454,6 +468,7 @@ impl TokenWrapperInterface, T: Vec, T::Balance, BoundedVec, + T::MaxAssetIdInPool, DispatchError, >>::exists(into_asset_id), Error::::UnregisteredAssetId @@ -465,6 +480,7 @@ impl TokenWrapperInterface, T: Vec, T::Balance, BoundedVec, + T::MaxAssetIdInPool, DispatchError, >>::contains_asset(from_pool_share_id, into_asset_id), Error::::NotFoundInPool @@ -496,6 +512,7 @@ impl TokenWrapperInterface, T: Vec, T::Balance, BoundedVec, + T::MaxAssetIdInPool, DispatchError, >>::get_by_id(into_pool_share_id)?; // Nonce should be greater than the proposal nonce in storage @@ -520,6 +537,7 @@ impl TokenWrapperInterface, T: Vec, T::Balance, BoundedVec, + T::MaxAssetIdInPool, DispatchError, >>::get_by_id(pool_share_id)?; // nonce should be greater than the proposal nonce in storage @@ -544,6 +562,7 @@ impl TokenWrapperInterface, T: Vec, T::Balance, BoundedVec, + T::MaxAssetIdInPool, DispatchError, >>::get_by_id(from_pool_share_id)?; // Nonce should be greater than the proposal nonce in storage @@ -575,12 +594,15 @@ impl TokenWrapperInterface, T: nonce: T::ProposalNonce, ) -> Result { // Nonce should be greater than the proposal nonce in storage - Self::validate_and_set_nonce(name, nonce)?; + let bounded_name = BoundedVec::::try_from(name.clone()) + .map_err(|_e| Error::::NameExceedsMaximumLimit)?; + Self::validate_and_set_nonce(&bounded_name, nonce)?; , T::Balance, BoundedVec, + T::MaxAssetIdInPool, DispatchError, >>::add_asset_to_existing_pool(name, asset_id) } @@ -591,13 +613,15 @@ impl TokenWrapperInterface, T: nonce: T::ProposalNonce, ) -> Result { // Nonce should be greater than the proposal nonce in storage - Self::validate_and_set_nonce(name, nonce)?; - + let bounded_name = BoundedVec::::try_from(name.clone()) + .map_err(|_e| Error::::NameExceedsMaximumLimit)?; + Self::validate_and_set_nonce(&bounded_name, nonce)?; , T::Balance, BoundedVec, + T::MaxAssetIdInPool, DispatchError, >>::delete_asset_from_existing_pool(name, asset_id) } diff --git a/pallets/token-wrapper/src/mock.rs b/pallets/token-wrapper/src/mock.rs index f92748ef6..868d0ca9c 100644 --- a/pallets/token-wrapper/src/mock.rs +++ b/pallets/token-wrapper/src/mock.rs @@ -6,6 +6,7 @@ use crate as pallet_token_wrapper; use frame_support::{pallet_prelude::GenesisBuild, parameter_types, traits::Nothing, PalletId}; use frame_system as system; use orml_currencies::{BasicCurrencyAdapter, NativeCurrencyOf}; +use scale_info::TypeInfo; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -79,12 +80,18 @@ pub type Amount = i128; /// Unsigned version of Balance pub type Balance = u128; +parameter_types! { + #[derive(Copy, Clone, Debug, PartialEq, Eq, TypeInfo)] + pub const MaxAssetIdInPool: u32 = 100; +} + impl asset_registry::Config for Test { type AssetId = webb_primitives::AssetId; type AssetNativeLocation = (); type Balance = u128; type RuntimeEvent = RuntimeEvent; type NativeAssetId = NativeAssetId; + type MaxAssetIdInPool = MaxAssetIdInPool; type RegistryOrigin = frame_system::EnsureRoot; type StringLimit = RegistryStringLimit; type WeightInfo = (); diff --git a/pallets/token-wrapper/src/tests.rs b/pallets/token-wrapper/src/tests.rs index ceb875c9e..939220be3 100644 --- a/pallets/token-wrapper/src/tests.rs +++ b/pallets/token-wrapper/src/tests.rs @@ -25,7 +25,7 @@ fn should_wrap_token() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![second_token_id, first_token_id]), + AssetType::PoolShare(vec![second_token_id, first_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); @@ -101,7 +101,7 @@ fn should_unwrap_token() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![second_token_id, first_token_id]), + AssetType::PoolShare(vec![second_token_id, first_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); @@ -175,7 +175,7 @@ fn wrapping_should_fail_if_asset_is_not_in_pool() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![second_token_id]), + AssetType::PoolShare(vec![second_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); @@ -224,7 +224,7 @@ fn only_root_should_update_wrapping_fee() { .unwrap(); let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![second_token_id, first_token_id]), + AssetType::PoolShare(vec![second_token_id, first_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); @@ -257,7 +257,7 @@ fn should_not_unwrap_if_no_liquidity_exists_for_selected_assets() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![second_token_id, first_token_id]), + AssetType::PoolShare(vec![second_token_id, first_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); @@ -327,7 +327,7 @@ fn should_unwrap_when_liquidity_exists_for_selected_asset() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![second_token_id, first_token_id]), + AssetType::PoolShare(vec![second_token_id, first_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); @@ -407,7 +407,7 @@ fn should_not_wrap_invalid_amount() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![second_token_id, first_token_id]), + AssetType::PoolShare(vec![second_token_id, first_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); @@ -457,7 +457,7 @@ fn test_two_different_pool_shares() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![second_token_id, first_token_id]), + AssetType::PoolShare(vec![second_token_id, first_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); @@ -477,7 +477,7 @@ fn test_two_different_pool_shares() { let second_pool_share_id = AssetRegistry::register_asset( b"real".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![third_token_id, fourth_token_id]), + AssetType::PoolShare(vec![third_token_id, fourth_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); @@ -568,7 +568,7 @@ fn should_rescue_all_tokens() { let pool_share_id = AssetRegistry::register_asset( b"meme".to_vec().try_into().unwrap(), - AssetType::PoolShare(vec![second_token_id, first_token_id]), + AssetType::PoolShare(vec![second_token_id, first_token_id].try_into().unwrap()), existential_balance.into(), ) .unwrap(); diff --git a/pallets/vanchor-handler/src/lib.rs b/pallets/vanchor-handler/src/lib.rs index 663cc8e66..9bbefbbf5 100644 --- a/pallets/vanchor-handler/src/lib.rs +++ b/pallets/vanchor-handler/src/lib.rs @@ -68,7 +68,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -126,6 +126,7 @@ pub mod pallet { /// This will be called by bridge when proposal to create a /// vanchor has been successfully voted on. #[pallet::weight(195_000_000)] + #[pallet::call_index(0)] pub fn execute_vanchor_create_proposal( origin: OriginFor, src_chain_id: T::ChainId, @@ -142,6 +143,7 @@ pub mod pallet { /// This will be called by bridge when proposal to add/update edge of a /// vanchor has been successfully voted on. #[pallet::weight(195_000_000)] + #[pallet::call_index(1)] pub fn execute_vanchor_update_proposal( origin: OriginFor, r_id: ResourceId, @@ -163,6 +165,7 @@ pub mod pallet { /// This will by called by bridge when proposal to set new resource for /// handler has been successfully voted on. #[pallet::weight(195_000_000)] + #[pallet::call_index(2)] pub fn execute_set_resource_proposal( origin: OriginFor, r_id: ResourceId, @@ -179,6 +182,7 @@ pub mod pallet { /// The `MaxDepositLimitProposal` updates the maximum deposit amount allowed on the variable /// anchor system. #[pallet::weight(195_000_000)] + #[pallet::call_index(3)] pub fn execute_set_max_deposit_limit_proposal( origin: OriginFor, max_deposit_limit: VAnchorBalanceOf, @@ -193,6 +197,7 @@ pub mod pallet { /// The `MinWithdrawalLimitProposal` updates the minimum withdrawal amount allowed on the /// variable anchor system. #[pallet::weight(195_000_000)] + #[pallet::call_index(4)] pub fn execute_set_minx_withdrawal_limit_proposal( origin: OriginFor, min_withdraw_limit: VAnchorBalanceOf, diff --git a/pallets/vanchor-handler/src/mock_signature_bridge.rs b/pallets/vanchor-handler/src/mock_signature_bridge.rs index 091158abc..09b77ef15 100644 --- a/pallets/vanchor-handler/src/mock_signature_bridge.rs +++ b/pallets/vanchor-handler/src/mock_signature_bridge.rs @@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize}; use sp_core::H256; use sp_runtime::{ testing::Header, - traits::{AccountIdConversion, BlakeTwo256, IdentityLookup}, + traits::{AccountIdConversion, BlakeTwo256, ConstU32, IdentityLookup}, }; use sp_std::convert::{TryFrom, TryInto}; use webb_primitives::{ @@ -120,6 +120,7 @@ parameter_types! { impl pallet_vanchor_verifier::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; + type MaxParameterLength = ConstU32<1000>; type Verifier = ArkworksVerifierBn254; type WeightInfo = (); } @@ -127,6 +128,7 @@ impl pallet_vanchor_verifier::Config for Test { impl pallet_hasher::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; + type MaxParameterLength = ConstU32<10000>; type Hasher = webb_primitives::hashing::ArkworksPoseidonHasherBn254; type WeightInfo = (); } @@ -157,6 +159,7 @@ parameter_types! { scale_info::TypeInfo, Serialize, Deserialize, + codec::MaxEncodedLen, )] pub struct Element([u8; 32]); @@ -172,12 +175,21 @@ impl ElementTrait for Element { } } +parameter_types! { + #[derive(Debug, scale_info::TypeInfo)] + pub const MaxEdges: u32 = 1000; + #[derive(Debug, scale_info::TypeInfo)] + pub const MaxDefaultHashes: u32 = 1000; +} + impl pallet_mt::Config for Test { type Currency = Balances; type DataDepositBase = LeafDepositBase; type DataDepositPerByte = LeafDepositPerByte; type DefaultZeroElement = DefaultZeroElement; type Element = Element; + type MaxEdges = MaxEdges; + type MaxDefaultHashes = MaxDefaultHashes; type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; type Hasher = HasherPallet; @@ -221,12 +233,18 @@ impl orml_currencies::Config for Test { type WeightInfo = (); } +parameter_types! { + #[derive(Copy, Clone, Debug, PartialEq, Eq, scale_info::TypeInfo)] + pub const MaxAssetIdInPool: u32 = 100; +} + impl pallet_asset_registry::Config for Test { type AssetId = webb_primitives::AssetId; type AssetNativeLocation = (); type Balance = u128; type RuntimeEvent = RuntimeEvent; type NativeAssetId = NativeCurrencyId; + type MaxAssetIdInPool = MaxAssetIdInPool; type RegistryOrigin = frame_system::EnsureRoot; type StringLimit = RegistryStringLimit; type WeightInfo = (); @@ -309,6 +327,7 @@ impl pallet_signature_bridge::Config for Test { type ChainType = ChainType; type RuntimeEvent = RuntimeEvent; type ProposalLifetime = ProposalLifetime; + type MaxStringLength = ConstU32<1000>; type ProposalNonce = ProposalNonce; type SetResourceProposalFilter = SetResourceProposalFilter; type ExecuteProposalFilter = ExecuteProposalFilter; @@ -352,6 +371,8 @@ impl pallet_vanchor_handler::Config for Test { impl pallet_key_storage::Config for Test { type RuntimeEvent = RuntimeEvent; + type MaxPubkeyLength = ConstU32<10000>; + type MaxPubKeyOwners = ConstU32<10000>; type WeightInfo = (); } diff --git a/pallets/vanchor-handler/src/tests_signature_bridge.rs b/pallets/vanchor-handler/src/tests_signature_bridge.rs index 46a4d93c4..e37d00eb9 100644 --- a/pallets/vanchor-handler/src/tests_signature_bridge.rs +++ b/pallets/vanchor-handler/src/tests_signature_bridge.rs @@ -12,6 +12,7 @@ use sp_core::{ ecdsa::{self, Signature}, keccak_256, Pair, }; +use sp_std::convert::TryInto; use webb_proposals::{ FunctionSignature, ResourceId, SubstrateTargetSystem, TargetSystem, TypedChainId, @@ -128,7 +129,10 @@ fn should_create_vanchor_with_sig_succeed() { .execute_with(|| { let curve = Curve::Bn254; let params = setup_params::(curve, 5, 3); - let _ = HasherPallet::force_set_parameters(RuntimeOrigin::root(), params.to_bytes()); + let _ = HasherPallet::force_set_parameters( + RuntimeOrigin::root(), + params.to_bytes().try_into().unwrap(), + ); let nonce = 1; let anchor_create_call = make_vanchor_create_proposal(src_id.chain_id(), &r_id, nonce); let anchor_create_call_encoded = anchor_create_call.encode(); @@ -146,23 +150,23 @@ fn should_create_vanchor_with_sig_succeed() { SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id.chain_id(), - prop_data.clone(), - sig.0.to_vec(), + prop_data.clone().try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), ), pallet_signature_bridge::Error::::InvalidPermissions ); // set the maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); assert!(!>::contains_key(0)); assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id.chain_id(), - prop_data, - sig.0.to_vec(), + prop_data.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); assert!(>::contains_key(0)); @@ -187,12 +191,15 @@ fn should_add_vanchor_edge_with_sig_succeed() { new_test_ext_initialized( src_id.chain_id(), r_id, - b"VAnchorHandler.execute_vanchor_update_proposal".to_vec(), + b"VAnchorHandler.execute_vanchor_update_proposal".to_vec().try_into().unwrap(), ) .execute_with(|| { let curve = Curve::Bn254; let params = setup_params::(curve, 5, 3); - let _ = HasherPallet::force_set_parameters(RuntimeOrigin::root(), params.to_bytes()); + let _ = HasherPallet::force_set_parameters( + RuntimeOrigin::root(), + params.to_bytes().try_into().unwrap(), + ); mock_vanchor_creation_using_pallet_call(&r_id); @@ -214,14 +221,14 @@ fn should_add_vanchor_edge_with_sig_succeed() { // set the maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id.chain_id(), - prop_data, - sig.0.to_vec(), + prop_data.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); // the anchor-handler callback must have been called by bridge // event must be emitted in callback should exist @@ -270,7 +277,10 @@ fn should_update_vanchor_edge_with_sig_succeed() { .execute_with(|| { let curve = Curve::Bn254; let params = setup_params::(curve, 5, 3); - let _ = HasherPallet::force_set_parameters(RuntimeOrigin::root(), params.to_bytes()); + let _ = HasherPallet::force_set_parameters( + RuntimeOrigin::root(), + params.to_bytes().try_into().unwrap(), + ); println!("here"); mock_vanchor_creation_using_pallet_call(&r_id); println!("there"); @@ -293,14 +303,14 @@ fn should_update_vanchor_edge_with_sig_succeed() { // set the maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id.chain_id(), - prop_data, - sig.0.to_vec(), + prop_data.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); // the anchor-handler callback must have been called by bridge // event must be emitted in callback should exist @@ -344,8 +354,8 @@ fn should_update_vanchor_edge_with_sig_succeed() { assert_ok!(SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id.chain_id(), - prop_data, - sig.0.to_vec(), + prop_data.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); // the anchor-handler callback must have been called by bridge // event must be emitted in callback should exist @@ -421,7 +431,7 @@ fn should_fail_to_execute_proposal_from_non_whitelisted_chain() { // set the maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); assert!(!>::contains_key(0)); @@ -429,8 +439,8 @@ fn should_fail_to_execute_proposal_from_non_whitelisted_chain() { SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id.chain_id() + 1, - prop_data, - sig.0.to_vec(), + prop_data.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), ), pallet_signature_bridge::Error::::ChainNotWhitelisted ); @@ -475,7 +485,7 @@ fn should_fail_to_execute_proposal_with_non_existent_resource_id() { // set the maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); assert!(!>::contains_key(0)); @@ -483,8 +493,8 @@ fn should_fail_to_execute_proposal_with_non_existent_resource_id() { SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id.chain_id(), - prop_data, - sig.0.to_vec(), + prop_data.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), ), pallet_signature_bridge::Error::::ResourceDoesNotExist ); @@ -523,7 +533,7 @@ fn should_fail_to_verify_proposal_with_tampered_signature() { // set the maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap() )); assert!(!>::contains_key(0)); let mut tampered_sig = sig.0.to_vec(); @@ -535,8 +545,8 @@ fn should_fail_to_verify_proposal_with_tampered_signature() { SignatureBridge::execute_proposal( RuntimeOrigin::signed(RELAYER_A), src_id.chain_id(), - prop_data, - tampered_sig.clone(), + prop_data.try_into().unwrap(), + tampered_sig.clone().try_into().unwrap(), ), pallet_signature_bridge::Error::::InvalidPermissions ); @@ -559,7 +569,10 @@ fn should_add_resource_sig_succeed_using_webb_proposals() { new_test_ext_for_set_resource_proposal_initialized(src_id.chain_id()).execute_with(|| { let curve = Curve::Bn254; let params = setup_params::(curve, 5, 3); - let _ = HasherPallet::force_set_parameters(RuntimeOrigin::root(), params.to_bytes()); + let _ = HasherPallet::force_set_parameters( + RuntimeOrigin::root(), + params.to_bytes().try_into().unwrap(), + ); let nonce = webb_proposals::Nonce::from(0x0001); let header = make_proposal_header(resource, SET_RESOURCE_FUNCTION_SIG, nonce); //create anchor @@ -576,14 +589,14 @@ fn should_add_resource_sig_succeed_using_webb_proposals() { // set the maintainer assert_ok!(SignatureBridge::force_set_maintainer( RuntimeOrigin::root(), - public_uncompressed.to_vec() + public_uncompressed.to_vec().try_into().unwrap(), )); assert_ok!(SignatureBridge::set_resource_with_signature( RuntimeOrigin::signed(RELAYER_A), src_id.chain_id(), - set_resource_proposal_bytes, - sig.0.to_vec(), + set_resource_proposal_bytes.try_into().unwrap(), + sig.0.to_vec().try_into().unwrap(), )); // the anchor-handler callback must have been called by bridge diff --git a/pallets/vanchor-verifier/src/lib.rs b/pallets/vanchor-verifier/src/lib.rs index ea586db5a..7e9c58d97 100644 --- a/pallets/vanchor-verifier/src/lib.rs +++ b/pallets/vanchor-verifier/src/lib.rs @@ -82,7 +82,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -99,6 +99,9 @@ pub mod pallet { /// privileged attributes. type ForceOrigin: EnsureOrigin; + /// The max parameter length accepted by the vanchor-verifier + type MaxParameterLength: Get; + /// WeightInfo for pallet type WeightInfo: WeightInfo; } @@ -107,7 +110,7 @@ pub mod pallet { pub struct GenesisConfig, I: 'static = ()> { pub phantom: (PhantomData, PhantomData), /// Optional vec of parameters (max edges, num_inputs, parameters) - pub parameters: Option)>>, + pub parameters: Option)>>, } #[cfg(feature = "std")] @@ -131,8 +134,13 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn parameters)] /// Details of the module's parameters for different vanchor configurations - pub(super) type Parameters, I: 'static = ()> = - StorageMap<_, Blake2_128Concat, (u8, u8), Vec, ValueQuery>; + pub(super) type Parameters, I: 'static = ()> = StorageMap< + _, + Blake2_128Concat, + (u8, u8), + BoundedVec, + ValueQuery, + >; #[pallet::event] pub enum Event, I: 'static = ()> {} @@ -151,10 +159,11 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { #[pallet::weight(T::WeightInfo::force_set_parameters(parameters.len() as u32))] + #[pallet::call_index(0)] pub fn force_set_parameters( origin: OriginFor, configuration: (u8, u8), - parameters: Vec, + parameters: BoundedVec, ) -> DispatchResultWithPostInfo { T::ForceOrigin::ensure_origin(origin)?; Parameters::::try_mutate(configuration, |params| { diff --git a/pallets/vanchor-verifier/src/mock.rs b/pallets/vanchor-verifier/src/mock.rs index 1b838f862..e5a0a4312 100644 --- a/pallets/vanchor-verifier/src/mock.rs +++ b/pallets/vanchor-verifier/src/mock.rs @@ -6,7 +6,7 @@ use frame_system as system; use sp_core::H256; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, ConstU32, IdentityLookup}, AccountId32, }; use sp_std::convert::{TryFrom, TryInto}; @@ -91,6 +91,7 @@ impl pallet_vanchor_verifier::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; type Verifier = ArkworksVerifierBn254; + type MaxParameterLength = ConstU32<100>; type WeightInfo = (); } diff --git a/pallets/vanchor/src/benchmarking.rs b/pallets/vanchor/src/benchmarking.rs index de5451f87..51f63655c 100644 --- a/pallets/vanchor/src/benchmarking.rs +++ b/pallets/vanchor/src/benchmarking.rs @@ -83,12 +83,12 @@ where assert_ok!(>::force_set_parameters( RawOrigin::Root.into(), (2, 2), - vk_2_2_bytes.clone() + vk_2_2_bytes.clone().try_into().unwrap() )); assert_ok!(>::force_set_parameters( RawOrigin::Root.into(), (2, 16), - vk_2_16_bytes.clone() + vk_2_16_bytes.clone().try_into().unwrap() )); pk_2_2_bytes diff --git a/pallets/vanchor/src/lib.rs b/pallets/vanchor/src/lib.rs index b858efe14..ca3b8b65d 100644 --- a/pallets/vanchor/src/lib.rs +++ b/pallets/vanchor/src/lib.rs @@ -104,7 +104,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -323,6 +323,7 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { #[pallet::weight(>::WeightInfo::create(*depth as u32))] + #[pallet::call_index(0)] pub fn create( origin: OriginFor, max_edges: u32, @@ -343,6 +344,7 @@ pub mod pallet { #[transactional] #[pallet::weight(>::WeightInfo::transact())] + #[pallet::call_index(1)] pub fn transact( origin: OriginFor, id: T::TreeId, @@ -356,6 +358,7 @@ pub mod pallet { #[transactional] #[pallet::weight(>::WeightInfo::register_and_transact())] + #[pallet::call_index(2)] pub fn register_and_transact( origin: OriginFor, owner: T::AccountId, @@ -372,6 +375,7 @@ pub mod pallet { } #[pallet::weight(>::WeightInfo::set_max_deposit_amount())] + #[pallet::call_index(3)] pub fn set_max_deposit_amount( origin: OriginFor, max_deposit_amount: BalanceOf, @@ -383,6 +387,7 @@ pub mod pallet { } #[pallet::weight(>::WeightInfo::set_min_withdraw_amount())] + #[pallet::call_index(4)] pub fn set_min_withdraw_amount( origin: OriginFor, min_withdraw_amount: BalanceOf, diff --git a/pallets/vanchor/src/mock.rs b/pallets/vanchor/src/mock.rs index 96663f1a4..2530a0697 100644 --- a/pallets/vanchor/src/mock.rs +++ b/pallets/vanchor/src/mock.rs @@ -7,9 +7,10 @@ use sp_core::H256; use frame_support::{parameter_types, traits::Nothing, PalletId}; use frame_system as system; use orml_currencies::{BasicCurrencyAdapter, NativeCurrencyOf}; +use scale_info::TypeInfo; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, ConstU32, IdentityLookup}, Permill, }; use sp_std::convert::{TryFrom, TryInto}; @@ -116,6 +117,7 @@ parameter_types! { impl pallet_vanchor_verifier::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; + type MaxParameterLength = ConstU32<10000>; type Verifier = ArkworksVerifierBn254; type WeightInfo = (); } @@ -123,6 +125,7 @@ impl pallet_vanchor_verifier::Config for Test { impl pallet_hasher::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; + type MaxParameterLength = ConstU32<10000>; type Hasher = ArkworksPoseidonHasherBn254; type WeightInfo = (); } @@ -141,12 +144,21 @@ parameter_types! { ]); } +parameter_types! { + #[derive(Debug, TypeInfo)] + pub const MaxEdges: u32 = 1000; + #[derive(Debug, TypeInfo)] + pub const MaxDefaultHashes: u32 = 1000; +} + impl pallet_mt::Config for Test { type Currency = Balances; type DataDepositBase = LeafDepositBase; type DataDepositPerByte = LeafDepositPerByte; type DefaultZeroElement = DefaultZeroElement; type Element = Element; + type MaxEdges = MaxEdges; + type MaxDefaultHashes = MaxDefaultHashes; type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; type Hasher = HasherPallet; @@ -207,12 +219,18 @@ impl orml_currencies::Config for Test { type WeightInfo = (); } +parameter_types! { + #[derive(Copy, Clone, Debug, PartialEq, Eq, scale_info::TypeInfo)] + pub const MaxAssetIdInPool: u32 = 100; +} + impl pallet_asset_registry::Config for Test { type AssetId = AssetId; type AssetNativeLocation = (); type Balance = u128; type RuntimeEvent = RuntimeEvent; type NativeAssetId = NativeCurrencyId; + type MaxAssetIdInPool = MaxAssetIdInPool; type RegistryOrigin = frame_system::EnsureRoot; type StringLimit = RegistryStringLimit; type WeightInfo = (); @@ -294,6 +312,8 @@ impl pallet_vanchor::Config for Test { impl pallet_key_storage::Config for Test { type RuntimeEvent = RuntimeEvent; + type MaxPubkeyLength = ConstU32<1000>; + type MaxPubKeyOwners = ConstU32<1000>; type WeightInfo = (); } diff --git a/pallets/vanchor/src/tests.rs b/pallets/vanchor/src/tests.rs index a0e0e08d0..48dee7896 100644 --- a/pallets/vanchor/src/tests.rs +++ b/pallets/vanchor/src/tests.rs @@ -43,7 +43,10 @@ fn setup_environment() -> (Vec, Vec, Vec, Vec) { let curve = Curve::Bn254; let params3 = setup_params::(curve, 5, 3); // 1. Setup The Hasher Pallet. - assert_ok!(HasherPallet::force_set_parameters(RuntimeOrigin::root(), params3.to_bytes())); + assert_ok!(HasherPallet::force_set_parameters( + RuntimeOrigin::root(), + params3.to_bytes().try_into().unwrap() + )); // 2. Initialize MerkleTree pallet. >::on_initialize(1); // 3. Setup the VerifierPallet @@ -68,12 +71,12 @@ fn setup_environment() -> (Vec, Vec, Vec, Vec) { assert_ok!(VAnchorVerifier::force_set_parameters( RuntimeOrigin::root(), (2, 2), - vk_2_2_bytes.clone() + vk_2_2_bytes.clone().try_into().unwrap() )); assert_ok!(VAnchorVerifier::force_set_parameters( RuntimeOrigin::root(), (2, 16), - vk_2_16_bytes.clone() + vk_2_16_bytes.clone().try_into().unwrap() )); let transactor = account::("", TRANSACTOR_ACCOUNT_ID, SEED); @@ -395,8 +398,8 @@ fn should_complete_2x2_transaction_with_withdraw_unwrap_and_refund_native_token( // Register a new wrapped asset / pool share over native assets assert_ok!(AssetRegistry::register( RuntimeOrigin::root(), - b"webbWEBB".to_vec(), - AssetType::PoolShare(vec![0]), + b"webbWEBB".to_vec().try_into().unwrap(), + AssetType::PoolShare(vec![0].try_into().unwrap()), 0 )); let asset_id = AssetRegistry::next_asset_id() - 1; @@ -576,7 +579,7 @@ fn should_complete_2x2_transaction_with_withdraw_unwrap_and_refund_non_native_to // Register a new asset that will be wrapped assert_ok!(AssetRegistry::register( RuntimeOrigin::root(), - b"temp".to_vec(), + b"temp".to_vec().try_into().unwrap(), AssetType::Token, 0 )); @@ -584,8 +587,8 @@ fn should_complete_2x2_transaction_with_withdraw_unwrap_and_refund_non_native_to assert_ok!(Tokens::set_balance(RuntimeOrigin::root(), alice, first_asset_id, 10_000, 0)); assert_ok!(AssetRegistry::register( RuntimeOrigin::root(), - b"webbTemp".to_vec(), - AssetType::PoolShare(vec![first_asset_id]), + b"webbTemp".to_vec().try_into().unwrap(), + AssetType::PoolShare(vec![first_asset_id].try_into().unwrap()), 0 )); let pooled_asset_id = AssetRegistry::next_asset_id() - 1; diff --git a/pallets/verifier/src/lib.rs b/pallets/verifier/src/lib.rs index deb6bf795..64a78c7dc 100644 --- a/pallets/verifier/src/lib.rs +++ b/pallets/verifier/src/lib.rs @@ -79,7 +79,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::config] @@ -96,6 +96,9 @@ pub mod pallet { /// privileged attributes. type ForceOrigin: EnsureOrigin; + /// The max parameter length accepted by the verifier + type MaxParameterLength: Get; + /// WeightInfo for pallet type WeightInfo: WeightInfo; } @@ -103,7 +106,7 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig, I: 'static = ()> { pub phantom: (PhantomData, PhantomData), - pub parameters: Option>, + pub parameters: Option>, } #[cfg(feature = "std")] @@ -126,7 +129,7 @@ pub mod pallet { #[pallet::getter(fn parameters)] /// Details of the module's parameters pub(super) type Parameters, I: 'static = ()> = - StorageValue<_, Vec, ValueQuery>; + StorageValue<_, BoundedVec, ValueQuery>; #[pallet::event] pub enum Event, I: 'static = ()> {} @@ -145,9 +148,10 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { #[pallet::weight(T::WeightInfo::force_set_parameters(parameters.len() as u32))] + #[pallet::call_index(0)] pub fn force_set_parameters( origin: OriginFor, - parameters: Vec, + parameters: BoundedVec, ) -> DispatchResultWithPostInfo { T::ForceOrigin::ensure_origin(origin)?; Parameters::::try_mutate(|params| { diff --git a/pallets/verifier/src/mock.rs b/pallets/verifier/src/mock.rs index 2ff729467..a1f8b9781 100644 --- a/pallets/verifier/src/mock.rs +++ b/pallets/verifier/src/mock.rs @@ -6,7 +6,7 @@ use frame_system as system; use sp_core::H256; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, ConstU32, IdentityLookup}, AccountId32, }; use sp_std::convert::{TryFrom, TryInto}; @@ -90,6 +90,7 @@ parameter_types! { impl pallet_verifier::Config for Test { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; + type MaxParameterLength = ConstU32<100>; type Verifier = ArkworksVerifierBn254; type WeightInfo = (); } diff --git a/pallets/xanchor/src/lib.rs b/pallets/xanchor/src/lib.rs index 431bad3dc..fb89d34e7 100644 --- a/pallets/xanchor/src/lib.rs +++ b/pallets/xanchor/src/lib.rs @@ -117,7 +117,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); /// The module configuration trait. @@ -223,6 +223,7 @@ pub mod pallet { /// /// TODO: Add a bond (a payment that gets locked up) when calling this xt. #[pallet::weight(0)] + #[pallet::call_index(0)] pub fn propose_to_link_anchor( origin: OriginFor, payload: LinkProposalOf, @@ -274,6 +275,7 @@ pub mod pallet { /// **Note**: This method requires the `origin` to be /// [T::DemocracyOrigin]. #[pallet::weight(0)] + #[pallet::call_index(1)] pub fn send_link_anchor_message( origin: OriginFor, payload: LinkProposalOf, @@ -318,6 +320,7 @@ pub mod pallet { /// parachain. #[transactional] #[pallet::weight(0)] + #[pallet::call_index(2)] pub fn save_link_proposal( origin: OriginFor, payload: LinkProposalOf, @@ -354,6 +357,7 @@ pub mod pallet { /// It also signals back to the caller chain with the proposal /// hash, so the caller chain knows that the link process is complete. #[pallet::weight(0)] + #[pallet::call_index(2)] pub fn handle_link_anchor_message( origin: OriginFor, payload: LinkProposalOf, @@ -384,6 +388,7 @@ pub mod pallet { /// **Note**: This method requires the `origin` to be the democracy. #[pallet::weight(0)] + #[pallet::call_index(3)] pub fn link_anchors( origin: OriginFor, payload: LinkProposalOf, @@ -427,6 +432,7 @@ pub mod pallet { /// Handles the signal back from the other parachain, if the link /// process is there is done to complete the link process here too. #[pallet::weight(0)] + #[pallet::call_index(4)] pub fn handle_link_anchors( origin: OriginFor, payload: LinkProposalOf, @@ -466,6 +472,7 @@ pub mod pallet { /// /// **Note**: Only could be called by [T::DemocracyOrigin]. #[pallet::weight(0)] + #[pallet::call_index(5)] pub fn register_resource_id( origin: OriginFor, r_id: ResourceId, @@ -479,6 +486,7 @@ pub mod pallet { /// A Forced version of [Self::register_resource_id] which can be only /// called by the Root. #[pallet::weight(0)] + #[pallet::call_index(6)] pub fn force_register_resource_id( origin: OriginFor, r_id: ResourceId, @@ -490,6 +498,7 @@ pub mod pallet { } #[pallet::weight(0)] + #[pallet::call_index(7)] pub fn update( origin: OriginFor, anchor_update_proposal_bytes: Vec, @@ -536,6 +545,7 @@ pub mod pallet { } #[pallet::weight(0)] + #[pallet::call_index(8)] pub fn force_update( origin: OriginFor, r_id: ResourceId, @@ -553,6 +563,7 @@ pub mod pallet { /// Sync All the Anchors in this chain to the other chains that are /// already linked. #[pallet::weight(0)] + #[pallet::call_index(9)] pub fn sync_anchors(origin: OriginFor) -> DispatchResultWithPostInfo { ensure_signed(origin)?; let vanchors = pallet_vanchor::Anchors::::iter_keys(); diff --git a/pallets/xanchor/src/mock/parachain.rs b/pallets/xanchor/src/mock/parachain.rs index 444fdb89a..831cc3985 100644 --- a/pallets/xanchor/src/mock/parachain.rs +++ b/pallets/xanchor/src/mock/parachain.rs @@ -184,7 +184,7 @@ pub mod mock_msg_queue { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] + pub struct Pallet(_); #[pallet::storage] diff --git a/primitives/src/runtime.rs b/primitives/src/runtime.rs index 6e2c0a474..8a38ea0fd 100644 --- a/primitives/src/runtime.rs +++ b/primitives/src/runtime.rs @@ -61,7 +61,18 @@ pub mod opaque { pub type BlockId = generic::BlockId; } -#[derive(Debug, Encode, Decode, Default, Copy, Clone, PartialEq, Eq, scale_info::TypeInfo)] +#[derive( + Debug, + Encode, + Decode, + Default, + Copy, + Clone, + PartialEq, + Eq, + scale_info::TypeInfo, + codec::MaxEncodedLen, +)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] pub struct Element(pub [u8; 32]); diff --git a/primitives/src/types/mod.rs b/primitives/src/types/mod.rs index 9c49f4579..33e5e72cf 100644 --- a/primitives/src/types/mod.rs +++ b/primitives/src/types/mod.rs @@ -1,7 +1,7 @@ pub mod runtime; pub mod vanchor; -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; pub use ethabi::{encode, Token}; use frame_support::pallet_prelude::*; use scale_info::TypeInfo; @@ -11,7 +11,7 @@ use sp_std::vec::Vec; // Deposit details used in hasher / verifier pallets for // tracking the reserved deposits of maintainers of various // parameters -#[derive(Clone, Default, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)] +#[derive(Clone, Default, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct DepositDetails { pub depositor: AccountId, pub deposit: Balance, diff --git a/primitives/src/types/vanchor.rs b/primitives/src/types/vanchor.rs index dcd14dc80..593bf76a6 100644 --- a/primitives/src/types/vanchor.rs +++ b/primitives/src/types/vanchor.rs @@ -1,9 +1,9 @@ use super::{ElementTrait, IntoAbiToken, Token}; -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_std::vec::Vec; -#[derive(Clone, Encode, Decode, TypeInfo)] +#[derive(Clone, Encode, Decode, TypeInfo, MaxEncodedLen)] pub struct VAnchorMetadata { /// Creator account pub creator: Option, diff --git a/standalone/node/Cargo.toml b/standalone/node/Cargo.toml index a72855762..f8971d341 100644 --- a/standalone/node/Cargo.toml +++ b/standalone/node/Cargo.toml @@ -65,6 +65,7 @@ sc-network-common = { git = "https://github.com/paritytech/substrate", branch = sc-basic-authorship = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } sp-authorship = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } sp-finality-grandpa = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.36" } sp-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } diff --git a/standalone/node/src/chain_spec.rs b/standalone/node/src/chain_spec.rs index 2c6f564c4..651a9d517 100644 --- a/standalone/node/src/chain_spec.rs +++ b/standalone/node/src/chain_spec.rs @@ -11,6 +11,7 @@ use sp_runtime::{ traits::{IdentifyAccount, Verify}, Perbill, }; +use sp_std::convert::TryInto; use webb_runtime::{ constants::currency::*, wasm_binary_unwrap, AssetRegistryConfig, AuthorityDiscoveryConfig, BabeConfig, Block, CouncilConfig, DemocracyConfig, ElectionsConfig, GenesisConfig, @@ -246,8 +247,8 @@ fn testnet_genesis( GenesisConfig { system: webb_runtime::SystemConfig { code: wasm_binary_unwrap().to_vec() }, asset_registry: AssetRegistryConfig { - asset_names: vec![(b"TEST".to_vec(), 1)], - native_asset_name: b"WEBB".to_vec(), + asset_names: vec![(b"TEST".to_vec().try_into().unwrap(), 1)], + native_asset_name: b"WEBB".to_vec().try_into().unwrap(), native_existential_deposit: webb_runtime::constants::currency::EXISTENTIAL_DEPOSIT, }, tokens: webb_runtime::TokensConfig { @@ -300,17 +301,17 @@ fn testnet_genesis( grandpa: GrandpaConfig { authorities: vec![] }, treasury: Default::default(), hasher_bn_254: HasherBn254Config { - parameters: Some(bn254_x5_3_params.to_bytes()), + parameters: Some(bn254_x5_3_params.to_bytes().try_into().unwrap()), phantom: Default::default(), }, mixer_verifier_bn_254: MixerVerifierBn254Config { - parameters: Some(mixer_verifier_bn254_params), + parameters: Some(mixer_verifier_bn254_params.try_into().unwrap()), phantom: Default::default(), }, v_anchor_verifier: VAnchorVerifierConfig { parameters: Some(vec![ - (2, 2, vanchor_verifier_2_2_bn254_params), - (2, 16, vanchor_verifier_2_16_bn254_params), + (2, 2, vanchor_verifier_2_2_bn254_params.try_into().unwrap()), + (2, 16, vanchor_verifier_2_16_bn254_params.try_into().unwrap()), ]), phantom: Default::default(), }, diff --git a/standalone/node/src/service.rs b/standalone/node/src/service.rs index 381466868..00670cf24 100644 --- a/standalone/node/src/service.rs +++ b/standalone/node/src/service.rs @@ -17,6 +17,7 @@ // along with this program. If not, see . #![warn(unused_extern_crates)] +#![allow(clippy::type_complexity)] //! Service implementation. Specialized wrapper over substrate service. diff --git a/standalone/runtime/src/lib.rs b/standalone/runtime/src/lib.rs index ae441709e..6b2fe6ba6 100644 --- a/standalone/runtime/src/lib.rs +++ b/standalone/runtime/src/lib.rs @@ -78,7 +78,7 @@ use frame_support::{ KeyOwnerProofSystem, LockIdentifier, OnUnbalanced, U128CurrencyToVote, }, weights::{ - constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_REF_TIME_PER_SECOND}, + constants::{BlockExecutionWeight, WEIGHT_REF_TIME_PER_SECOND}, IdentityFee, Weight, }, PalletId, RuntimeDebug, @@ -1108,6 +1108,7 @@ impl pallet_hasher::Config for Runtime { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; type Hasher = ArkworksPoseidonHasherBn254; + type MaxParameterLength = ConstU32<10000>; type WeightInfo = pallet_hasher::weights::WebbWeight; } @@ -1125,6 +1126,10 @@ parameter_types! { 47, 229, 76, 96, 211, 172, 171, 243, 52, 58, 53, 182, 235, 161, 93, 180, 130, 27, 52, 15, 118, 231, 65, 226, 36, 150, 133, 237, 72, 153, 175, 108, ]); + #[derive(Debug, scale_info::TypeInfo)] + pub const MaxEdges: u32 = 1000; + #[derive(Debug, scale_info::TypeInfo)] + pub const MaxDefaultHashes: u32 = 1000; } impl pallet_mt::Config for Runtime { @@ -1141,16 +1146,23 @@ impl pallet_mt::Config for Runtime { type RootHistorySize = RootHistorySize; type RootIndex = u32; type StringLimit = StringLimit; + type MaxEdges = MaxEdges; + type MaxDefaultHashes = MaxDefaultHashes; type TreeDeposit = TreeDeposit; type TreeId = u32; type Two = Two; type WeightInfo = pallet_mt::weights::WebbWeight; } +parameter_types! { + pub const MaxParameterLength : u32 = 1000; +} + impl pallet_verifier::Config for Runtime { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; type Verifier = ArkworksVerifierBn254; + type MaxParameterLength = MaxParameterLength; type WeightInfo = pallet_verifier::weights::WebbWeight; } @@ -1158,15 +1170,22 @@ impl pallet_vanchor_verifier::Config for Runtime { type RuntimeEvent = RuntimeEvent; type ForceOrigin = frame_system::EnsureRoot; type Verifier = ArkworksVerifierBn254; + type MaxParameterLength = MaxParameterLength; type WeightInfo = pallet_vanchor_verifier::weights::WebbWeight; } +parameter_types! { + #[derive(Copy, Clone, Debug, PartialEq, Eq, scale_info::TypeInfo)] + pub const MaxAssetIdInPool: u32 = 100; +} + impl pallet_asset_registry::Config for Runtime { type AssetId = webb_primitives::AssetId; type AssetNativeLocation = u32; type Balance = Balance; type RuntimeEvent = RuntimeEvent; type NativeAssetId = GetNativeCurrencyId; + type MaxAssetIdInPool = MaxAssetIdInPool; type RegistryOrigin = frame_system::EnsureRoot; type StringLimit = RegistryStringLimit; type WeightInfo = (); @@ -1326,6 +1345,7 @@ impl Contains for ExecuteProposalFilter { parameter_types! { pub const ProposalLifetime: BlockNumber = 50; pub const BridgeAccountId: PalletId = PalletId(*b"dw/bridg"); + pub const MaxStringLength: u32 = 1000; } type SignatureBridgeInstance = pallet_signature_bridge::Instance1; @@ -1338,6 +1358,7 @@ impl pallet_signature_bridge::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Proposal = RuntimeCall; type ProposalLifetime = ProposalLifetime; + type MaxStringLength = MaxStringLength; type ProposalNonce = u32; type SetResourceProposalFilter = SetResourceProposalFilter; type ExecuteProposalFilter = ExecuteProposalFilter; @@ -1386,6 +1407,8 @@ impl pallet_relayer_registry::Config for Runtime { impl pallet_key_storage::Config for Runtime { type RuntimeEvent = RuntimeEvent; + type MaxPubkeyLength = ConstU32<1000>; + type MaxPubKeyOwners = ConstU32<100>; type WeightInfo = pallet_key_storage::weights::WebbWeight; }