difftreelog
Merge pull request #974 from UniqueNetwork/fix/evm-coder-leftovers
in: master
25 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -528,7 +528,7 @@
|r: sc_service::Result<
up_data_structs::TokenDataVersion1<CrossAccountId>,
sp_runtime::DispatchError,
- >| r.and_then(|value| Ok(value.into())),
+ >| r.map(|value| value.into()),
)
.or_else(|_| {
Ok(api
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -297,7 +297,7 @@
default_runtime,
// Sudo account
get_account_id_from_seed::<sr25519::Public>("Alice"),
- vec![
+ [
(
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_from_seed::<AuraId>("Alice"),
@@ -371,7 +371,7 @@
default_runtime,
// Sudo account
get_account_id_from_seed::<sr25519::Public>("Alice"),
- vec![
+ [
(
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_from_seed::<AuraId>("Alice"),
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -63,7 +63,7 @@
}
let bytes = id.to_string();
let len = data.len();
- data[len - bytes.len()..].copy_from_slice(&bytes.as_bytes());
+ data[len - bytes.len()..].copy_from_slice(bytes.as_bytes());
data
}
pub fn property_value() -> PropertyValue {
@@ -80,7 +80,7 @@
cast: impl FnOnce(CollectionHandle<T>) -> R,
) -> Result<R, DispatchError> {
let imbalance = <T as Config>::Currency::deposit(
- &owner.as_sub(),
+ owner.as_sub(),
T::CollectionCreationPrice::get(),
Precision::Exact,
)?;
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -2420,7 +2420,8 @@
}
}
-#[cfg(feature = "tests")]
+#[cfg(any(feature = "tests", test))]
+#[allow(missing_docs)]
pub mod tests {
use crate::{DispatchResult, DispatchError, LazyValue, Config};
@@ -2456,7 +2457,7 @@
}
#[rustfmt::skip]
- pub const table: [TestCase; 16] = [
+ pub const TABLE: [TestCase; 16] = [
// ┌╴collection_admin
// │ ┌╴is_collection_admin
// │ │ ┌╴token_owner
pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -286,7 +286,14 @@
{
let call = C::parse_full(input)?;
if call.is_none() {
- return Err("unrecognized selector".into());
+ let selector = if input.len() >= 4 {
+ let mut selector = [0; 4];
+ selector.copy_from_slice(&input[..4]);
+ u32::from_be_bytes(selector)
+ } else {
+ 0
+ };
+ return Err(format!("unrecognized selector: 0x{selector:0>8x}").into());
}
let call = call.unwrap();
@@ -329,7 +336,7 @@
ERC165Call(ERC165Call, PhantomData<fn() -> T>),
OtherCall(ERC165Call),
- #[weight(Weight::from_ref_time(a + b))]
+ #[weight(Weight::from_parts(a + b, 0))]
Example {
a: u64,
b: u64,
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -53,7 +53,7 @@
let data = (0..b).map(|i| {
bench_init!(to: cross_sub(i););
(to, 200)
- }).collect::<BTreeMap<_, _>>().try_into().unwrap();
+ }).collect::<BTreeMap<_, _>>();
}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
burn_item {
pallets/identity/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/identity/src/benchmarking.rs
+++ b/pallets/identity/src/benchmarking.rs
@@ -35,6 +35,7 @@
//! Identity pallet benchmarking.
#![cfg(feature = "runtime-benchmarks")]
+#![allow(clippy::no_effect)]
use super::*;
pallets/identity/src/tests.rsdiffbeforeafterboth--- a/pallets/identity/src/tests.rs
+++ b/pallets/identity/src/tests.rs
@@ -67,7 +67,7 @@
parameter_types! {
pub BlockWeights: frame_system::limits::BlockWeights =
- frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::from_ref_time(1024));
+ frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::from_parts(1024, 0));
}
impl frame_system::Config for Test {
type BaseCallFilter = frame_support::traits::Everything;
pallets/identity/src/types.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435use super::*;36use codec::{Decode, Encode, MaxEncodedLen};37use enumflags2::{bitflags, BitFlags};38use frame_support::{39 traits::{ConstU32, Get},40 BoundedVec, CloneNoBound, PartialEqNoBound, RuntimeDebugNoBound,41};42use scale_info::{43 build::{Fields, Variants},44 meta_type, Path, Type, TypeInfo, TypeParameter,45};46use sp_runtime::{traits::Zero, RuntimeDebug};47use sp_std::{fmt::Debug, iter::once, ops::Add, prelude::*};4849/// Either underlying data blob if it is at most 32 bytes, or a hash of it. If the data is greater50/// than 32-bytes then it will be truncated when encoding.51///52/// Can also be `None`.53#[derive(Clone, Eq, PartialEq, RuntimeDebug, MaxEncodedLen)]54pub enum Data {55 /// No data here.56 None,57 /// The data is stored directly.58 Raw(BoundedVec<u8, ConstU32<32>>),59 /// Only the Blake2 hash of the data is stored. The preimage of the hash may be retrieved60 /// through some hash-lookup service.61 BlakeTwo256([u8; 32]),62 /// Only the SHA2-256 hash of the data is stored. The preimage of the hash may be retrieved63 /// through some hash-lookup service.64 Sha256([u8; 32]),65 /// Only the Keccak-256 hash of the data is stored. The preimage of the hash may be retrieved66 /// through some hash-lookup service.67 Keccak256([u8; 32]),68 /// Only the SHA3-256 hash of the data is stored. The preimage of the hash may be retrieved69 /// through some hash-lookup service.70 ShaThree256([u8; 32]),71}7273impl Data {74 pub fn is_none(&self) -> bool {75 self == &Data::None76 }77}7879impl Decode for Data {80 fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {81 let b = input.read_byte()?;82 Ok(match b {83 0 => Data::None,84 n @ 1..=33 => {85 let mut r: BoundedVec<_, _> = vec![0u8; n as usize - 1]86 .try_into()87 .expect("bound checked in match arm condition; qed");88 input.read(&mut r[..])?;89 Data::Raw(r)90 }91 34 => Data::BlakeTwo256(<[u8; 32]>::decode(input)?),92 35 => Data::Sha256(<[u8; 32]>::decode(input)?),93 36 => Data::Keccak256(<[u8; 32]>::decode(input)?),94 37 => Data::ShaThree256(<[u8; 32]>::decode(input)?),95 _ => return Err(codec::Error::from("invalid leading byte")),96 })97 }98}99100impl Encode for Data {101 fn encode(&self) -> Vec<u8> {102 match self {103 Data::None => vec![0u8; 1],104 Data::Raw(ref x) => {105 let l = x.len().min(32);106 let mut r = vec![l as u8 + 1; l + 1];107 r[1..].copy_from_slice(&x[..l]);108 r109 }110 Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),111 Data::Sha256(ref h) => once(35u8).chain(h.iter().cloned()).collect(),112 Data::Keccak256(ref h) => once(36u8).chain(h.iter().cloned()).collect(),113 Data::ShaThree256(ref h) => once(37u8).chain(h.iter().cloned()).collect(),114 }115 }116}117impl codec::EncodeLike for Data {}118119/// Add a Raw variant with the given index and a fixed sized byte array120macro_rules! data_raw_variants {121 ($variants:ident, $(($index:literal, $size:literal)),* ) => {122 $variants123 $(124 .variant(concat!("Raw", stringify!($size)), |v| v125 .index($index)126 .fields(Fields::unnamed().field(|f| f.ty::<[u8; $size]>()))127 )128 )*129 }130}131132impl TypeInfo for Data {133 type Identity = Self;134135 fn type_info() -> Type {136 let variants = Variants::new().variant("None", |v| v.index(0));137138 // create a variant for all sizes of Raw data from 0-32139 let variants = data_raw_variants!(140 variants,141 (1, 0),142 (2, 1),143 (3, 2),144 (4, 3),145 (5, 4),146 (6, 5),147 (7, 6),148 (8, 7),149 (9, 8),150 (10, 9),151 (11, 10),152 (12, 11),153 (13, 12),154 (14, 13),155 (15, 14),156 (16, 15),157 (17, 16),158 (18, 17),159 (19, 18),160 (20, 19),161 (21, 20),162 (22, 21),163 (23, 22),164 (24, 23),165 (25, 24),166 (26, 25),167 (27, 26),168 (28, 27),169 (29, 28),170 (30, 29),171 (31, 30),172 (32, 31),173 (33, 32)174 );175176 let variants = variants177 .variant("BlakeTwo256", |v| {178 v.index(34)179 .fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))180 })181 .variant("Sha256", |v| {182 v.index(35)183 .fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))184 })185 .variant("Keccak256", |v| {186 v.index(36)187 .fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))188 })189 .variant("ShaThree256", |v| {190 v.index(37)191 .fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))192 });193194 Type::builder()195 .path(Path::new("Data", module_path!()))196 .variant(variants)197 }198}199200impl Default for Data {201 fn default() -> Self {202 Self::None203 }204}205206/// An identifier for a single name registrar/identity verification service.207pub type RegistrarIndex = u32;208209/// An attestation of a registrar over how accurate some `IdentityInfo` is in describing an account.210///211/// NOTE: Registrars may pay little attention to some fields. Registrars may want to make clear212/// which fields their attestation is relevant for by off-chain means.213#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)]214pub enum Judgement<Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq>215{216 /// The default value; no opinion is held.217 Unknown,218 /// No judgement is yet in place, but a deposit is reserved as payment for providing one.219 FeePaid(Balance),220 /// The data appears to be reasonably acceptable in terms of its accuracy, however no in depth221 /// checks (such as in-person meetings or formal KYC) have been conducted.222 Reasonable,223 /// The target is known directly by the registrar and the registrar can fully attest to the224 /// the data's accuracy.225 KnownGood,226 /// The data was once good but is currently out of date. There is no malicious intent in the227 /// inaccuracy. This judgement can be removed through updating the data.228 OutOfDate,229 /// The data is imprecise or of sufficiently low-quality to be problematic. It is not230 /// indicative of malicious intent. This judgement can be removed through updating the data.231 LowQuality,232 /// The data is erroneous. This may be indicative of malicious intent. This cannot be removed233 /// except by the registrar.234 Erroneous,235}236237impl<Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq>238 Judgement<Balance>239{240 /// Returns `true` if this judgement is indicative of a deposit being currently held. This means241 /// it should not be cleared or replaced except by an operation which utilizes the deposit.242 pub(crate) fn has_deposit(&self) -> bool {243 matches!(self, Judgement::FeePaid(_))244 }245246 /// Returns `true` if this judgement is one that should not be generally be replaced outside247 /// of specialized handlers. Examples include "malicious" judgements and deposit-holding248 /// judgements.249 pub(crate) fn is_sticky(&self) -> bool {250 matches!(self, Judgement::FeePaid(_) | Judgement::Erroneous)251 }252}253254/// The fields that we use to identify the owner of an account with. Each corresponds to a field255/// in the `IdentityInfo` struct.256#[bitflags]257#[repr(u64)]258#[derive(Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]259pub enum IdentityField {260 Display = 0b0000000000000000000000000000000000000000000000000000000000000001,261 Legal = 0b0000000000000000000000000000000000000000000000000000000000000010,262 Web = 0b0000000000000000000000000000000000000000000000000000000000000100,263 Riot = 0b0000000000000000000000000000000000000000000000000000000000001000,264 Email = 0b0000000000000000000000000000000000000000000000000000000000010000,265 PgpFingerprint = 0b0000000000000000000000000000000000000000000000000000000000100000,266 Image = 0b0000000000000000000000000000000000000000000000000000000001000000,267 Twitter = 0b0000000000000000000000000000000000000000000000000000000010000000,268}269270/// Wrapper type for `BitFlags<IdentityField>` that implements `Codec`.271#[derive(Clone, Copy, PartialEq, Default, RuntimeDebug)]272pub struct IdentityFields(pub BitFlags<IdentityField>);273274impl MaxEncodedLen for IdentityFields {275 fn max_encoded_len() -> usize {276 u64::max_encoded_len()277 }278}279280impl Eq for IdentityFields {}281impl Encode for IdentityFields {282 fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {283 self.0.bits().using_encoded(f)284 }285}286impl Decode for IdentityFields {287 fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {288 let field = u64::decode(input)?;289 Ok(Self(290 <BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,291 ))292 }293}294impl TypeInfo for IdentityFields {295 type Identity = Self;296297 fn type_info() -> Type {298 Type::builder()299 .path(Path::new("BitFlags", module_path!()))300 .type_params(vec![TypeParameter::new(301 "T",302 Some(meta_type::<IdentityField>()),303 )])304 .composite(Fields::unnamed().field(|f| f.ty::<u64>().type_name("IdentityField")))305 }306}307308/// Information concerning the identity of the controller of an account.309///310/// NOTE: This should be stored at the end of the storage item to facilitate the addition of extra311/// fields in a backwards compatible way through a specialized `Decode` impl.312#[derive(313 CloneNoBound, Encode, Decode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo,314)]315#[codec(mel_bound())]316#[cfg_attr(test, derive(frame_support::DefaultNoBound))]317#[scale_info(skip_type_params(FieldLimit))]318pub struct IdentityInfo<FieldLimit: Get<u32>> {319 /// Additional fields of the identity that are not catered for with the struct's explicit320 /// fields.321 pub additional: BoundedVec<(Data, Data), FieldLimit>,322323 /// A reasonable display name for the controller of the account. This should be whatever it is324 /// that it is typically known as and should not be confusable with other entities, given325 /// reasonable context.326 ///327 /// Stored as UTF-8.328 pub display: Data,329330 /// The full legal name in the local jurisdiction of the entity. This might be a bit331 /// long-winded.332 ///333 /// Stored as UTF-8.334 pub legal: Data,335336 /// A representative website held by the controller of the account.337 ///338 /// NOTE: `https://` is automatically prepended.339 ///340 /// Stored as UTF-8.341 pub web: Data,342343 /// The Riot/Matrix handle held by the controller of the account.344 ///345 /// Stored as UTF-8.346 pub riot: Data,347348 /// The email address of the controller of the account.349 ///350 /// Stored as UTF-8.351 pub email: Data,352353 /// The PGP/GPG public key of the controller of the account.354 pub pgp_fingerprint: Option<[u8; 20]>,355356 /// A graphic image representing the controller of the account. Should be a company,357 /// organization or project logo or a headshot in the case of a human.358 pub image: Data,359360 /// The Twitter identity. The leading `@` character may be elided.361 pub twitter: Data,362}363364impl<FieldLimit: Get<u32>> IdentityInfo<FieldLimit> {365 pub(crate) fn fields(&self) -> IdentityFields {366 let mut res = <BitFlags<IdentityField>>::empty();367 if !self.display.is_none() {368 res.insert(IdentityField::Display);369 }370 if !self.legal.is_none() {371 res.insert(IdentityField::Legal);372 }373 if !self.web.is_none() {374 res.insert(IdentityField::Web);375 }376 if !self.riot.is_none() {377 res.insert(IdentityField::Riot);378 }379 if !self.email.is_none() {380 res.insert(IdentityField::Email);381 }382 if self.pgp_fingerprint.is_some() {383 res.insert(IdentityField::PgpFingerprint);384 }385 if !self.image.is_none() {386 res.insert(IdentityField::Image);387 }388 if !self.twitter.is_none() {389 res.insert(IdentityField::Twitter);390 }391 IdentityFields(res)392 }393}394395/// Information concerning the identity of the controller of an account.396///397/// NOTE: This is stored separately primarily to facilitate the addition of extra fields in a398/// backwards compatible way through a specialized `Decode` impl.399#[derive(400 CloneNoBound, Encode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo,401)]402#[codec(mel_bound())]403#[scale_info(skip_type_params(MaxJudgements, MaxAdditionalFields))]404pub struct Registration<405 Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq,406 MaxJudgements: Get<u32>,407 MaxAdditionalFields: Get<u32>,408> {409 /// Judgements from the registrars on this identity. Stored ordered by `RegistrarIndex`. There410 /// may be only a single judgement from each registrar.411 pub judgements: BoundedVec<(RegistrarIndex, Judgement<Balance>), MaxJudgements>,412413 /// Amount held on deposit for this information.414 pub deposit: Balance,415416 /// Information on the identity.417 pub info: IdentityInfo<MaxAdditionalFields>,418}419420impl<421 Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq + Zero + Add,422 MaxJudgements: Get<u32>,423 MaxAdditionalFields: Get<u32>,424 > Registration<Balance, MaxJudgements, MaxAdditionalFields>425{426 pub(crate) fn total_deposit(&self) -> Balance {427 self.deposit428 + self429 .judgements430 .iter()431 .map(|(_, ref j)| {432 if let Judgement::FeePaid(fee) = j {433 *fee434 } else {435 Zero::zero()436 }437 })438 .fold(Zero::zero(), |a, i| a + i)439 }440}441442impl<443 Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq,444 MaxJudgements: Get<u32>,445 MaxAdditionalFields: Get<u32>,446 > Decode for Registration<Balance, MaxJudgements, MaxAdditionalFields>447{448 fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {449 let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?;450 Ok(Self {451 judgements,452 deposit,453 info,454 })455 }456}457458/// Information concerning a registrar.459#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)]460pub struct RegistrarInfo<461 Balance: Encode + Decode + Clone + Debug + Eq + PartialEq,462 AccountId: Encode + Decode + Clone + Debug + Eq + PartialEq,463> {464 /// The account of the registrar.465 pub account: AccountId,466467 /// Amount required to be given to the registrar for them to provide judgement.468 pub fee: Balance,469470 /// Relevant fields for this registrar. Registrar judgements are limited to attestations on471 /// these fields.472 pub fields: IdentityFields,473}474475#[cfg(test)]476mod tests {477 use super::*;478479 #[test]480 fn manual_data_type_info() {481 let mut registry = scale_info::Registry::new();482 let type_id = registry.register_type(&scale_info::meta_type::<Data>());483 let registry: scale_info::PortableRegistry = registry.into();484 let type_info = registry.resolve(type_id.id).unwrap();485486 let check_type_info = |data: &Data| {487 let variant_name = match data {488 Data::None => "None".to_string(),489 Data::BlakeTwo256(_) => "BlakeTwo256".to_string(),490 Data::Sha256(_) => "Sha256".to_string(),491 Data::Keccak256(_) => "Keccak256".to_string(),492 Data::ShaThree256(_) => "ShaThree256".to_string(),493 Data::Raw(bytes) => format!("Raw{}", bytes.len()),494 };495 if let scale_info::TypeDef::Variant(variant) = &type_info.type_def {496 let variant = variant497 .variants498 .iter()499 .find(|v| v.name == variant_name)500 .expect(&format!("Expected to find variant {}", variant_name));501502 let field_arr_len = variant503 .fields504 .first()505 .and_then(|f| registry.resolve(f.ty.id))506 .map(|ty| {507 if let scale_info::TypeDef::Array(arr) = &ty.type_def {508 arr.len509 } else {510 panic!("Should be an array type")511 }512 })513 .unwrap_or(0);514515 let encoded = data.encode();516 assert_eq!(encoded[0], variant.index);517 assert_eq!(encoded.len() as u32 - 1, field_arr_len);518 } else {519 panic!("Should be a variant type")520 };521 };522523 let mut data = vec![524 Data::None,525 Data::BlakeTwo256(Default::default()),526 Data::Sha256(Default::default()),527 Data::Keccak256(Default::default()),528 Data::ShaThree256(Default::default()),529 ];530531 // A Raw instance for all possible sizes of the Raw data532 for n in 0..32 {533 data.push(Data::Raw(vec![0u8; n as usize].try_into().unwrap()))534 }535536 for d in data.iter() {537 check_type_info(d);538 }539 }540}pallets/inflation/src/tests.rsdiffbeforeafterboth--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -78,7 +78,7 @@
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub BlockWeights: frame_system::limits::BlockWeights =
- frame_system::limits::BlockWeights::simple_max(Weight::from_ref_time(1024));
+ frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1024, 0));
pub const SS58Prefix: u8 = 42;
}
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -43,12 +43,12 @@
owner: T::CrossAccountId,
) -> Result<TokenId, DispatchError> {
<Pallet<T>>::create_item(
- &collection,
+ collection,
sender,
create_max_item_data::<T>(owner),
&Unlimited,
)?;
- Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
+ Ok(TokenId(<TokensMinted<T>>::get(collection.id)))
}
fn create_collection<T: Config>(
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -51,8 +51,8 @@
users: impl IntoIterator<Item = (T::CrossAccountId, u128)>,
) -> Result<TokenId, DispatchError> {
let data: CreateItemData<T> = create_max_item_data::<T>(users);
- <Pallet<T>>::create_item(&collection, sender, data, &Unlimited)?;
- Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
+ <Pallet<T>>::create_item(collection, sender, data, &Unlimited)?;
+ Ok(TokenId(<TokensMinted<T>>::get(collection.id)))
}
fn create_collection<T: Config>(
@@ -104,7 +104,7 @@
let data = vec![create_max_item_data::<T>((0..b).map(|u| {
bench_init!(to: cross_sub(u););
(to, 200)
- }))].try_into().unwrap();
+ }))];
}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}
// Other user left, token data is kept
pallets/scheduler-v2/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/scheduler-v2/src/benchmarking.rs
+++ b/pallets/scheduler-v2/src/benchmarking.rs
@@ -83,11 +83,11 @@
///
/// # Arguments
/// * `periodic` - makes the task periodic.
-/// Sets the task's period and repetition count to `100`.
+/// Sets the task's period and repetition count to `100`.
/// * `named` - gives a name to the task: `u32_to_name(0)`.
/// * `signed` - determines the origin of the task.
-/// If true, it will have the Signed origin. Otherwise it will have the Root origin.
-/// See [`make_origin`] for details.
+/// If true, it will have the Signed origin. Otherwise it will have the Root origin.
+/// See [`make_origin`] for details.
/// * maybe_lookup_len - sets optional lookup length. It is used to benchmark task fetching from the `Preimages` store.
/// * priority - the task's priority.
fn make_task<T: Config>(
@@ -155,12 +155,10 @@
}
if maybe_lookup_len.is_some() {
len += 1;
+ } else if len > 0 {
+ len -= 1;
} else {
- if len > 0 {
- len -= 1;
- } else {
- break c;
- }
+ break c;
}
}
}
pallets/scheduler-v2/src/mock.rsdiffbeforeafterboth--- a/pallets/scheduler-v2/src/mock.rs
+++ b/pallets/scheduler-v2/src/mock.rs
@@ -33,6 +33,7 @@
// limitations under the License.
//! # Scheduler test environment.
+#![allow(deprecated)]
use super::*;
@@ -229,6 +230,10 @@
r => Err(O::from(r)),
})
}
+ #[cfg(feature = "runtime-benchmarks")]
+ fn try_successful_origin() -> Result<O, ()> {
+ Ok(O::from(RawOrigin::Root))
+ }
}
pub struct Executor;
pallets/scheduler-v2/src/tests.rsdiffbeforeafterboth--- a/pallets/scheduler-v2/src/tests.rs
+++ b/pallets/scheduler-v2/src/tests.rs
@@ -33,6 +33,7 @@
// limitations under the License.
//! # Scheduler tests.
+#![allow(deprecated)]
use super::*;
use crate::mock::{
pallets/structure/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/structure/src/benchmarking.rs
+++ b/pallets/structure/src/benchmarking.rs
@@ -19,8 +19,7 @@
use frame_benchmarking::{benchmarks, account};
use frame_support::traits::{fungible::Balanced, Get, tokens::Precision};
use up_data_structs::{
- CreateCollectionData, CollectionMode, CreateItemData, CollectionFlags, CreateNftData,
- budget::Unlimited,
+ CreateCollectionData, CollectionMode, CreateItemData, CreateNftData, budget::Unlimited,
};
use pallet_common::Config as CommonConfig;
use pallet_evm::account::CrossAccountId;
runtime/common/config/pallets/mod.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -24,8 +24,7 @@
weights::CommonWeights,
RelayChainBlockNumberProvider,
},
- Runtime, RuntimeEvent, RuntimeCall, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS,
- Balances,
+ Runtime, RuntimeEvent, RuntimeCall, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS, Balances,
};
use frame_support::traits::{ConstU32, ConstU64, Currency};
use up_common::{
runtime/common/ethereum/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -161,7 +161,8 @@
}
}
CollectionMode::ReFungible => {
- let call = <UniqueRefungibleCall<T>>::parse_full(&call_context.input).ok()??;
+ let call =
+ <UniqueRefungibleCall<T>>::parse_full(&call_context.input).ok()??;
refungible::call_sponsor(call, collection, who).map(|()| sponsor)
}
CollectionMode::Fungible(_) => {
runtime/common/tests/mod.rsdiffbeforeafterboth--- a/runtime/common/tests/mod.rs
+++ b/runtime/common/tests/mod.rs
@@ -16,7 +16,6 @@
use sp_runtime::{BuildStorage, Storage};
use sp_core::{Public, Pair};
-use sp_std::vec;
use up_common::types::AuraId;
use crate::{Runtime, GenesisConfig, ParachainInfoConfig, RuntimeEvent, System};
@@ -76,7 +75,7 @@
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
- let accounts = vec!["Alice", "Bob"];
+ let accounts = ["Alice", "Bob"];
let keys = accounts
.iter()
.map(|&acc| {
@@ -104,7 +103,7 @@
..GenesisConfig::default()
};
- cfg.build_storage().unwrap().into()
+ cfg.build_storage().unwrap()
}
#[cfg(not(feature = "collator-selection"))]
runtime/common/tests/xcm.rsdiffbeforeafterboth--- a/runtime/common/tests/xcm.rs
+++ b/runtime/common/tests/xcm.rs
@@ -26,7 +26,7 @@
const ALICE: AccountId = AccountId::new([0u8; 32]);
const BOB: AccountId = AccountId::new([1u8; 32]);
-const INITIAL_BALANCE: u128 = 1000000000000000000_0000; // 1000 UNQ
+const INITIAL_BALANCE: u128 = 10_000_000_000_000_000_000_000; // 10_000 UNQ
#[test]
pub fn xcm_transact_is_forbidden() {
runtime/tests/Cargo.tomldiffbeforeafterboth--- a/runtime/tests/Cargo.toml
+++ b/runtime/tests/Cargo.toml
@@ -5,7 +5,6 @@
[features]
default = ['refungible']
-tests = ['pallet-common/tests']
refungible = []
@@ -44,3 +43,6 @@
evm-coder = { workspace = true }
up-sponsorship = { workspace = true }
xcm = { workspace = true }
+
+[dev-dependencies]
+pallet-common = { workspace = true, features = ["tests"] }
runtime/tests/src/tests.rsdiffbeforeafterboth--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -99,7 +99,7 @@
.try_into()
.unwrap();
- let data: CreateCollectionData<u64> = CreateCollectionData {
+ let data = CreateCollectionData {
name: col_name1.try_into().unwrap(),
description: col_desc1.try_into().unwrap(),
token_prefix: token_prefix1.try_into().unwrap(),
@@ -204,14 +204,13 @@
let description: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
let token_prefix: Vec<u8> = b"token_prefix1\0".to_vec();
- let data: CreateCollectionData<<Test as frame_system::Config>::AccountId> =
- CreateCollectionData {
- name: name.try_into().unwrap(),
- description: description.try_into().unwrap(),
- token_prefix: token_prefix.try_into().unwrap(),
- mode: CollectionMode::NFT,
- ..Default::default()
- };
+ let data = CreateCollectionData {
+ name: name.try_into().unwrap(),
+ description: description.try_into().unwrap(),
+ token_prefix: token_prefix.try_into().unwrap(),
+ mode: CollectionMode::NFT,
+ ..Default::default()
+ };
let result = Unique::create_collection_ex(RuntimeOrigin::signed(acc), data);
assert_err!(result, <CommonError<Test>>::NotSufficientFounds);
@@ -225,7 +224,7 @@
let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
- let data: CreateCollectionData<u64> = CreateCollectionData {
+ let data = CreateCollectionData {
name: col_name1.try_into().unwrap(),
description: col_desc1.try_into().unwrap(),
token_prefix: token_prefix1.try_into().unwrap(),
@@ -2364,7 +2363,7 @@
let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
- let data: CreateCollectionData<u64> = CreateCollectionData {
+ let data = CreateCollectionData {
name: col_name1.try_into().unwrap(),
description: col_desc1.try_into().unwrap(),
token_prefix: token_prefix1.try_into().unwrap(),
@@ -2618,9 +2617,7 @@
mod check_token_permissions {
use super::*;
- use frame_support::once_cell::sync::Lazy;
use pallet_common::LazyValue;
- use sp_runtime::DispatchError;
fn test<FTE: FnOnce() -> bool>(
i: usize,
@@ -2662,7 +2659,7 @@
fn no_permission_only() {
new_test_ext().execute_with(|| {
let mut check_token_existence = LazyValue::new(|| true);
- for (i, row) in pallet_common::tests::table.iter().enumerate() {
+ for (i, row) in pallet_common::tests::TABLE.iter().enumerate() {
test(i, row, &mut check_token_existence);
}
});
@@ -2671,7 +2668,7 @@
#[test]
fn no_permission_and_token_not_found() {
new_test_ext().execute_with(|| {
- for (i, row) in pallet_common::tests::table.iter().enumerate() {
+ for (i, row) in pallet_common::tests::TABLE.iter().enumerate() {
// This is inside the loop to keep track of whether the lambda was called
let mut check_token_existence = LazyValue::new(|| false);
test(i, row, &mut check_token_existence);
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -106,15 +106,17 @@
flags: [CollectionFlag.Erc721metadata],
}, 'nft');
- await mintCollectionHelper(helper, alice, {
+ // User can not set Foreign flag itself
+
+ await expect(mintCollectionHelper(helper, alice, {
name: 'name', description: 'descr', tokenPrefix: 'COL',
flags: [CollectionFlag.Foreign],
- }, 'nft');
+ }, 'nft')).to.be.rejectedWith(/common.NoPermission/);
- await mintCollectionHelper(helper, alice, {
+ await expect(mintCollectionHelper(helper, alice, {
name: 'name', description: 'descr', tokenPrefix: 'COL',
flags: [CollectionFlag.Erc721metadata, CollectionFlag.Foreign],
- }, 'nft');
+ }, 'nft')).to.be.rejectedWith(/common.NoPermission/);
});
itSub('Create new collection with extra fields', async ({helper}) => {
tests/src/eth/collectionLimits.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionLimits.test.ts
+++ b/tests/src/eth/collectionLimits.test.ts
@@ -106,7 +106,7 @@
// Cannot disable limits
await expect(collectionEvm.methods
- .setCollectionLimit({field: CollectionLimitField.AccountTokenOwnership, value: {status: false, value: 200}})
+ .setCollectionLimit({field: CollectionLimitField.AccountTokenOwnership, value: {status: false, value: 0}})
.call()).to.be.rejectedWith('user can\'t disable limits');
await expect(collectionEvm.methods
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -41,7 +41,7 @@
for(const arg of args) {
if(typeof arg !== 'string')
continue;
- const skippedWarnings = ['1000:: Normal connection closure', 'Not decorating unknown runtime apis:', 'RPC methods not decorated:', 'Not decorating runtime apis'];
+ const skippedWarnings = ['1000:: Normal connection closure', 'Not decorating unknown runtime apis:', 'RPC methods not decorated:', 'Not decorating runtime apis', 'Bad input data provided to validate_transaction', 'account balance too low', '1006:: Abnormal Closure'];
const needToSkip = skippedWarnings.reduce((a, b) => a || arg.includes(b), false);
if(needToSkip || arg === 'Normal connection closure')
return;