difftreelog
Merge pull request #943 from UniqueNetwork/fix/clippy-warnings
in: master
36 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth110110111/// Helper function to generate a crypto pair from seed111/// Helper function to generate a crypto pair from seed112pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {112pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {113 TPublic::Pair::from_string(&format!("//{}", seed), None)113 TPublic::Pair::from_string(&format!("//{seed}"), None)114 .expect("static values are valid; qed")114 .expect("static values are valid; qed")115 .public()115 .public()116}116}node/cli/src/command.rsdiffbeforeafterboth83 "" | "local" => Box::new(chain_spec::local_testnet_config()),83 "" | "local" => Box::new(chain_spec::local_testnet_config()),84 path => {84 path => {85 let path = std::path::PathBuf::from(path);85 let path = std::path::PathBuf::from(path);86 let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)86 let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path)?)87 as Box<dyn sc_service::ChainSpec>;87 as Box<dyn sc_service::ChainSpec>;888889 match chain_spec.runtime_id() {89 match chain_spec.runtime_id() {352 &polkadot_cli,352 &polkadot_cli,353 config.tokio_handle.clone(),353 config.tokio_handle.clone(),354 )354 )355 .map_err(|err| format!("Relay chain argument error: {}", err))?;355 .map_err(|err| format!("Relay chain argument error: {err}"))?;356356357 cmd.run(config, polkadot_config)357 cmd.run(config, polkadot_config)358 })358 })464 runner.run_node_until_exit(|config| async move {464 runner.run_node_until_exit(|config| async move {465 let hwbench = if !cli.no_hardware_benchmarks {465 let hwbench = if !cli.no_hardware_benchmarks {466 config.database.path().map(|database_path| {466 config.database.path().map(|database_path| {467 let _ = std::fs::create_dir_all(&database_path);467 let _ = std::fs::create_dir_all(database_path);468 sc_sysinfo::gather_hwbench(Some(database_path))468 sc_sysinfo::gather_hwbench(Some(database_path))469 })469 })470 } else {470 } else {512512513 let state_version = Cli::native_runtime_version(&config.chain_spec).state_version();513 let state_version = Cli::native_runtime_version(&config.chain_spec).state_version();514 let block: Block = generate_genesis_block(&*config.chain_spec, state_version)514 let block: Block = generate_genesis_block(&*config.chain_spec, state_version)515 .map_err(|e| format!("{:?}", e))?;515 .map_err(|e| format!("{e:?}"))?;516 let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));516 let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));517 let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));517 let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));518518521 &polkadot_cli,521 &polkadot_cli,522 config.tokio_handle.clone(),522 config.tokio_handle.clone(),523 )523 )524 .map_err(|err| format!("Relay chain argument error: {}", err))?;524 .map_err(|err| format!("Relay chain argument error: {err}"))?;525525526 info!("Parachain id: {:?}", para_id);526 info!("Parachain id: {:?}", para_id);527 info!("Parachain Account: {}", parachain_account);527 info!("Parachain Account: {}", parachain_account);node/cli/src/service.rsdiffbeforeafterboth698{698{699 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;699 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;700700701 let block_import = ParachainBlockImport::new(client.clone(), backend.clone());701 let block_import = ParachainBlockImport::new(client.clone(), backend);702702703 cumulus_client_consensus_aura::import_queue::<703 cumulus_client_consensus_aura::import_queue::<704 sp_consensus_aura::sr25519::AuthorityPair,704 sp_consensus_aura::sr25519::AuthorityPair,709 _,709 _,710 >(cumulus_client_consensus_aura::ImportQueueParams {710 >(cumulus_client_consensus_aura::ImportQueueParams {711 block_import,711 block_import,712 client: client.clone(),712 client,713 create_inherent_data_providers: move |_, _| async move {713 create_inherent_data_providers: move |_, _| async move {714 let time = sp_timestamp::InherentDataProvider::from_system_time();714 let time = sp_timestamp::InherentDataProvider::from_system_time();715715787 telemetry.clone(),787 telemetry.clone(),788 );788 );789789790 let block_import = ParachainBlockImport::new(client.clone(), backend.clone());790 let block_import = ParachainBlockImport::new(client.clone(), backend);791791792 Ok(AuraConsensus::build::<792 Ok(AuraConsensus::build::<793 sp_consensus_aura::sr25519::AuthorityPair,793 sp_consensus_aura::sr25519::AuthorityPair,864 ExecutorDispatch: NativeExecutionDispatch + 'static,864 ExecutorDispatch: NativeExecutionDispatch + 'static,865{865{866 Ok(sc_consensus_manual_seal::import_queue(866 Ok(sc_consensus_manual_seal::import_queue(867 Box::new(client.clone()),867 Box::new(client),868 &task_manager.spawn_essential_handle(),868 &task_manager.spawn_essential_handle(),869 config.prometheus_registry(),869 config.prometheus_registry(),870 ))870 ))956956957 let collator = config.role.is_authority();957 let collator = config.role.is_authority();958958959 let select_chain = maybe_select_chain.clone();959 let select_chain = maybe_select_chain;960960961 if collator {961 if collator {962 let block_import =962 let block_import =node/rpc/src/lib.rsdiffbeforeafterboth289 io.merge(289 io.merge(290 Net::new(290 Net::new(291 client.clone(),291 client.clone(),292 network.clone(),292 network,293 // Whether to format the `peer_count` response as Hex (default) or not.293 // Whether to format the `peer_count` response as Hex (default) or not.294 true,294 true,295 )295 )pallets/app-promotion/src/lib.rsdiffbeforeafterboth296296297 if !block_pending.is_empty() {297 if !block_pending.is_empty() {298 block_pending.into_iter().for_each(|(staker, amount)| {298 block_pending.into_iter().for_each(|(staker, amount)| {299 Self::get_frozen_balance(&staker).map(|b| {299 if let Some(b) = Self::get_frozen_balance(&staker) {300 let new_state = b.checked_sub(&amount).unwrap_or_default();300 let new_state = b.checked_sub(&amount).unwrap_or_default();301301302 // In this case, setting a new state for the frozen funds cannot fail302 // In this case, setting a new state for the frozen funds cannot fail305 // that we cannot (in the current implementation) unfreeze more funds305 // that we cannot (in the current implementation) unfreeze more funds306 // than were originally frozen by the pallet. Either way, `on_initialize()` cannot fail.306 // than were originally frozen by the pallet. Either way, `on_initialize()` cannot fail.307 Self::set_freeze_unchecked(&staker, new_state);307 Self::set_freeze_unchecked(&staker, new_state);308 });308 };309 });309 });310 }310 }311311598 // this value is set for the stakers to whom the recalculation will be performed598 // this value is set for the stakers to whom the recalculation will be performed599 let next_recalc_block = current_recalc_block + config.recalculation_interval;599 let next_recalc_block = current_recalc_block + config.recalculation_interval;600600601 let mut storage_iterator = Self::get_next_calculated_key()601 let storage_iterator =602 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));602 Self::get_next_calculated_key().map_or(Staked::<T>::iter(), Staked::<T>::iter_from);603603604 PreviousCalculatedRecord::<T>::set(None);604 PreviousCalculatedRecord::<T>::set(None);605605658 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)658 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)659 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out659 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out660 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)660 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)661 while let Some((661 for ((current_id, staked_block), (amount, next_recalc_block_for_stake)) in662 (current_id, staked_block),663 (amount, next_recalc_block_for_stake),664 )) = storage_iterator.next()662 storage_iterator665 {663 {666 // last_id is not equal current_id when we switch to handling a new staker address664 // last_id is not equal current_id when we switch to handling a new staker address667 // or just start handling the very first address. In the latter case last_id will be None and665 // or just start handling the very first address. In the latter case last_id will be None and859 if acc_amount < balance_per_block {857 if acc_amount < balance_per_block {860 let res = (block, balance_per_block - acc_amount);858 let res = (block, balance_per_block - acc_amount);861 acc_amount = <BalanceOf<T>>::default();859 acc_amount = <BalanceOf<T>>::default();862 return Some(res);860 Some(res)863 } else {861 } else {864 acc_amount -= balance_per_block;862 acc_amount -= balance_per_block;865 will_deleted_stakes_count += 1;863 will_deleted_stakes_count += 1;866 return Some((block, <BalanceOf<T>>::default()));864 Some((block, <BalanceOf<T>>::default()))867 }865 }868 })866 })869 .collect::<Vec<_>>();867 .collect::<Vec<_>>();926 if amount.is_zero() {924 if amount.is_zero() {927 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(925 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(928 &T::FreezeIdentifier::get(),926 &T::FreezeIdentifier::get(),929 &staker,927 staker,930 )928 )931 } else {929 } else {932 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(930 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(1026 ) {1024 ) {1027 let income = Self::calculate_income(base, iters);1025 let income = Self::calculate_income(base, iters);102810261029 base.checked_add(&income).map(|res| {1027 if let Some(res) = base.checked_add(&income) {1030 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1028 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1031 *income_acc += income;1029 *income_acc += income;1032 });1030 };1033 }1031 }103410321035 fn calculate_income<I>(base: I, iters: u32) -> I1033 fn calculate_income<I>(base: I, iters: u32) -> Ipallets/app-promotion/src/types.rsdiffbeforeafterboth149 Self {149 Self {150 recalculation_interval: config150 recalculation_interval: config151 .recalculation_interval151 .recalculation_interval152 .unwrap_or_else(|| T::RecalculationInterval::get()),152 .unwrap_or_else(T::RecalculationInterval::get),153 pending_interval: config153 pending_interval: config154 .pending_interval154 .pending_interval155 .unwrap_or_else(|| T::PendingInterval::get()),155 .unwrap_or_else(T::PendingInterval::get),156 interval_income: config156 interval_income: config157 .interval_income157 .interval_income158 .unwrap_or_else(|| T::IntervalIncome::get()),158 .unwrap_or_else(T::IntervalIncome::get),159 max_stakers_per_calculation: config159 max_stakers_per_calculation: config160 .max_stakers_per_calculation160 .max_stakers_per_calculation161 .unwrap_or_else(|| MAX_NUMBER_PAYOUTS),161 .unwrap_or(MAX_NUMBER_PAYOUTS),162 }162 }163 }163 }164}164}pallets/balances-adapter/src/lib.rsdiffbeforeafterboth31 }31 }32}32}3334impl<T: Config> Default for NativeFungibleHandle<T> {35 fn default() -> Self {36 Self::new()37 }38}333934impl<T: Config> WithRecorder<T> for NativeFungibleHandle<T> {40impl<T: Config> WithRecorder<T> for NativeFungibleHandle<T> {35 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {41 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {pallets/common/src/eth.rsdiffbeforeafterboth136136137 fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {137 fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {138 let key = evm_coder::types::String::from_utf8(from.key.into())138 let key = evm_coder::types::String::from_utf8(from.key.into())139 .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {}", e)))?;139 .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {e}")))?;140 let value = evm_coder::types::Bytes(from.value.to_vec());140 let value = evm_coder::types::Bytes(from.value.to_vec());141 Ok(Property { key, value })141 Ok(Property { key, value })142 }142 }201 pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {201 pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {202 Self {202 Self {203 field,203 field,204 value: match value {204 value: value.map(|value| value.into()),205 Some(value) => Some(value.into()),206 None => None,207 },208 }205 }209 }206 }210 /// Whether the field contains a value.207 /// Whether the field contains a value.222 .ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;219 .ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;223 let value = Some(value.try_into().map_err(|error| {220 let value = Some(value.try_into().map_err(|error| {224 Self::Error::Revert(format!(221 Self::Error::Revert(format!(225 "can't convert value to u32 \"{}\" because: \"{error}\"",222 "can't convert value to u32 \"{value}\" because: \"{error}\""226 value227 ))223 ))228 })?);224 })?);229225249 limits.sponsored_data_size = value;245 limits.sponsored_data_size = value;250 }246 }251 CollectionLimitField::SponsoredDataRateLimit => {247 CollectionLimitField::SponsoredDataRateLimit => {252 limits.sponsored_data_rate_limit = match value {248 limits.sponsored_data_rate_limit =253 Some(value) => Some(up_data_structs::SponsoringRateLimit::Blocks(value)),249 value.map(up_data_structs::SponsoringRateLimit::Blocks);254 None => None,255 };256 }250 }257 CollectionLimitField::TokenLimit => {251 CollectionLimitField::TokenLimit => {258 limits.token_limit = value;252 limits.token_limit = value;454 }448 }455}449}456450457impl Into<up_data_structs::AccessMode> for AccessMode {451impl From<AccessMode> for up_data_structs::AccessMode {458 fn into(self) -> up_data_structs::AccessMode {452 fn from(value: AccessMode) -> Self {459 match self {453 match value {460 AccessMode::Normal => up_data_structs::AccessMode::Normal,454 AccessMode::Normal => up_data_structs::AccessMode::Normal,461 AccessMode::AllowList => up_data_structs::AccessMode::AllowList,455 AccessMode::AllowList => up_data_structs::AccessMode::AllowList,462 }456 }pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth260 message: Some(msg), ..260 message: Some(msg), ..261 }) => ExError::Revert(msg.into()),261 }) => ExError::Revert(msg.into()),262 DispatchError::Module(ModuleError { index, error, .. }) => {262 DispatchError::Module(ModuleError { index, error, .. }) => {263 ExError::Revert(format!("error {:?} in pallet {}", error, index))263 ExError::Revert(format!("error {error:?} in pallet {index}"))264 }264 }265 e => ExError::Revert(format!("substrate error: {:?}", e)),265 e => ExError::Revert(format!("substrate error: {e:?}")),266 }266 }267}267}268268pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth184 /// @param contractAddress The contract for which a sponsor is requested.184 /// @param contractAddress The contract for which a sponsor is requested.185 /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.185 /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.186 fn sponsor(&self, contract_address: Address) -> Result<Option<eth::CrossAddress>> {186 fn sponsor(&self, contract_address: Address) -> Result<Option<eth::CrossAddress>> {187 Ok(match Pallet::<T>::get_sponsor(contract_address) {187 Ok(Pallet::<T>::get_sponsor(contract_address)188 Some(ref value) => Some(eth::CrossAddress::from_sub_cross_account::<T>(value)),188 .as_ref()189 None => None,190 })189 .map(eth::CrossAddress::from_sub_cross_account::<T>))191 }190 }192191193 /// Check tat contract has confirmed sponsor.192 /// Check tat contract has confirmed sponsor.275 self.recorder().consume_sstore()?;274 self.recorder().consume_sstore()?;276275277 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;276 <Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;278 <Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())277 <Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit)279 .map_err(dispatch_to_evm::<T>)?;278 .map_err(dispatch_to_evm::<T>)?;280 Ok(())279 Ok(())281 }280 }pallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth376 <SponsoringMode<T>>::get(contract)376 <SponsoringMode<T>>::get(contract)377 .or_else(|| {377 .or_else(|| {378 #[allow(deprecated)]378 #[allow(deprecated)]379 <SelfSponsoring<T>>::get(contract).then(|| SponsoringModeT::Allowlisted)379 <SelfSponsoring<T>>::get(contract).then_some(SponsoringModeT::Allowlisted)380 })380 })381 .unwrap_or_default()381 .unwrap_or_default()382 }382 }410410411 /// Is user added to allowlist, or he is owner of specified contract411 /// Is user added to allowlist, or he is owner of specified contract412 pub fn allowed(contract: H160, user: H160) -> bool {412 pub fn allowed(contract: H160, user: H160) -> bool {413 <Allowlist<T>>::get(&contract, &user) || <Owner<T>>::get(&contract) == user413 <Allowlist<T>>::get(contract, user) || <Owner<T>>::get(contract) == user414 }414 }415415416 /// Toggle contract allowlist access416 /// Toggle contract allowlist access425425426 /// Throw error if user is not allowed to reconfigure target contract426 /// Throw error if user is not allowed to reconfigure target contract427 pub fn ensure_owner(contract: H160, user: H160) -> DispatchResult {427 pub fn ensure_owner(contract: H160, user: H160) -> DispatchResult {428 ensure!(<Owner<T>>::get(&contract) == user, Error::<T>::NoPermission);428 ensure!(<Owner<T>>::get(contract) == user, Error::<T>::NoPermission);429 Ok(())429 Ok(())430 }430 }431 }431 }pallets/evm-migration/src/lib.rsdiffbeforeafterboth78 pub fn begin(origin: OriginFor<T>, address: H160) -> DispatchResult {78 pub fn begin(origin: OriginFor<T>, address: H160) -> DispatchResult {79 ensure_root(origin)?;79 ensure_root(origin)?;80 ensure!(80 ensure!(81 <PalletEvm<T>>::is_account_empty(&address) && !<MigrationPending<T>>::get(&address),81 <PalletEvm<T>>::is_account_empty(&address) && !<MigrationPending<T>>::get(address),82 <Error<T>>::AccountNotEmpty,82 <Error<T>>::AccountNotEmpty,83 );83 );848497 ) -> DispatchResult {97 ) -> DispatchResult {98 ensure_root(origin)?;98 ensure_root(origin)?;99 ensure!(99 ensure!(100 <MigrationPending<T>>::get(&address),100 <MigrationPending<T>>::get(address),101 <Error<T>>::AccountIsNotMigrating,101 <Error<T>>::AccountIsNotMigrating,102 );102 );103103104 for (k, v) in data {104 for (k, v) in data {105 <pallet_evm::AccountStorages<T>>::insert(&address, k, v);105 <pallet_evm::AccountStorages<T>>::insert(address, k, v);106 }106 }107 Ok(())107 Ok(())108 }108 }115 pub fn finish(origin: OriginFor<T>, address: H160, code: Vec<u8>) -> DispatchResult {115 pub fn finish(origin: OriginFor<T>, address: H160, code: Vec<u8>) -> DispatchResult {116 ensure_root(origin)?;116 ensure_root(origin)?;117 ensure!(117 ensure!(118 <MigrationPending<T>>::get(&address),118 <MigrationPending<T>>::get(address),119 <Error<T>>::AccountIsNotMigrating,119 <Error<T>>::AccountIsNotMigrating,120 );120 );121121122 <pallet_evm::AccountCodes<T>>::insert(&address, code);122 <pallet_evm::AccountCodes<T>>::insert(address, code);123 <MigrationPending<T>>::remove(address);123 <MigrationPending<T>>::remove(address);124 Ok(())124 Ok(())125 }125 }166 pub struct OnMethodCall<T>(PhantomData<T>);166 pub struct OnMethodCall<T>(PhantomData<T>);167 impl<T: Config> pallet_evm::OnMethodCall<T> for OnMethodCall<T> {167 impl<T: Config> pallet_evm::OnMethodCall<T> for OnMethodCall<T> {168 fn is_reserved(contract: &H160) -> bool {168 fn is_reserved(contract: &H160) -> bool {169 <MigrationPending<T>>::get(&contract)169 <MigrationPending<T>>::get(contract)170 }170 }171171172 fn is_used(_contract: &H160) -> bool {172 fn is_used(_contract: &H160) -> bool {pallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth333 &Value::new(0),333 &Value::new(0),334 )?;334 )?;335335336 Ok(amount.into())336 Ok(amount)337 }337 }338 }338 }339 }339 }pallets/foreign-assets/src/lib.rsdiffbeforeafterboth161161162 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {162 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {163 log::trace!(target: "fassets::get_currency_id", "call");163 log::trace!(target: "fassets::get_currency_id", "call");164 Pallet::<T>::location_to_currency_ids(multi_location).map(|id| AssetIds::ForeignAssetId(id))164 Pallet::<T>::location_to_currency_ids(multi_location).map(AssetIds::ForeignAssetId)165 }165 }166}166}167167378 foreign_asset_id,378 foreign_asset_id,379 |maybe_location| -> DispatchResult {379 |maybe_location| -> DispatchResult {380 ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);380 ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);381 *maybe_location = Some(location.clone());381 *maybe_location = Some(*location);382382383 AssetMetadatas::<T>::try_mutate(383 AssetMetadatas::<T>::try_mutate(384 AssetIds::ForeignAssetId(foreign_asset_id),384 AssetIds::ForeignAssetId(foreign_asset_id),422422423 // modify location423 // modify location424 if location != old_multi_locations {424 if location != old_multi_locations {425 LocationToCurrencyIds::<T>::remove(old_multi_locations.clone());425 LocationToCurrencyIds::<T>::remove(*old_multi_locations);426 LocationToCurrencyIds::<T>::try_mutate(426 LocationToCurrencyIds::<T>::try_mutate(427 location,427 location,428 |maybe_currency_ids| -> DispatchResult {428 |maybe_currency_ids| -> DispatchResult {437 )?;437 )?;438 }438 }439 *maybe_asset_metadatas = Some(metadata.clone());439 *maybe_asset_metadatas = Some(metadata.clone());440 *old_multi_locations = location.clone();440 *old_multi_locations = *location;441 Ok(())441 Ok(())442 },442 },443 )443 )pallets/identity/src/types.rsdiffbeforeafterboth104 Data::Raw(ref x) => {104 Data::Raw(ref x) => {105 let l = x.len().min(32);105 let l = x.len().min(32);106 let mut r = vec![l as u8 + 1; l + 1];106 let mut r = vec![l as u8 + 1; l + 1];107 r[1..].copy_from_slice(&x[..l as usize]);107 r[1..].copy_from_slice(&x[..l]);108 r108 r109 }109 }110 Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),110 Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),287 fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {287 fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {288 let field = u64::decode(input)?;288 let field = u64::decode(input)?;289 Ok(Self(289 Ok(Self(290 <BitFlags<IdentityField>>::from_bits(field as u64).map_err(|_| "invalid value")?,290 <BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,291 ))291 ))292 }292 }293}293}pallets/nonfungible/src/erc.rsdiffbeforeafterboth212122extern crate alloc;22extern crate alloc;2324use alloc::string::ToString;23use core::{25use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},26 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,27 convert::TryInto,356 .transpose()358 .transpose()357 .map_err(|e| {359 .map_err(|e| {358 Error::Revert(alloc::format!(360 Error::Revert(alloc::format!(359 "Can not convert value \"baseURI\" to string with error \"{}\"",361 "Can not convert value \"baseURI\" to string with error \"{e}\""360 e361 ))362 ))362 })?;363 })?;363364675 .try_into()676 .try_into()676 .map_err(|_| "token uri is too long")?,677 .map_err(|_| "token uri is too long")?,677 })678 })678 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;679 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;679680680 <Pallet<T>>::create_item(681 <Pallet<T>>::create_item(681 self,682 self,717 .map(Clone::clone)718 .map(Clone::clone)718 .ok_or_else(|| {719 .ok_or_else(|| {719 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();720 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();720 Error::Revert(alloc::format!("No permission for key {}", key))721 Error::Revert(alloc::format!("No permission for key {key}"))721 })?;722 })?;722 Ok(a)723 Ok(a)723}724}752 /// @param tokenId Id for the token.753 /// @param tokenId Id for the token.753 #[solidity(hide)]754 #[solidity(hide)]754 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {755 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {755 Self::owner_of_cross(&self, token_id)756 Self::owner_of_cross(self, token_id)756 }757 }757758758 /// Returns the owner (in cross format) of the token.759 /// Returns the owner (in cross format) of the token.759 ///760 ///760 /// @param tokenId Id for the token.761 /// @param tokenId Id for the token.761 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {762 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {762 Self::token_owner(&self, token_id.try_into()?)763 Self::token_owner(self, token_id.try_into()?)763 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))764 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))764 .map_err(|_| Error::Revert("token not found".into()))765 .map_err(|_| Error::Revert("token not found".into()))765 }766 }789 .collect::<Result<Vec<_>>>()?;790 .collect::<Result<Vec<_>>>()?;790791791 <Self as CommonCollectionOperations<T>>::token_properties(792 <Self as CommonCollectionOperations<T>>::token_properties(792 &self,793 self,793 token_id.try_into()?,794 token_id.try_into()?,794 if keys.is_empty() { None } else { Some(keys) },795 if keys.is_empty() { None } else { Some(keys) },795 )796 )1021 .try_into()1022 .try_into()1022 .map_err(|_| "token uri is too long")?,1023 .map_err(|_| "token uri is too long")?,1023 })1024 })1024 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;1025 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;102510261026 data.push(CreateItemData::<T> {1027 data.push(CreateItemData::<T> {1027 properties,1028 properties,1056 .map(eth::Property::try_into)1057 .map(eth::Property::try_into)1057 .collect::<Result<Vec<_>>>()?1058 .collect::<Result<Vec<_>>>()?1058 .try_into()1059 .try_into()1059 .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;1060 .map_err(|_| Error::Revert("too many properties".to_string()))?;106010611061 let caller = T::CrossAccountId::from_eth(caller);1062 let caller = T::CrossAccountId::from_eth(caller);10621063pallets/nonfungible/src/lib.rsdiffbeforeafterboth863 <TokenData<T>>::insert(860 <TokenData<T>>::insert((collection.id, token), ItemData { owner: to.clone() });864 (collection.id, token),865 ItemData {866 owner: to.clone(),867 ..token_data868 },869 );870861871 if let Some(balance_to) = balance_to {862 if let Some(balance_to) = balance_to {pallets/refungible/src/erc.rsdiffbeforeafterboth212122extern crate alloc;22extern crate alloc;232324use alloc::string::ToString;24use core::{25use core::{25 char::{REPLACEMENT_CHARACTER, decode_utf16},26 char::{REPLACEMENT_CHARACTER, decode_utf16},26 convert::TryInto,27 convert::TryInto,353 .transpose()354 .transpose()354 .map_err(|e| {355 .map_err(|e| {355 Error::Revert(alloc::format!(356 Error::Revert(alloc::format!(356 "Can not convert value \"baseURI\" to string with error \"{}\"",357 "Can not convert value \"baseURI\" to string with error \"{e}\""357 e358 ))358 ))359 })?;359 })?;360360482 .recorder482 .recorder483 .weight_calls_budget(<StructureWeight<T>>::find_parent());483 .weight_calls_budget(<StructureWeight<T>>::find_parent());484484485 let balance = balance(&self, token, &from)?;485 let balance = balance(self, token, &from)?;486 ensure_single_owner(&self, token, balance)?;486 ensure_single_owner(self, token, balance)?;487487488 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)488 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)489 .map_err(dispatch_to_evm::<T>)?;489 .map_err(dispatch_to_evm::<T>)?;575 let caller = T::CrossAccountId::from_eth(caller);575 let caller = T::CrossAccountId::from_eth(caller);576 let token = token_id.try_into()?;576 let token = token_id.try_into()?;577577578 let balance = balance(&self, token, &caller)?;578 let balance = balance(self, token, &caller)?;579 ensure_single_owner(&self, token, balance)?;579 ensure_single_owner(self, token, balance)?;580580581 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;581 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;582 Ok(())582 Ok(())622 return Err("item id should be next".into());622 return Err("item id should be next".into());623 }623 }624624625 let users = [(to.clone(), 1)]625 let users = [(to, 1)]626 .into_iter()626 .into_iter()627 .collect::<BTreeMap<_, _>>()627 .collect::<BTreeMap<_, _>>()628 .try_into()628 .try_into()706 .try_into()706 .try_into()707 .map_err(|_| "token uri is too long")?,707 .map_err(|_| "token uri is too long")?,708 })708 })709 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;709 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;710710711 let users = [(to.clone(), 1)]711 let users = [(to, 1)]712 .into_iter()712 .into_iter()713 .collect::<BTreeMap<_, _>>()713 .collect::<BTreeMap<_, _>>()714 .try_into()714 .try_into()750 .map(Clone::clone)750 .map(Clone::clone)751 .ok_or_else(|| {751 .ok_or_else(|| {752 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();752 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();753 Error::Revert(alloc::format!("No permission for key {}", key))753 Error::Revert(alloc::format!("No permission for key {key}"))754 })?;754 })?;755 Ok(a)755 Ok(a)756}756}785 /// @param tokenId Id for the token.785 /// @param tokenId Id for the token.786 #[solidity(hide)]786 #[solidity(hide)]787 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {787 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {788 Self::owner_of_cross(&self, token_id)788 Self::owner_of_cross(self, token_id)789 }789 }790790791 /// Returns the owner (in cross format) of the token.791 /// Returns the owner (in cross format) of the token.792 ///792 ///793 /// @param tokenId Id for the token.793 /// @param tokenId Id for the token.794 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {794 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {795 Self::token_owner(&self, token_id.try_into()?)795 Self::token_owner(self, token_id.try_into()?)796 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))796 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))797 .or_else(|err| match err {797 .or_else(|err| match err {798 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),798 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),827 .collect::<Result<Vec<_>>>()?;827 .collect::<Result<Vec<_>>>()?;828828829 <Self as CommonCollectionOperations<T>>::token_properties(829 <Self as CommonCollectionOperations<T>>::token_properties(830 &self,830 self,831 token_id.try_into()?,831 token_id.try_into()?,832 if keys.is_empty() { None } else { Some(keys) },832 if keys.is_empty() { None } else { Some(keys) },833 )833 )1004 }1004 }1005 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1005 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1006 }1006 }1007 let users = [(to.clone(), 1)]1007 let users = [(to, 1)]1008 .into_iter()1008 .into_iter()1009 .collect::<BTreeMap<_, _>>()1009 .collect::<BTreeMap<_, _>>()1010 .try_into()1010 .try_into()1046 .weight_calls_budget(<StructureWeight<T>>::find_parent());1046 .weight_calls_budget(<StructureWeight<T>>::find_parent());104710471048 let mut data = Vec::with_capacity(tokens.len());1048 let mut data = Vec::with_capacity(tokens.len());1049 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]1049 let users: BoundedBTreeMap<_, _, _> = [(to, 1)]1050 .into_iter()1050 .into_iter()1051 .collect::<BTreeMap<_, _>>()1051 .collect::<BTreeMap<_, _>>()1052 .try_into()1052 .try_into()1067 .try_into()1067 .try_into()1068 .map_err(|_| "token uri is too long")?,1068 .map_err(|_| "token uri is too long")?,1069 })1069 })1070 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;1070 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;107110711072 let create_item_data = CreateItemData::<T> {1072 let create_item_data = CreateItemData::<T> {1073 users: users.clone(),1073 users: users.clone(),1103 .map(eth::Property::try_into)1103 .map(eth::Property::try_into)1104 .collect::<Result<Vec<_>>>()?1104 .collect::<Result<Vec<_>>>()?1105 .try_into()1105 .try_into()1106 .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;1106 .map_err(|_| Error::Revert("too many properties".to_string()))?;110711071108 let caller = T::CrossAccountId::from_eth(caller);1108 let caller = T::CrossAccountId::from_eth(caller);11091109pallets/refungible/src/lib.rsdiffbeforeafterboth112411241125 if collection.ignores_token_restrictions(spender) {1125 if collection.ignores_token_restrictions(spender) {1126 return Ok(Self::compute_allowance_decrease(1126 return Ok(Self::compute_allowance_decrease(1127 collection, token, from, &spender, amount,1127 collection, token, from, spender, amount,1128 ));1128 ));1129 }1129 }113011301143 return Ok(None);1143 return Ok(None);1144 }1144 }114511451146 let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);1146 let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);1147 if allowance.is_some() {1147 if allowance.is_some() {1148 return Ok(allowance);1148 return Ok(allowance);1149 }1149 }pallets/scheduler-v2/src/lib.rsdiffbeforeafterboth969 call: ScheduledCall<T>,969 call: ScheduledCall<T>,970 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {970 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {971 // ensure id it is unique971 // ensure id it is unique972 if Lookup::<T>::contains_key(&id) {972 if Lookup::<T>::contains_key(id) {973 return Err(Error::<T>::FailedToSchedule.into());973 return Err(Error::<T>::FailedToSchedule.into());974 }974 }975975pallets/structure/src/lib.rsdiffbeforeafterboth280 ) -> DispatchResultWithPostInfo {280 ) -> DispatchResultWithPostInfo {281 let dispatch = T::CollectionDispatch::dispatch(collection)?;281 let dispatch = T::CollectionDispatch::dispatch(collection)?;282 let dispatch = dispatch.as_dyn();282 let dispatch = dispatch.as_dyn();283 dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)283 dispatch.burn_item_recursively(from, token, self_budget, breadth_budget)284 }284 }285285286 /// Check if `token` indirectly owned by `user`286 /// Check if `token` indirectly owned by `user`396 account: &T::CrossAccountId,396 account: &T::CrossAccountId,397 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,397 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,398 ) -> DispatchResult {398 ) -> DispatchResult {399 if is_collection(&account.as_eth()) {399 if is_collection(account.as_eth()) {400 fail!(<Error<T>>::CantNestTokenUnderCollection);400 fail!(<Error<T>>::CantNestTokenUnderCollection);401 }401 }402 let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account) else {402 let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account) else {pallets/unique/src/eth/mod.rsdiffbeforeafterboth114 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());114 T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());115115116 let collection_id = T::CollectionDispatch::create(116 let collection_id =117 caller.clone(),117 T::CollectionDispatch::create(caller, collection_helpers_address, data, Default::default())118 collection_helpers_address,119 data,120 Default::default(),121 )122 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;118 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;123 let address = pallet_common::eth::collection_id_to_address(collection_id);119 let address = pallet_common::eth::collection_id_to_address(collection_id);132 .expect("Collection creation price should be convertible to u128");128 .expect("Collection creation price should be convertible to u128");133 if value != creation_price {129 if value != creation_price {134 return Err(format!(130 return Err(format!(135 "Sent amount not equals to collection creation price ({0})",131 "Sent amount not equals to collection creation price ({creation_price})",136 creation_price137 )132 )138 .into());133 .into());139 }134 }383 map_eth_to_id(&collection_address)378 map_eth_to_id(&collection_address)384 .map(|id| id.0)379 .map(|id| id.0)385 .ok_or(Error::Revert(format!(380 .ok_or(Error::Revert(format!(386 "failed to convert address {} into collectionId.",381 "failed to convert address {collection_address} into collectionId."387 collection_address388 )))382 )))389 }383 }390}384}422generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);416generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);423417424fn error_field_too_long(feild: &str, bound: usize) -> Error {418fn error_field_too_long(feild: &str, bound: usize) -> Error {425 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))419 Error::Revert(format!("{feild} is too long. Max length is {bound}."))426}420}427421pallets/unique/src/lib.rsdiffbeforeafterboth507 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);507 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);508 let new_owner = T::CrossAccountId::from_sub(new_owner);508 let new_owner = T::CrossAccountId::from_sub(new_owner);509 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;509 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;510 target_collection.change_owner(sender, new_owner.clone())510 target_collection.change_owner(sender, new_owner)511 }511 }512512513 /// Add an admin to a collection.513 /// Add an admin to a collection.667 /// * `owner`: Address of the initial owner of the item.667 /// * `owner`: Address of the initial owner of the item.668 /// * `data`: Token data describing the item to store on chain.668 /// * `data`: Token data describing the item to store on chain.669 #[pallet::call_index(11)]669 #[pallet::call_index(11)]670 #[pallet::weight(T::CommonWeightInfo::create_item(&data))]670 #[pallet::weight(T::CommonWeightInfo::create_item(data))]671 pub fn create_item(671 pub fn create_item(672 origin: OriginFor<T>,672 origin: OriginFor<T>,673 collection_id: CollectionId,673 collection_id: CollectionId,701 /// * `owner`: Address of the initial owner of the tokens.701 /// * `owner`: Address of the initial owner of the tokens.702 /// * `items_data`: Vector of data describing each item to be created.702 /// * `items_data`: Vector of data describing each item to be created.703 #[pallet::call_index(12)]703 #[pallet::call_index(12)]704 #[pallet::weight(T::CommonWeightInfo::create_multiple_items(&items_data))]704 #[pallet::weight(T::CommonWeightInfo::create_multiple_items(items_data))]705 pub fn create_multiple_items(705 pub fn create_multiple_items(706 origin: OriginFor<T>,706 origin: OriginFor<T>,707 collection_id: CollectionId,707 collection_id: CollectionId,889 /// * `collection_id`: ID of the collection to which the tokens would belong.889 /// * `collection_id`: ID of the collection to which the tokens would belong.890 /// * `data`: Explicit item creation data.890 /// * `data`: Explicit item creation data.891 #[pallet::call_index(18)]891 #[pallet::call_index(18)]892 #[pallet::weight(T::CommonWeightInfo::create_multiple_items_ex(&data))]892 #[pallet::weight(T::CommonWeightInfo::create_multiple_items_ex(data))]893 pub fn create_multiple_items_ex(893 pub fn create_multiple_items_ex(894 origin: OriginFor<T>,894 origin: OriginFor<T>,895 collection_id: CollectionId,895 collection_id: CollectionId,1313 collection_id: CollectionId,1313 collection_id: CollectionId,1314 ) -> DispatchResult {1314 ) -> DispatchResult {1315 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;1315 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;1316 target_collection.force_set_sponsor(sponsor.clone())1316 target_collection.force_set_sponsor(sponsor)1317 }1317 }131813181319 /// Force remove `sponsor` for `collection`.1319 /// Force remove `sponsor` for `collection`.primitives/data-structs/src/bounded.rsdiffbeforeafterboth63 V: fmt::Debug,63 V: fmt::Debug,64{64{65 use core::fmt::Debug;65 use core::fmt::Debug;66 (&v as &Vec<V>).fmt(f)66 (v as &Vec<V>).fmt(f)67}67}686869#[cfg(feature = "serde1")]69#[cfg(feature = "serde1")]114 V: fmt::Debug,114 V: fmt::Debug,115{115{116 use core::fmt::Debug;116 use core::fmt::Debug;117 (&v as &BTreeMap<K, V>).fmt(f)117 (v as &BTreeMap<K, V>).fmt(f)118}118}119119120#[cfg(feature = "serde1")]120#[cfg(feature = "serde1")]157 K: fmt::Debug + Ord,157 K: fmt::Debug + Ord,158{158{159 use core::fmt::Debug;159 use core::fmt::Debug;160 (&v as &BTreeSet<K>).fmt(f)160 (v as &BTreeSet<K>).fmt(f)161}161}162162primitives/data-structs/src/lib.rsdiffbeforeafterboth536 type Target = Vec<u8>;536 type Target = Vec<u8>;537537538 fn deref(&self) -> &Self::Target {538 fn deref(&self) -> &Self::Target {539 return &self.0;539 &self.0540 }540 }541}541}542542816 Self(Default::default())816 Self(Default::default())817 }817 }818}818}819impl Default for OwnerRestrictedSet {820 fn default() -> Self {821 Self::new()822 }823}819impl core::ops::Deref for OwnerRestrictedSet {824impl core::ops::Deref for OwnerRestrictedSet {820 type Target = OwnerRestrictedSetInner;825 type Target = OwnerRestrictedSetInner;821 fn deref(&self) -> &Self::Target {826 fn deref(&self) -> &Self::Target {1098 pub value: PropertyValue,1103 pub value: PropertyValue,1099}1104}110011051101impl Into<(PropertyKey, PropertyValue)> for Property {1106impl From<Property> for (PropertyKey, PropertyValue) {1102 fn into(self) -> (PropertyKey, PropertyValue) {1107 fn from(value: Property) -> Self {1103 (self.key, self.value)1108 (value.key, value.value)1104 }1109 }1105}1110}110611111116 pub permission: PropertyPermission,1121 pub permission: PropertyPermission,1117}1122}111811231119impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {1124impl From<PropertyKeyPermission> for (PropertyKey, PropertyPermission) {1120 fn into(self) -> (PropertyKey, PropertyPermission) {1125 fn from(value: PropertyKeyPermission) -> Self {1121 (self.key, self.permission)1126 (value.key, value.permission)1122 }1127 }1123}1128}112411291415 value: Self::Value,1420 value: Self::Value,1416 ) -> Result<Option<Self::Value>, PropertiesError> {1421 ) -> Result<Option<Self::Value>, PropertiesError> {1417 let key_size = scoped_slice_size(scope, &key);1422 let key_size = scoped_slice_size(scope, &key);1418 let value_size = slice_size(&value) as u32;1423 let value_size = slice_size(&value);141914241420 if self.consumed_space + value_size + key_size > S && !cfg!(feature = "runtime-benchmarks")1425 if self.consumed_space + value_size + key_size > S && !cfg!(feature = "runtime-benchmarks")1421 {1426 {1425 let old_value = self.map.try_scoped_set(scope, key, value)?;1430 let old_value = self.map.try_scoped_set(scope, key, value)?;142614311427 if let Some(old_value) = old_value.as_ref() {1432 if let Some(old_value) = old_value.as_ref() {1428 let old_value_size = slice_size(&old_value);1433 let old_value_size = slice_size(old_value);1429 self.consumed_space = self.consumed_space.saturating_sub(old_value_size) + value_size;1434 self.consumed_space = self.consumed_space.saturating_sub(old_value_size) + value_size;1430 } else {1435 } else {1431 self.consumed_space += key_size + value_size;1436 self.consumed_space += key_size + value_size;runtime/common/config/xcm/foreignassets.rsdiffbeforeafterboth65 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));65 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));66 }66 }676768 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {68 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {69 Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {69 Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {70 ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))70 ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))71 }71 }207 }207 }208208209 if let Some(currency_id) =209 if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {210 XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location.clone())211 {212 return Some(currency_id);210 return Some(currency_id);213 }211 }runtime/common/ethereum/precompiles/mod.rsdiffbeforeafterboth38 }38 }39}39}4041impl<R> Default for UniquePrecompiles<R>42where43 R: pallet_evm::Config,44{45 fn default() -> Self {46 Self::new()47 }48}4940impl<R> PrecompileSet for UniquePrecompiles<R>50impl<R> PrecompileSet for UniquePrecompiles<R>41where51whereruntime/common/ethereum/precompiles/sr25519.rsdiffbeforeafterboth646465 // Parse arguments65 // Parse arguments66 let public: sr25519::Public =66 let public: sr25519::Public =67 sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?).into();67 sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?);68 let signature_bytes: Vec<u8> = input.read::<Bytes>(gasometer)?.into();68 let signature_bytes: Vec<u8> = input.read::<Bytes>(gasometer)?.into();69 let message: Vec<u8> = input.read::<Bytes>(gasometer)?.into();69 let message: Vec<u8> = input.read::<Bytes>(gasometer)?.into();7070runtime/common/ethereum/precompiles/utils/data.rsdiffbeforeafterboth60}60}616162impl Into<Vec<u8>> for Bytes {62impl Into<Vec<u8>> for Bytes {63 fn into(self: Self) -> Vec<u8> {63 fn into(self) -> Vec<u8> {64 self.064 self.065 }65 }66}66}runtime/common/ethereum/precompiles/utils/mod.rsdiffbeforeafterboth73 }73 }74 }74 }757576 #[must_use]77 /// Check that a function call is compatible with the context it is76 /// Check that a function call is compatible with the context it is78 /// called into.77 /// called into.79 pub fn check_function_modifier(78 pub fn check_function_modifier(runtime/common/ethereum/sponsoring.rsdiffbeforeafterboth78 let token_id: TokenId = token_id.try_into().ok()?;78 let token_id: TokenId = token_id.try_into().ok()?;79 withdraw_set_token_property::<T>(79 withdraw_set_token_property::<T>(80 &collection,80 &collection,81 &who,81 who,82 &token_id,82 &token_id,83 key.len() + value.len(),83 key.len() + value.len(),84 )84 )88 ERC721UniqueExtensionsCall::Transfer { token_id, .. },88 ERC721UniqueExtensionsCall::Transfer { token_id, .. },89 ) => {89 ) => {90 let token_id: TokenId = token_id.try_into().ok()?;90 let token_id: TokenId = token_id.try_into().ok()?;91 withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)91 withdraw_transfer::<T>(&collection, who, &token_id).map(|()| sponsor)92 }92 }93 UniqueNFTCall::ERC721UniqueMintable(93 UniqueNFTCall::ERC721UniqueMintable(94 ERC721UniqueMintableCall::Mint { .. }94 ERC721UniqueMintableCall::Mint { .. }97 | ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },97 | ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },98 ) => withdraw_create_item::<T>(98 ) => withdraw_create_item::<T>(99 &collection,99 &collection,100 &who,100 who,101 &CreateItemData::NFT(CreateNftData::default()),101 &CreateItemData::NFT(CreateNftData::default()),102 )102 )103 .map(|()| sponsor),103 .map(|()| sponsor),runtime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth161617//! Implements EVM sponsoring logic via TransactionValidityHack17//! Implements EVM sponsoring logic via TransactionValidityHack181819use core::convert::TryInto;20use pallet_common::CollectionHandle;19use pallet_common::CollectionHandle;21use pallet_evm::account::CrossAccountId;20use pallet_evm::account::CrossAccountId;22use pallet_fungible::Config as FungibleConfig;21use pallet_fungible::Config as FungibleConfig;95 ..94 ..96 } => {95 } => {97 let token_id = TokenId::try_from(token_id).ok()?;96 let token_id = TokenId::try_from(token_id).ok()?;98 withdraw_set_token_property::<T>(&collection, &who, &token_id, key.len() + value.len())97 withdraw_set_token_property::<T>(&collection, who, &token_id, key.len() + value.len())99 }98 }100 }99 }101}100}242241243 MintCross { .. } => withdraw_create_item::<T>(242 MintCross { .. } => withdraw_create_item::<T>(244 &collection,243 &collection,245 &who,244 who,246 &CreateItemData::NFT(CreateNftData::default()),245 &CreateItemData::NFT(CreateNftData::default()),247 ),246 ),248247249 TransferCross { token_id, .. }248 TransferCross { token_id, .. }250 | TransferFromCross { token_id, .. }249 | TransferFromCross { token_id, .. }251 | Transfer { token_id, .. } => {250 | Transfer { token_id, .. } => {252 let token_id = TokenId::try_from(token_id).ok()?;251 let token_id = TokenId::try_from(token_id).ok()?;253 withdraw_transfer::<T>(&collection, &who, &token_id)252 withdraw_transfer::<T>(&collection, who, &token_id)254 }253 }255 }254 }256 }255 }275 | MintWithTokenUri { .. }274 | MintWithTokenUri { .. }276 | MintWithTokenUriCheckId { .. } => withdraw_create_item::<T>(275 | MintWithTokenUriCheckId { .. } => withdraw_create_item::<T>(277 &collection,276 &collection,278 &who,277 who,279 &CreateItemData::NFT(CreateNftData::default()),278 &CreateItemData::NFT(CreateNftData::default()),280 ),279 ),281 }280 }311310312 Transfer { .. } => {311 Transfer { .. } => {313 let RefungibleTokenHandle(handle, token_id) = token;312 let RefungibleTokenHandle(handle, token_id) = token;314 let token_id = token_id.try_into().ok()?;315 withdraw_transfer::<T>(&handle, &who, &token_id)313 withdraw_transfer::<T>(&handle, who, &token_id)316 }314 }317 TransferFrom { from, .. } => {315 TransferFrom { from, .. } => {318 let RefungibleTokenHandle(handle, token_id) = token;316 let RefungibleTokenHandle(handle, token_id) = token;319 let token_id = token_id.try_into().ok()?;320 let from = T::CrossAccountId::from_eth(from);317 let from = T::CrossAccountId::from_eth(from);321 withdraw_transfer::<T>(&handle, &from, &token_id)318 withdraw_transfer::<T>(&handle, &from, &token_id)322 }319 }323 Approve { .. } => {320 Approve { .. } => {324 let RefungibleTokenHandle(handle, token_id) = token;321 let RefungibleTokenHandle(handle, token_id) = token;325 let token_id = token_id.try_into().ok()?;326 withdraw_approve::<T>(&handle, who.as_sub(), &token_id)322 withdraw_approve::<T>(&handle, who.as_sub(), &token_id)327 }323 }328 }324 }351347352 TransferCross { .. } | TransferFromCross { .. } => {348 TransferCross { .. } | TransferFromCross { .. } => {353 let RefungibleTokenHandle(handle, token_id) = token;349 let RefungibleTokenHandle(handle, token_id) = token;354 let token_id = token_id.try_into().ok()?;355 withdraw_transfer::<T>(&handle, &who, &token_id)350 withdraw_transfer::<T>(&handle, who, &token_id)356 }351 }357352358 ApproveCross { .. } => {353 ApproveCross { .. } => {359 let RefungibleTokenHandle(handle, token_id) = token;354 let RefungibleTokenHandle(handle, token_id) = token;360 let token_id = token_id.try_into().ok()?;361 withdraw_approve::<T>(&handle, who.as_sub(), &token_id)355 withdraw_approve::<T>(&handle, who.as_sub(), &token_id)362 }356 }363 }357 }runtime/common/mod.rsdiffbeforeafterboth204 &[],204 &[],205 );205 );206206207 let should_upgrade = match version {207 let should_upgrade = version.is_none();208 None => true,209 Some(_) => false,210 };211208212 if should_upgrade {209 if should_upgrade {213 log::info!(210 log::info!(220 .cloned()217 .cloned()221 .filter_map(|authority_id| {218 .filter_map(|authority_id| {222 weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));219 weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));223 let vec = authority_id.clone().to_raw_vec();220 let vec = authority_id.to_raw_vec();224 let slice = vec.as_slice();221 let slice = vec.as_slice();225 let array: Option<[u8; 32]> = match slice.try_into() {222 let array: Option<[u8; 32]> = match slice.try_into() {226 Ok(a) => Some(a),223 Ok(a) => Some(a),250 (247 (251 acc.clone(), // account id248 acc.clone(), // account id252 acc, // validator id249 acc, // validator id253 SessionKeys { aura: aura.clone() }, // session keys250 SessionKeys { aura }, // session keys254 )251 )255 })252 })256 .collect::<Vec<_>>();253 .collect::<Vec<_>>();257254258 for (account, val, keys) in keys.iter().cloned() {255 for (account, val, keys) in keys.iter() {259 for id in <Runtime as pallet_session::Config>::Keys::key_ids() {256 for id in <Runtime as pallet_session::Config>::Keys::key_ids() {260 <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), &val)257 <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), val)261 }258 }262 <pallet_session::NextKeys<Runtime>>::insert(&val, &keys);259 <pallet_session::NextKeys<Runtime>>::insert(val, keys);263 // todo exercise caution, the following is taken from genesis260 // todo exercise caution, the following is taken from genesis264 if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(&account)261 if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(account)265 .is_err()262 .is_err()266 {263 {267 log::warn!(264 log::warn!(271 // genesis) so it's really not a big deal and we assume that the user wants to268 // genesis) so it's really not a big deal and we assume that the user wants to272 // do this since it's the only way a non-endowed account can contain a session269 // do this since it's the only way a non-endowed account can contain a session273 // key.270 // key.274 frame_system::Pallet::<Runtime>::inc_providers(&account);271 frame_system::Pallet::<Runtime>::inc_providers(account);275 }272 }276 }273 }277274runtime/common/runtime_apis.rsdiffbeforeafterboth84 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {84 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {85 let budget = up_data_structs::budget::Value::new(10);85 let budget = up_data_structs::budget::Value::new(10);868687 Ok(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?)87 <pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)88 }88 }89 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {89 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {90 Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))90 Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))runtime/common/sponsoring.rsdiffbeforeafterboth240 withdraw_set_token_property(240 withdraw_set_token_property(241 &collection,241 &collection,242 &T::CrossAccountId::from_sub(who.clone()),242 &T::CrossAccountId::from_sub(who.clone()),243 &token_id,243 token_id,244 // No overflow may happen, as data larger than usize can't reach here244 // No overflow may happen, as data larger than usize can't reach here245 properties.iter().map(|p| p.key.len() + p.value.len()).sum(),245 properties.iter().map(|p| p.key.len() + p.value.len()).sum(),246 )246 )test-pallets/utils/src/lib.rsdiffbeforeafterboth170 fn ensure_origin_and_enabled(origin: OriginFor<T>) -> DispatchResult {170 fn ensure_origin_and_enabled(origin: OriginFor<T>) -> DispatchResult {171 ensure_signed(origin)?;171 ensure_signed(origin)?;172 <Enabled<T>>::get()172 <Enabled<T>>::get()173 .then(|| ())173 .then_some(())174 .ok_or(<Error<T>>::TestPalletDisabled.into())174 .ok_or(<Error<T>>::TestPalletDisabled.into())175 }175 }176}176}