difftreelog
fix clippy warnings
in: master
36 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -110,7 +110,7 @@
/// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
- TPublic::Pair::from_string(&format!("//{}", seed), None)
+ TPublic::Pair::from_string(&format!("//{seed}"), None)
.expect("static values are valid; qed")
.public()
}
node/cli/src/command.rsdiffbeforeafterboth--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -83,7 +83,7 @@
"" | "local" => Box::new(chain_spec::local_testnet_config()),
path => {
let path = std::path::PathBuf::from(path);
- let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)
+ let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path)?)
as Box<dyn sc_service::ChainSpec>;
match chain_spec.runtime_id() {
@@ -352,7 +352,7 @@
&polkadot_cli,
config.tokio_handle.clone(),
)
- .map_err(|err| format!("Relay chain argument error: {}", err))?;
+ .map_err(|err| format!("Relay chain argument error: {err}"))?;
cmd.run(config, polkadot_config)
})
@@ -464,7 +464,7 @@
runner.run_node_until_exit(|config| async move {
let hwbench = if !cli.no_hardware_benchmarks {
config.database.path().map(|database_path| {
- let _ = std::fs::create_dir_all(&database_path);
+ let _ = std::fs::create_dir_all(database_path);
sc_sysinfo::gather_hwbench(Some(database_path))
})
} else {
@@ -513,7 +513,7 @@
let state_version =
RelayChainCli::native_runtime_version(&config.chain_spec).state_version();
let block: Block = generate_genesis_block(&*config.chain_spec, state_version)
- .map_err(|e| format!("{:?}", e))?;
+ .map_err(|e| format!("{e:?}"))?;
let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));
let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));
@@ -522,7 +522,7 @@
&polkadot_cli,
config.tokio_handle.clone(),
)
- .map_err(|err| format!("Relay chain argument error: {}", err))?;
+ .map_err(|err| format!("Relay chain argument error: {err}"))?;
info!("Parachain id: {:?}", para_id);
info!("Parachain Account: {}", parachain_account);
node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -698,7 +698,7 @@
{
let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
- let block_import = ParachainBlockImport::new(client.clone(), backend.clone());
+ let block_import = ParachainBlockImport::new(client.clone(), backend);
cumulus_client_consensus_aura::import_queue::<
sp_consensus_aura::sr25519::AuthorityPair,
@@ -709,7 +709,7 @@
_,
>(cumulus_client_consensus_aura::ImportQueueParams {
block_import,
- client: client.clone(),
+ client,
create_inherent_data_providers: move |_, _| async move {
let time = sp_timestamp::InherentDataProvider::from_system_time();
@@ -787,7 +787,7 @@
telemetry.clone(),
);
- let block_import = ParachainBlockImport::new(client.clone(), backend.clone());
+ let block_import = ParachainBlockImport::new(client.clone(), backend);
Ok(AuraConsensus::build::<
sp_consensus_aura::sr25519::AuthorityPair,
@@ -864,7 +864,7 @@
ExecutorDispatch: NativeExecutionDispatch + 'static,
{
Ok(sc_consensus_manual_seal::import_queue(
- Box::new(client.clone()),
+ Box::new(client),
&task_manager.spawn_essential_handle(),
config.prometheus_registry(),
))
@@ -956,7 +956,7 @@
let collator = config.role.is_authority();
- let select_chain = maybe_select_chain.clone();
+ let select_chain = maybe_select_chain;
if collator {
let block_import =
node/rpc/src/lib.rsdiffbeforeafterboth--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -289,7 +289,7 @@
io.merge(
Net::new(
client.clone(),
- network.clone(),
+ network,
// Whether to format the `peer_count` response as Hex (default) or not.
true,
)
pallets/app-promotion/src/lib.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -296,7 +296,7 @@
if !block_pending.is_empty() {
block_pending.into_iter().for_each(|(staker, amount)| {
- Self::get_frozen_balance(&staker).map(|b| {
+ if let Some(b) = Self::get_frozen_balance(&staker) {
let new_state = b.checked_sub(&amount).unwrap_or_default();
// In this case, setting a new state for the frozen funds cannot fail
@@ -305,7 +305,7 @@
// that we cannot (in the current implementation) unfreeze more funds
// than were originally frozen by the pallet. Either way, `on_initialize()` cannot fail.
Self::set_freeze_unchecked(&staker, new_state);
- });
+ };
});
}
@@ -598,8 +598,8 @@
// this value is set for the stakers to whom the recalculation will be performed
let next_recalc_block = current_recalc_block + config.recalculation_interval;
- let mut storage_iterator = Self::get_next_calculated_key()
- .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));
+ let storage_iterator =
+ Self::get_next_calculated_key().map_or(Staked::<T>::iter(), Staked::<T>::iter_from);
PreviousCalculatedRecord::<T>::set(None);
@@ -658,10 +658,8 @@
// stakers_number - keeps the remaining number of iterations (staker addresses to handle)
// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out
// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)
- while let Some((
- (current_id, staked_block),
- (amount, next_recalc_block_for_stake),
- )) = storage_iterator.next()
+ for ((current_id, staked_block), (amount, next_recalc_block_for_stake)) in
+ storage_iterator
{
// last_id is not equal current_id when we switch to handling a new staker address
// or just start handling the very first address. In the latter case last_id will be None and
@@ -859,11 +857,11 @@
if acc_amount < balance_per_block {
let res = (block, balance_per_block - acc_amount);
acc_amount = <BalanceOf<T>>::default();
- return Some(res);
+ Some(res)
} else {
acc_amount -= balance_per_block;
will_deleted_stakes_count += 1;
- return Some((block, <BalanceOf<T>>::default()));
+ Some((block, <BalanceOf<T>>::default()))
}
})
.collect::<Vec<_>>();
@@ -926,7 +924,7 @@
if amount.is_zero() {
<<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(
&T::FreezeIdentifier::get(),
- &staker,
+ staker,
)
} else {
<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(
@@ -1026,10 +1024,10 @@
) {
let income = Self::calculate_income(base, iters);
- base.checked_add(&income).map(|res| {
+ if let Some(res) = base.checked_add(&income) {
<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));
*income_acc += income;
- });
+ };
}
fn calculate_income<I>(base: I, iters: u32) -> I
pallets/app-promotion/src/types.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/types.rs
+++ b/pallets/app-promotion/src/types.rs
@@ -149,16 +149,16 @@
Self {
recalculation_interval: config
.recalculation_interval
- .unwrap_or_else(|| T::RecalculationInterval::get()),
+ .unwrap_or_else(T::RecalculationInterval::get),
pending_interval: config
.pending_interval
- .unwrap_or_else(|| T::PendingInterval::get()),
+ .unwrap_or_else(T::PendingInterval::get),
interval_income: config
.interval_income
- .unwrap_or_else(|| T::IntervalIncome::get()),
+ .unwrap_or_else(T::IntervalIncome::get),
max_stakers_per_calculation: config
.max_stakers_per_calculation
- .unwrap_or_else(|| MAX_NUMBER_PAYOUTS),
+ .unwrap_or(MAX_NUMBER_PAYOUTS),
}
}
}
pallets/balances-adapter/src/lib.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/lib.rs
+++ b/pallets/balances-adapter/src/lib.rs
@@ -31,6 +31,12 @@
}
}
+impl<T: Config> Default for NativeFungibleHandle<T> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl<T: Config> WithRecorder<T> for NativeFungibleHandle<T> {
fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {
&self.0
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -136,7 +136,7 @@
fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {
let key = evm_coder::types::String::from_utf8(from.key.into())
- .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {}", e)))?;
+ .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {e}")))?;
let value = evm_coder::types::Bytes(from.value.to_vec());
Ok(Property { key, value })
}
@@ -201,10 +201,7 @@
pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {
Self {
field,
- value: match value {
- Some(value) => Some(value.into()),
- None => None,
- },
+ value: value.map(|value| value.into()),
}
}
/// Whether the field contains a value.
@@ -222,8 +219,7 @@
.ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;
let value = Some(value.try_into().map_err(|error| {
Self::Error::Revert(format!(
- "can't convert value to u32 \"{}\" because: \"{error}\"",
- value
+ "can't convert value to u32 \"{value}\" because: \"{error}\""
))
})?);
@@ -249,10 +245,8 @@
limits.sponsored_data_size = value;
}
CollectionLimitField::SponsoredDataRateLimit => {
- limits.sponsored_data_rate_limit = match value {
- Some(value) => Some(up_data_structs::SponsoringRateLimit::Blocks(value)),
- None => None,
- };
+ limits.sponsored_data_rate_limit =
+ value.map(up_data_structs::SponsoringRateLimit::Blocks);
}
CollectionLimitField::TokenLimit => {
limits.token_limit = value;
@@ -454,9 +448,9 @@
}
}
-impl Into<up_data_structs::AccessMode> for AccessMode {
- fn into(self) -> up_data_structs::AccessMode {
- match self {
+impl From<AccessMode> for up_data_structs::AccessMode {
+ fn from(value: AccessMode) -> Self {
+ match value {
AccessMode::Normal => up_data_structs::AccessMode::Normal,
AccessMode::AllowList => up_data_structs::AccessMode::AllowList,
}
pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -260,9 +260,9 @@
message: Some(msg), ..
}) => ExError::Revert(msg.into()),
DispatchError::Module(ModuleError { index, error, .. }) => {
- ExError::Revert(format!("error {:?} in pallet {}", error, index))
+ ExError::Revert(format!("error {error:?} in pallet {index}"))
}
- e => ExError::Revert(format!("substrate error: {:?}", e)),
+ e => ExError::Revert(format!("substrate error: {e:?}")),
}
}
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -184,10 +184,9 @@
/// @param contractAddress The contract for which a sponsor is requested.
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
fn sponsor(&self, contract_address: Address) -> Result<Option<eth::CrossAddress>> {
- Ok(match Pallet::<T>::get_sponsor(contract_address) {
- Some(ref value) => Some(eth::CrossAddress::from_sub_cross_account::<T>(value)),
- None => None,
- })
+ Ok(Pallet::<T>::get_sponsor(contract_address)
+ .as_ref()
+ .map(eth::CrossAddress::from_sub_cross_account::<T>))
}
/// Check tat contract has confirmed sponsor.
@@ -275,7 +274,7 @@
self.recorder().consume_sstore()?;
<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;
- <Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())
+ <Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit)
.map_err(dispatch_to_evm::<T>)?;
Ok(())
}
pallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -376,7 +376,7 @@
<SponsoringMode<T>>::get(contract)
.or_else(|| {
#[allow(deprecated)]
- <SelfSponsoring<T>>::get(contract).then(|| SponsoringModeT::Allowlisted)
+ <SelfSponsoring<T>>::get(contract).then_some(SponsoringModeT::Allowlisted)
})
.unwrap_or_default()
}
@@ -410,7 +410,7 @@
/// Is user added to allowlist, or he is owner of specified contract
pub fn allowed(contract: H160, user: H160) -> bool {
- <Allowlist<T>>::get(&contract, &user) || <Owner<T>>::get(&contract) == user
+ <Allowlist<T>>::get(contract, user) || <Owner<T>>::get(contract) == user
}
/// Toggle contract allowlist access
@@ -425,7 +425,7 @@
/// Throw error if user is not allowed to reconfigure target contract
pub fn ensure_owner(contract: H160, user: H160) -> DispatchResult {
- ensure!(<Owner<T>>::get(&contract) == user, Error::<T>::NoPermission);
+ ensure!(<Owner<T>>::get(contract) == user, Error::<T>::NoPermission);
Ok(())
}
}
pallets/evm-migration/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-migration/src/lib.rs
+++ b/pallets/evm-migration/src/lib.rs
@@ -78,7 +78,7 @@
pub fn begin(origin: OriginFor<T>, address: H160) -> DispatchResult {
ensure_root(origin)?;
ensure!(
- <PalletEvm<T>>::is_account_empty(&address) && !<MigrationPending<T>>::get(&address),
+ <PalletEvm<T>>::is_account_empty(&address) && !<MigrationPending<T>>::get(address),
<Error<T>>::AccountNotEmpty,
);
@@ -97,12 +97,12 @@
) -> DispatchResult {
ensure_root(origin)?;
ensure!(
- <MigrationPending<T>>::get(&address),
+ <MigrationPending<T>>::get(address),
<Error<T>>::AccountIsNotMigrating,
);
for (k, v) in data {
- <pallet_evm::AccountStorages<T>>::insert(&address, k, v);
+ <pallet_evm::AccountStorages<T>>::insert(address, k, v);
}
Ok(())
}
@@ -115,11 +115,11 @@
pub fn finish(origin: OriginFor<T>, address: H160, code: Vec<u8>) -> DispatchResult {
ensure_root(origin)?;
ensure!(
- <MigrationPending<T>>::get(&address),
+ <MigrationPending<T>>::get(address),
<Error<T>>::AccountIsNotMigrating,
);
- <pallet_evm::AccountCodes<T>>::insert(&address, code);
+ <pallet_evm::AccountCodes<T>>::insert(address, code);
<MigrationPending<T>>::remove(address);
Ok(())
}
@@ -166,7 +166,7 @@
pub struct OnMethodCall<T>(PhantomData<T>);
impl<T: Config> pallet_evm::OnMethodCall<T> for OnMethodCall<T> {
fn is_reserved(contract: &H160) -> bool {
- <MigrationPending<T>>::get(&contract)
+ <MigrationPending<T>>::get(contract)
}
fn is_used(_contract: &H160) -> bool {
pallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ b/pallets/foreign-assets/src/impl_fungibles.rs
@@ -333,7 +333,7 @@
&Value::new(0),
)?;
- Ok(amount.into())
+ Ok(amount)
}
}
}
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -161,7 +161,7 @@
fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {
log::trace!(target: "fassets::get_currency_id", "call");
- Pallet::<T>::location_to_currency_ids(multi_location).map(|id| AssetIds::ForeignAssetId(id))
+ Pallet::<T>::location_to_currency_ids(multi_location).map(AssetIds::ForeignAssetId)
}
}
@@ -378,7 +378,7 @@
foreign_asset_id,
|maybe_location| -> DispatchResult {
ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);
- *maybe_location = Some(location.clone());
+ *maybe_location = Some(*location);
AssetMetadatas::<T>::try_mutate(
AssetIds::ForeignAssetId(foreign_asset_id),
@@ -422,7 +422,7 @@
// modify location
if location != old_multi_locations {
- LocationToCurrencyIds::<T>::remove(old_multi_locations.clone());
+ LocationToCurrencyIds::<T>::remove(*old_multi_locations);
LocationToCurrencyIds::<T>::try_mutate(
location,
|maybe_currency_ids| -> DispatchResult {
@@ -437,7 +437,7 @@
)?;
}
*maybe_asset_metadatas = Some(metadata.clone());
- *old_multi_locations = location.clone();
+ *old_multi_locations = *location;
Ok(())
},
)
pallets/identity/src/types.rsdiffbeforeafterboth--- a/pallets/identity/src/types.rs
+++ b/pallets/identity/src/types.rs
@@ -104,7 +104,7 @@
Data::Raw(ref x) => {
let l = x.len().min(32);
let mut r = vec![l as u8 + 1; l + 1];
- r[1..].copy_from_slice(&x[..l as usize]);
+ r[1..].copy_from_slice(&x[..l]);
r
}
Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),
@@ -287,7 +287,7 @@
fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
let field = u64::decode(input)?;
Ok(Self(
- <BitFlags<IdentityField>>::from_bits(field as u64).map_err(|_| "invalid value")?,
+ <BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,
))
}
}
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -20,6 +20,8 @@
//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.
extern crate alloc;
+
+use alloc::string::ToString;
use core::{
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
@@ -356,8 +358,7 @@
.transpose()
.map_err(|e| {
Error::Revert(alloc::format!(
- "Can not convert value \"baseURI\" to string with error \"{}\"",
- e
+ "Can not convert value \"baseURI\" to string with error \"{e}\""
))
})?;
@@ -675,7 +676,7 @@
.try_into()
.map_err(|_| "token uri is too long")?,
})
- .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
<Pallet<T>>::create_item(
self,
@@ -717,7 +718,7 @@
.map(Clone::clone)
.ok_or_else(|| {
let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();
- Error::Revert(alloc::format!("No permission for key {}", key))
+ Error::Revert(alloc::format!("No permission for key {key}"))
})?;
Ok(a)
}
@@ -752,14 +753,14 @@
/// @param tokenId Id for the token.
#[solidity(hide)]
fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
- Self::owner_of_cross(&self, token_id)
+ Self::owner_of_cross(self, token_id)
}
/// Returns the owner (in cross format) of the token.
///
/// @param tokenId Id for the token.
fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {
- Self::token_owner(&self, token_id.try_into()?)
+ Self::token_owner(self, token_id.try_into()?)
.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
.map_err(|_| Error::Revert("token not found".into()))
}
@@ -789,7 +790,7 @@
.collect::<Result<Vec<_>>>()?;
<Self as CommonCollectionOperations<T>>::token_properties(
- &self,
+ self,
token_id.try_into()?,
if keys.is_empty() { None } else { Some(keys) },
)
@@ -1021,7 +1022,7 @@
.try_into()
.map_err(|_| "token uri is too long")?,
})
- .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
data.push(CreateItemData::<T> {
properties,
@@ -1056,7 +1057,7 @@
.map(eth::Property::try_into)
.collect::<Result<Vec<_>>>()?
.try_into()
- .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;
+ .map_err(|_| Error::Revert("too many properties".to_string()))?;
let caller = T::CrossAccountId::from_eth(caller);
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -166,10 +166,7 @@
#[pallet::config]
pub trait Config:
- frame_system::Config
- + pallet_common::Config
- + pallet_structure::Config
- + pallet_evm::Config
+ frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config
{
type WeightInfo: WeightInfo;
}
@@ -860,13 +857,7 @@
<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);
- <TokenData<T>>::insert(
- (collection.id, token),
- ItemData {
- owner: to.clone(),
- ..token_data
- },
- );
+ <TokenData<T>>::insert((collection.id, token), ItemData { owner: to.clone() });
if let Some(balance_to) = balance_to {
// from != to
pallets/refungible/src/erc.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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use core::{25 char::{REPLACEMENT_CHARACTER, decode_utf16},26 convert::TryInto,27};28use evm_coder::{abi::AbiType, ToLog, generate_stubgen, solidity_interface, types::*};29use frame_support::{BoundedBTreeMap, BoundedVec};30use pallet_common::{31 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,32 Error as CommonError,33 erc::{CommonEvmHandler, CollectionCall, static_property::key},34 eth::{self, TokenUri},35};36use pallet_evm::{account::CrossAccountId, PrecompileHandle};37use pallet_evm_coder_substrate::{38 call, dispatch_to_evm,39 execution::{PreDispatch, Result, Error},40 frontier_contract,41};42use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};43use sp_core::{H160, U256, Get};44use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};45use up_data_structs::{46 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,47 PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,48};4950use crate::{51 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, TokenProperties,52 TokensMinted, TotalSupply, SelfWeightOf, weights::WeightInfo,53};5455frontier_contract! {56 macro_rules! RefungibleHandle_result {...}57 impl<T: Config> Contract for RefungibleHandle<T> {...}58}5960pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);6162/// Rft events.63#[derive(ToLog)]64pub enum ERC721TokenEvent {65 /// The token has been changed.66 TokenChanged {67 /// Token ID.68 #[indexed]69 token_id: U256,70 },71}7273/// @title A contract that allows to set and delete token properties and change token property permissions.74#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]75impl<T: Config> RefungibleHandle<T> {76 /// @notice Set permissions for token property.77 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.78 /// @param key Property key.79 /// @param isMutable Permission to mutate property.80 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.81 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.82 #[solidity(hide)]83 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]84 fn set_token_property_permission(85 &mut self,86 caller: Caller,87 key: String,88 is_mutable: bool,89 collection_admin: bool,90 token_owner: bool,91 ) -> Result<()> {92 let caller = T::CrossAccountId::from_eth(caller);93 <Pallet<T>>::set_token_property_permissions(94 self,95 &caller,96 vec![PropertyKeyPermission {97 key: <Vec<u8>>::from(key)98 .try_into()99 .map_err(|_| "too long key")?,100 permission: PropertyPermission {101 mutable: is_mutable,102 collection_admin,103 token_owner,104 },105 }],106 )107 .map_err(dispatch_to_evm::<T>)108 }109110 /// @notice Set permissions for token property.111 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.112 /// @param permissions Permissions for keys.113 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]114 fn set_token_property_permissions(115 &mut self,116 caller: Caller,117 permissions: Vec<eth::TokenPropertyPermission>,118 ) -> Result<()> {119 let caller = T::CrossAccountId::from_eth(caller);120 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;121122 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)123 .map_err(dispatch_to_evm::<T>)124 }125126 /// @notice Get permissions for token properties.127 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {128 let perms = <Pallet<T>>::token_property_permission(self.id);129 Ok(perms130 .into_iter()131 .map(eth::TokenPropertyPermission::from)132 .collect())133 }134135 /// @notice Set token property value.136 /// @dev Throws error if `msg.sender` has no permission to edit the property.137 /// @param tokenId ID of the token.138 /// @param key Property key.139 /// @param value Property value.140 #[solidity(hide)]141 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]142 fn set_property(143 &mut self,144 caller: Caller,145 token_id: U256,146 key: String,147 value: Bytes,148 ) -> Result<()> {149 let caller = T::CrossAccountId::from_eth(caller);150 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;151 let key = <Vec<u8>>::from(key)152 .try_into()153 .map_err(|_| "key too long")?;154 let value = value.0.try_into().map_err(|_| "value too long")?;155156 let nesting_budget = self157 .recorder158 .weight_calls_budget(<StructureWeight<T>>::find_parent());159160 <Pallet<T>>::set_token_property(161 self,162 &caller,163 TokenId(token_id),164 Property { key, value },165 &nesting_budget,166 )167 .map_err(dispatch_to_evm::<T>)168 }169170 /// @notice Set token properties value.171 /// @dev Throws error if `msg.sender` has no permission to edit the property.172 /// @param tokenId ID of the token.173 /// @param properties settable properties174 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]175 fn set_properties(176 &mut self,177 caller: Caller,178 token_id: U256,179 properties: Vec<eth::Property>,180 ) -> Result<()> {181 let caller = T::CrossAccountId::from_eth(caller);182 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;183184 let nesting_budget = self185 .recorder186 .weight_calls_budget(<StructureWeight<T>>::find_parent());187188 let properties = properties189 .into_iter()190 .map(eth::Property::try_into)191 .collect::<Result<Vec<_>>>()?;192193 <Pallet<T>>::set_token_properties(194 self,195 &caller,196 TokenId(token_id),197 properties.into_iter(),198 false,199 &nesting_budget,200 )201 .map_err(dispatch_to_evm::<T>)202 }203204 /// @notice Delete token property value.205 /// @dev Throws error if `msg.sender` has no permission to edit the property.206 /// @param tokenId ID of the token.207 /// @param key Property key.208 #[solidity(hide)]209 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]210 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {211 let caller = T::CrossAccountId::from_eth(caller);212 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;213 let key = <Vec<u8>>::from(key)214 .try_into()215 .map_err(|_| "key too long")?;216217 let nesting_budget = self218 .recorder219 .weight_calls_budget(<StructureWeight<T>>::find_parent());220221 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)222 .map_err(dispatch_to_evm::<T>)223 }224225 /// @notice Delete token properties value.226 /// @dev Throws error if `msg.sender` has no permission to edit the property.227 /// @param tokenId ID of the token.228 /// @param keys Properties key.229 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]230 fn delete_properties(231 &mut self,232 token_id: U256,233 caller: Caller,234 keys: Vec<String>,235 ) -> Result<()> {236 let caller = T::CrossAccountId::from_eth(caller);237 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;238 let keys = keys239 .into_iter()240 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))241 .collect::<Result<Vec<_>>>()?;242243 let nesting_budget = self244 .recorder245 .weight_calls_budget(<StructureWeight<T>>::find_parent());246247 <Pallet<T>>::delete_token_properties(248 self,249 &caller,250 TokenId(token_id),251 keys.into_iter(),252 &nesting_budget,253 )254 .map_err(dispatch_to_evm::<T>)255 }256257 /// @notice Get token property value.258 /// @dev Throws error if key not found259 /// @param tokenId ID of the token.260 /// @param key Property key.261 /// @return Property value bytes262 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {263 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;264 let key = <Vec<u8>>::from(key)265 .try_into()266 .map_err(|_| "key too long")?;267268 let props = <TokenProperties<T>>::get((self.id, token_id));269 let prop = props.get(&key).ok_or("key not found")?;270271 Ok(prop.to_vec().into())272 }273}274275#[derive(ToLog)]276pub enum ERC721Events {277 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed278 /// (`to` == 0). Exception: during contract creation, any number of RFTs279 /// may be created and assigned without emitting Transfer.280 Transfer {281 #[indexed]282 from: Address,283 #[indexed]284 to: Address,285 #[indexed]286 token_id: U256,287 },288 /// @dev Not supported289 Approval {290 #[indexed]291 owner: Address,292 #[indexed]293 approved: Address,294 #[indexed]295 token_id: U256,296 },297 /// @dev Not supported298 #[allow(dead_code)]299 ApprovalForAll {300 #[indexed]301 owner: Address,302 #[indexed]303 operator: Address,304 approved: bool,305 },306}307308/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension309/// @dev See https://eips.ethereum.org/EIPS/eip-721310#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]311impl<T: Config> RefungibleHandle<T>312where313 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,314{315 /// @notice A descriptive name for a collection of NFTs in this contract316 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`317 #[solidity(hide, rename_selector = "name")]318 fn name_proxy(&self) -> Result<String> {319 self.name()320 }321322 /// @notice An abbreviated name for NFTs in this contract323 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`324 #[solidity(hide, rename_selector = "symbol")]325 fn symbol_proxy(&self) -> Result<String> {326 self.symbol()327 }328329 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.330 ///331 /// @dev If the token has a `url` property and it is not empty, it is returned.332 /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.333 /// If the collection property `baseURI` is empty or absent, return "" (empty string)334 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix335 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).336 ///337 /// @return token's const_metadata338 #[solidity(rename_selector = "tokenURI")]339 fn token_uri(&self, token_id: U256) -> Result<String> {340 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;341342 match get_token_property(self, token_id_u32, &key::url()).as_deref() {343 Err(_) | Ok("") => (),344 Ok(url) => {345 return Ok(url.into());346 }347 };348349 let base_uri =350 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())351 .map(BoundedVec::into_inner)352 .map(String::from_utf8)353 .transpose()354 .map_err(|e| {355 Error::Revert(alloc::format!(356 "Can not convert value \"baseURI\" to string with error \"{}\"",357 e358 ))359 })?;360361 let base_uri = match base_uri.as_deref() {362 None | Some("") => {363 return Ok("".into());364 }365 Some(base_uri) => base_uri.into(),366 };367368 Ok(369 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {370 Err(_) | Ok("") => base_uri,371 Ok(suffix) => base_uri + suffix,372 },373 )374 }375}376377/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension378/// @dev See https://eips.ethereum.org/EIPS/eip-721379#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]380impl<T: Config> RefungibleHandle<T> {381 /// @notice Enumerate valid RFTs382 /// @param index A counter less than `totalSupply()`383 /// @return The token identifier for the `index`th NFT,384 /// (sort order not specified)385 fn token_by_index(&self, index: U256) -> U256 {386 index387 }388389 /// Not implemented390 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {391 // TODO: Not implemetable392 Err("not implemented".into())393 }394395 /// @notice Count RFTs tracked by this contract396 /// @return A count of valid RFTs tracked by this contract, where each one of397 /// them has an assigned and queryable owner not equal to the zero address398 fn total_supply(&self) -> Result<U256> {399 self.consume_store_reads(1)?;400 Ok(<Pallet<T>>::total_supply(self).into())401 }402}403404/// @title ERC-721 Non-Fungible Token Standard405/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md406#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]407impl<T: Config> RefungibleHandle<T> {408 /// @notice Count all RFTs assigned to an owner409 /// @dev RFTs assigned to the zero address are considered invalid, and this410 /// function throws for queries about the zero address.411 /// @param owner An address for whom to query the balance412 /// @return The number of RFTs owned by `owner`, possibly zero413 fn balance_of(&self, owner: Address) -> Result<U256> {414 self.consume_store_reads(1)?;415 let owner = T::CrossAccountId::from_eth(owner);416 let balance = <AccountBalance<T>>::get((self.id, owner));417 Ok(balance.into())418 }419420 /// @notice Find the owner of an RFT421 /// @dev RFTs assigned to zero address are considered invalid, and queries422 /// about them do throw.423 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for424 /// the tokens that are partially owned.425 /// @param tokenId The identifier for an RFT426 /// @return The address of the owner of the RFT427 fn owner_of(&self, token_id: U256) -> Result<Address> {428 self.consume_store_reads(2)?;429 let token = token_id.try_into()?;430 let owner = <Pallet<T>>::token_owner(self.id, token);431 owner432 .map(|address| *address.as_eth())433 .or_else(|err| match err {434 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),435 TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),436 })437 }438439 /// @dev Not implemented440 #[solidity(rename_selector = "safeTransferFrom")]441 fn safe_transfer_from_with_data(442 &mut self,443 _from: Address,444 _to: Address,445 _token_id: U256,446 _data: Bytes,447 ) -> Result<()> {448 // TODO: Not implemetable449 Err("not implemented".into())450 }451452 /// @dev Not implemented453 #[solidity(rename_selector = "safeTransferFrom")]454 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {455 // TODO: Not implemetable456 Err("not implemented".into())457 }458459 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE460 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE461 /// THEY MAY BE PERMANENTLY LOST462 /// @dev Throws unless `msg.sender` is the current owner or an authorized463 /// operator for this RFT. Throws if `from` is not the current owner. Throws464 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.465 /// Throws if RFT pieces have multiple owners.466 /// @param from The current owner of the NFT467 /// @param to The new owner468 /// @param tokenId The NFT to transfer469 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]470 fn transfer_from(471 &mut self,472 caller: Caller,473 from: Address,474 to: Address,475 token_id: U256,476 ) -> Result<()> {477 let caller = T::CrossAccountId::from_eth(caller);478 let from = T::CrossAccountId::from_eth(from);479 let to = T::CrossAccountId::from_eth(to);480 let token = token_id.try_into()?;481 let budget = self482 .recorder483 .weight_calls_budget(<StructureWeight<T>>::find_parent());484485 let balance = balance(&self, token, &from)?;486 ensure_single_owner(&self, token, balance)?;487488 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)489 .map_err(dispatch_to_evm::<T>)?;490491 Ok(())492 }493494 /// @dev Not implemented495 fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {496 Err("not implemented".into())497 }498499 /// @notice Sets or unsets the approval of a given operator.500 /// The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.501 /// @param operator Operator502 /// @param approved Should operator status be granted or revoked?503 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]504 fn set_approval_for_all(505 &mut self,506 caller: Caller,507 operator: Address,508 approved: bool,509 ) -> Result<()> {510 let caller = T::CrossAccountId::from_eth(caller);511 let operator = T::CrossAccountId::from_eth(operator);512513 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)514 .map_err(dispatch_to_evm::<T>)?;515 Ok(())516 }517518 /// @dev Not implemented519 fn get_approved(&self, _token_id: U256) -> Result<Address> {520 // TODO: Not implemetable521 Err("not implemented".into())522 }523524 /// @notice Tells whether the given `owner` approves the `operator`.525 #[weight(<SelfWeightOf<T>>::allowance_for_all())]526 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {527 let owner = T::CrossAccountId::from_eth(owner);528 let operator = T::CrossAccountId::from_eth(operator);529530 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))531 }532}533534/// Returns amount of pieces of `token` that `owner` have535pub fn balance<T: Config>(536 collection: &RefungibleHandle<T>,537 token: TokenId,538 owner: &T::CrossAccountId,539) -> Result<u128> {540 collection.consume_store_reads(1)?;541 let balance = <Balance<T>>::get((collection.id, token, &owner));542 Ok(balance)543}544545/// Throws if `owner_balance` is lower than total amount of `token` pieces546pub fn ensure_single_owner<T: Config>(547 collection: &RefungibleHandle<T>,548 token: TokenId,549 owner_balance: u128,550) -> Result<()> {551 collection.consume_store_reads(1)?;552 let total_supply = <TotalSupply<T>>::get((collection.id, token));553554 if owner_balance == 0 {555 return Err(dispatch_to_evm::<T>(556 <CommonError<T>>::MustBeTokenOwner.into(),557 ));558 }559560 if total_supply != owner_balance {561 return Err("token has multiple owners".into());562 }563 Ok(())564}565566/// @title ERC721 Token that can be irreversibly burned (destroyed).567#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]568impl<T: Config> RefungibleHandle<T> {569 /// @notice Burns a specific ERC721 token.570 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized571 /// operator of the current owner.572 /// @param tokenId The RFT to approve573 #[weight(<SelfWeightOf<T>>::burn_item_fully())]574 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {575 let caller = T::CrossAccountId::from_eth(caller);576 let token = token_id.try_into()?;577578 let balance = balance(&self, token, &caller)?;579 ensure_single_owner(&self, token, balance)?;580581 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;582 Ok(())583 }584}585586/// @title ERC721 minting logic.587#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]588impl<T: Config> RefungibleHandle<T> {589 /// @notice Function to mint a token.590 /// @param to The new owner591 /// @return uint256 The id of the newly minted token592 #[weight(<SelfWeightOf<T>>::create_item())]593 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {594 let token_id: U256 = <TokensMinted<T>>::get(self.id)595 .checked_add(1)596 .ok_or("item id overflow")?597 .into();598 self.mint_check_id(caller, to, token_id)?;599 Ok(token_id)600 }601602 /// @notice Function to mint a token.603 /// @dev `tokenId` should be obtained with `nextTokenId` method,604 /// unlike standard, you can't specify it manually605 /// @param to The new owner606 /// @param tokenId ID of the minted RFT607 #[solidity(hide, rename_selector = "mint")]608 #[weight(<SelfWeightOf<T>>::create_item())]609 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {610 let caller = T::CrossAccountId::from_eth(caller);611 let to = T::CrossAccountId::from_eth(to);612 let token_id: u32 = token_id.try_into()?;613 let budget = self614 .recorder615 .weight_calls_budget(<StructureWeight<T>>::find_parent());616617 if <TokensMinted<T>>::get(self.id)618 .checked_add(1)619 .ok_or("item id overflow")?620 != token_id621 {622 return Err("item id should be next".into());623 }624625 let users = [(to.clone(), 1)]626 .into_iter()627 .collect::<BTreeMap<_, _>>()628 .try_into()629 .unwrap();630 <Pallet<T>>::create_item(631 self,632 &caller,633 CreateItemData::<T> {634 users,635 properties: CollectionPropertiesVec::default(),636 },637 &budget,638 )639 .map_err(dispatch_to_evm::<T>)?;640641 Ok(true)642 }643644 /// @notice Function to mint token with the given tokenUri.645 /// @param to The new owner646 /// @param tokenUri Token URI that would be stored in the NFT properties647 /// @return uint256 The id of the newly minted token648 #[solidity(rename_selector = "mintWithTokenURI")]649 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]650 fn mint_with_token_uri(651 &mut self,652 caller: Caller,653 to: Address,654 token_uri: String,655 ) -> Result<U256> {656 let token_id: U256 = <TokensMinted<T>>::get(self.id)657 .checked_add(1)658 .ok_or("item id overflow")?659 .into();660 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;661 Ok(token_id)662 }663664 /// @notice Function to mint token with the given tokenUri.665 /// @dev `tokenId` should be obtained with `nextTokenId` method,666 /// unlike standard, you can't specify it manually667 /// @param to The new owner668 /// @param tokenId ID of the minted RFT669 /// @param tokenUri Token URI that would be stored in the RFT properties670 #[solidity(hide, rename_selector = "mintWithTokenURI")]671 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]672 fn mint_with_token_uri_check_id(673 &mut self,674 caller: Caller,675 to: Address,676 token_id: U256,677 token_uri: String,678 ) -> Result<bool> {679 let key = key::url();680 let permission = get_token_permission::<T>(self.id, &key)?;681 if !permission.collection_admin {682 return Err("Operation is not allowed".into());683 }684685 let caller = T::CrossAccountId::from_eth(caller);686 let to = T::CrossAccountId::from_eth(to);687 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;688 let budget = self689 .recorder690 .weight_calls_budget(<StructureWeight<T>>::find_parent());691692 if <TokensMinted<T>>::get(self.id)693 .checked_add(1)694 .ok_or("item id overflow")?695 != token_id696 {697 return Err("item id should be next".into());698 }699700 let mut properties = CollectionPropertiesVec::default();701 properties702 .try_push(Property {703 key,704 value: token_uri705 .into_bytes()706 .try_into()707 .map_err(|_| "token uri is too long")?,708 })709 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;710711 let users = [(to.clone(), 1)]712 .into_iter()713 .collect::<BTreeMap<_, _>>()714 .try_into()715 .unwrap();716 <Pallet<T>>::create_item(717 self,718 &caller,719 CreateItemData::<T> { users, properties },720 &budget,721 )722 .map_err(dispatch_to_evm::<T>)?;723 Ok(true)724 }725}726727fn get_token_property<T: Config>(728 collection: &CollectionHandle<T>,729 token_id: u32,730 key: &up_data_structs::PropertyKey,731) -> Result<String> {732 collection.consume_store_reads(1)?;733 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))734 .map_err(|_| Error::Revert("Token properties not found".into()))?;735 if let Some(property) = properties.get(key) {736 return Ok(String::from_utf8_lossy(property).into());737 }738739 Err("Property tokenURI not found".into())740}741742fn get_token_permission<T: Config>(743 collection_id: CollectionId,744 key: &PropertyKey,745) -> Result<PropertyPermission> {746 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)747 .map_err(|_| Error::Revert("No permissions for collection".into()))?;748 let a = token_property_permissions749 .get(key)750 .map(Clone::clone)751 .ok_or_else(|| {752 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();753 Error::Revert(alloc::format!("No permission for key {}", key))754 })?;755 Ok(a)756}757758/// @title Unique extensions for ERC721.759#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]760impl<T: Config> RefungibleHandle<T>761where762 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,763{764 /// @notice A descriptive name for a collection of NFTs in this contract765 fn name(&self) -> Result<String> {766 Ok(decode_utf16(self.name.iter().copied())767 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))768 .collect::<String>())769 }770771 /// @notice An abbreviated name for NFTs in this contract772 fn symbol(&self) -> Result<String> {773 Ok(String::from_utf8_lossy(&self.token_prefix).into())774 }775776 /// @notice A description for the collection.777 fn description(&self) -> Result<String> {778 Ok(decode_utf16(self.description.iter().copied())779 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))780 .collect::<String>())781 }782783 /// Returns the owner (in cross format) of the token.784 ///785 /// @param tokenId Id for the token.786 #[solidity(hide)]787 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {788 Self::owner_of_cross(&self, token_id)789 }790791 /// Returns the owner (in cross format) of the token.792 ///793 /// @param tokenId Id for the token.794 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {795 Self::token_owner(&self, token_id.try_into()?)796 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))797 .or_else(|err| match err {798 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),799 TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(800 ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,801 )),802 })803 }804805 /// @notice Count all RFTs assigned to an owner806 /// @param owner An cross address for whom to query the balance807 /// @return The number of RFTs owned by `owner`, possibly zero808 fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {809 self.consume_store_reads(1)?;810 let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));811 Ok(balance.into())812 }813814 /// Returns the token properties.815 ///816 /// @param tokenId Id for the token.817 /// @param keys Properties keys. Empty keys for all propertyes.818 /// @return Vector of properties key/value pairs.819 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {820 let keys = keys821 .into_iter()822 .map(|key| {823 <Vec<u8>>::from(key)824 .try_into()825 .map_err(|_| Error::Revert("key too large".into()))826 })827 .collect::<Result<Vec<_>>>()?;828829 <Self as CommonCollectionOperations<T>>::token_properties(830 &self,831 token_id.try_into()?,832 if keys.is_empty() { None } else { Some(keys) },833 )834 .into_iter()835 .map(eth::Property::try_from)836 .collect::<Result<Vec<_>>>()837 }838 /// @notice Transfer ownership of an RFT839 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`840 /// is the zero address. Throws if `tokenId` is not a valid RFT.841 /// Throws if RFT pieces have multiple owners.842 /// @param to The new owner843 /// @param tokenId The RFT to transfer844 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]845 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {846 let caller = T::CrossAccountId::from_eth(caller);847 let to = T::CrossAccountId::from_eth(to);848 let token = token_id.try_into()?;849 let budget = self850 .recorder851 .weight_calls_budget(<StructureWeight<T>>::find_parent());852853 let balance = balance(self, token, &caller)?;854 ensure_single_owner(self, token, balance)?;855856 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)857 .map_err(dispatch_to_evm::<T>)?;858 Ok(())859 }860861 /// @notice Transfer ownership of an RFT862 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`863 /// is the zero address. Throws if `tokenId` is not a valid RFT.864 /// Throws if RFT pieces have multiple owners.865 /// @param to The new owner866 /// @param tokenId The RFT to transfer867 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]868 fn transfer_cross(869 &mut self,870 caller: Caller,871 to: eth::CrossAddress,872 token_id: U256,873 ) -> Result<()> {874 let caller = T::CrossAccountId::from_eth(caller);875 let to = to.into_sub_cross_account::<T>()?;876 let token = token_id.try_into()?;877 let budget = self878 .recorder879 .weight_calls_budget(<StructureWeight<T>>::find_parent());880881 let balance = balance(self, token, &caller)?;882 ensure_single_owner(self, token, balance)?;883884 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)885 .map_err(dispatch_to_evm::<T>)?;886 Ok(())887 }888889 /// @notice Transfer ownership of an RFT890 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`891 /// is the zero address. Throws if `tokenId` is not a valid RFT.892 /// Throws if RFT pieces have multiple owners.893 /// @param to The new owner894 /// @param tokenId The RFT to transfer895 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]896 fn transfer_from_cross(897 &mut self,898 caller: Caller,899 from: eth::CrossAddress,900 to: eth::CrossAddress,901 token_id: U256,902 ) -> Result<()> {903 let caller = T::CrossAccountId::from_eth(caller);904 let from = from.into_sub_cross_account::<T>()?;905 let to = to.into_sub_cross_account::<T>()?;906 let token_id = token_id.try_into()?;907 let budget = self908 .recorder909 .weight_calls_budget(<StructureWeight<T>>::find_parent());910911 let balance = balance(self, token_id, &from)?;912 ensure_single_owner(self, token_id, balance)?;913914 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)915 .map_err(dispatch_to_evm::<T>)?;916 Ok(())917 }918919 /// @notice Burns a specific ERC721 token.920 /// @dev Throws unless `msg.sender` is the current owner or an authorized921 /// operator for this RFT. Throws if `from` is not the current owner. Throws922 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.923 /// Throws if RFT pieces have multiple owners.924 /// @param from The current owner of the RFT925 /// @param tokenId The RFT to transfer926 #[solidity(hide)]927 #[weight(<SelfWeightOf<T>>::burn_from())]928 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {929 let caller = T::CrossAccountId::from_eth(caller);930 let from = T::CrossAccountId::from_eth(from);931 let token = token_id.try_into()?;932 let budget = self933 .recorder934 .weight_calls_budget(<StructureWeight<T>>::find_parent());935936 let balance = balance(self, token, &from)?;937 ensure_single_owner(self, token, balance)?;938939 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)940 .map_err(dispatch_to_evm::<T>)?;941 Ok(())942 }943944 /// @notice Burns a specific ERC721 token.945 /// @dev Throws unless `msg.sender` is the current owner or an authorized946 /// operator for this RFT. Throws if `from` is not the current owner. Throws947 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.948 /// Throws if RFT pieces have multiple owners.949 /// @param from The current owner of the RFT950 /// @param tokenId The RFT to transfer951 #[weight(<SelfWeightOf<T>>::burn_from())]952 fn burn_from_cross(953 &mut self,954 caller: Caller,955 from: eth::CrossAddress,956 token_id: U256,957 ) -> Result<()> {958 let caller = T::CrossAccountId::from_eth(caller);959 let from = from.into_sub_cross_account::<T>()?;960 let token = token_id.try_into()?;961 let budget = self962 .recorder963 .weight_calls_budget(<StructureWeight<T>>::find_parent());964965 let balance = balance(self, token, &from)?;966 ensure_single_owner(self, token, balance)?;967968 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)969 .map_err(dispatch_to_evm::<T>)?;970 Ok(())971 }972973 /// @notice Returns next free RFT ID.974 fn next_token_id(&self) -> Result<U256> {975 self.consume_store_reads(1)?;976 Ok(<TokensMinted<T>>::get(self.id)977 .checked_add(1)978 .ok_or("item id overflow")?979 .into())980 }981982 /// @notice Function to mint multiple tokens.983 /// @dev `tokenIds` should be an array of consecutive numbers and first number984 /// should be obtained with `nextTokenId` method985 /// @param to The new owner986 /// @param tokenIds IDs of the minted RFTs987 #[solidity(hide)]988 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]989 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {990 let caller = T::CrossAccountId::from_eth(caller);991 let to = T::CrossAccountId::from_eth(to);992 let mut expected_index = <TokensMinted<T>>::get(self.id)993 .checked_add(1)994 .ok_or("item id overflow")?;995 let budget = self996 .recorder997 .weight_calls_budget(<StructureWeight<T>>::find_parent());998999 let total_tokens = token_ids.len();1000 for id in token_ids.into_iter() {1001 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1002 if id != expected_index {1003 return Err("item id should be next".into());1004 }1005 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1006 }1007 let users = [(to.clone(), 1)]1008 .into_iter()1009 .collect::<BTreeMap<_, _>>()1010 .try_into()1011 .unwrap();1012 let create_item_data = CreateItemData::<T> {1013 users,1014 properties: CollectionPropertiesVec::default(),1015 };1016 let data = (0..total_tokens)1017 .map(|_| create_item_data.clone())1018 .collect();10191020 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1021 .map_err(dispatch_to_evm::<T>)?;1022 Ok(true)1023 }10241025 /// @notice Function to mint multiple tokens with the given tokenUris.1026 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1027 /// numbers and first number should be obtained with `nextTokenId` method1028 /// @param to The new owner1029 /// @param tokens array of pairs of token ID and token URI for minted tokens1030 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1031 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1032 fn mint_bulk_with_token_uri(1033 &mut self,1034 caller: Caller,1035 to: Address,1036 tokens: Vec<TokenUri>,1037 ) -> Result<bool> {1038 let key = key::url();1039 let caller = T::CrossAccountId::from_eth(caller);1040 let to = T::CrossAccountId::from_eth(to);1041 let mut expected_index = <TokensMinted<T>>::get(self.id)1042 .checked_add(1)1043 .ok_or("item id overflow")?;1044 let budget = self1045 .recorder1046 .weight_calls_budget(<StructureWeight<T>>::find_parent());10471048 let mut data = Vec::with_capacity(tokens.len());1049 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]1050 .into_iter()1051 .collect::<BTreeMap<_, _>>()1052 .try_into()1053 .unwrap();1054 for TokenUri { id, uri } in tokens {1055 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1056 if id != expected_index {1057 return Err("item id should be next".into());1058 }1059 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10601061 let mut properties = CollectionPropertiesVec::default();1062 properties1063 .try_push(Property {1064 key: key.clone(),1065 value: uri1066 .into_bytes()1067 .try_into()1068 .map_err(|_| "token uri is too long")?,1069 })1070 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;10711072 let create_item_data = CreateItemData::<T> {1073 users: users.clone(),1074 properties,1075 };1076 data.push(create_item_data);1077 }10781079 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1080 .map_err(dispatch_to_evm::<T>)?;1081 Ok(true)1082 }10831084 /// @notice Function to mint a token.1085 /// @param to The new owner crossAccountId1086 /// @param properties Properties of minted token1087 /// @return uint256 The id of the newly minted token1088 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1089 fn mint_cross(1090 &mut self,1091 caller: Caller,1092 to: eth::CrossAddress,1093 properties: Vec<eth::Property>,1094 ) -> Result<U256> {1095 let token_id = <TokensMinted<T>>::get(self.id)1096 .checked_add(1)1097 .ok_or("item id overflow")?;10981099 let to = to.into_sub_cross_account::<T>()?;11001101 let properties = properties1102 .into_iter()1103 .map(eth::Property::try_into)1104 .collect::<Result<Vec<_>>>()?1105 .try_into()1106 .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;11071108 let caller = T::CrossAccountId::from_eth(caller);11091110 let budget = self1111 .recorder1112 .weight_calls_budget(<StructureWeight<T>>::find_parent());11131114 let users = [(to, 1)]1115 .into_iter()1116 .collect::<BTreeMap<_, _>>()1117 .try_into()1118 .unwrap();1119 <Pallet<T>>::create_item(1120 self,1121 &caller,1122 CreateItemData::<T> { users, properties },1123 &budget,1124 )1125 .map_err(dispatch_to_evm::<T>)?;11261127 Ok(token_id.into())1128 }11291130 /// Returns EVM address for refungible token1131 ///1132 /// @param token ID of the token1133 fn token_contract_address(&self, token: U256) -> Result<Address> {1134 Ok(T::EvmTokenAddressMapping::token_to_address(1135 self.id,1136 token.try_into().map_err(|_| "token id overflow")?,1137 ))1138 }11391140 /// @notice Returns collection helper contract address1141 fn collection_helper_address(&self) -> Result<Address> {1142 Ok(T::ContractAddress::get())1143 }1144}11451146#[solidity_interface(1147 name = UniqueRefungible,1148 is(1149 ERC721,1150 ERC721Enumerable,1151 ERC721UniqueExtensions,1152 ERC721UniqueMintable,1153 ERC721Burnable,1154 ERC721Metadata(if(this.flags.erc721metadata)),1155 Collection(via(common_mut returns CollectionHandle<T>)),1156 TokenProperties,1157 ),1158 enum(derive(PreDispatch)),1159)]1160impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11611162// Not a tests, but code generators1163generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1164generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);11651166impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1167where1168 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1169{1170 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1171 fn call(1172 self,1173 handle: &mut impl PrecompileHandle,1174 ) -> Option<pallet_common::erc::PrecompileResult> {1175 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1176 }1177}1// 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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26 char::{REPLACEMENT_CHARACTER, decode_utf16},27 convert::TryInto,28};29use evm_coder::{abi::AbiType, ToLog, generate_stubgen, solidity_interface, types::*};30use frame_support::{BoundedBTreeMap, BoundedVec};31use pallet_common::{32 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,33 Error as CommonError,34 erc::{CommonEvmHandler, CollectionCall, static_property::key},35 eth::{self, TokenUri},36};37use pallet_evm::{account::CrossAccountId, PrecompileHandle};38use pallet_evm_coder_substrate::{39 call, dispatch_to_evm,40 execution::{PreDispatch, Result, Error},41 frontier_contract,42};43use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};44use sp_core::{H160, U256, Get};45use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};46use up_data_structs::{47 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,48 PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,49};5051use crate::{52 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, TokenProperties,53 TokensMinted, TotalSupply, SelfWeightOf, weights::WeightInfo,54};5556frontier_contract! {57 macro_rules! RefungibleHandle_result {...}58 impl<T: Config> Contract for RefungibleHandle<T> {...}59}6061pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);6263/// Rft events.64#[derive(ToLog)]65pub enum ERC721TokenEvent {66 /// The token has been changed.67 TokenChanged {68 /// Token ID.69 #[indexed]70 token_id: U256,71 },72}7374/// @title A contract that allows to set and delete token properties and change token property permissions.75#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]76impl<T: Config> RefungibleHandle<T> {77 /// @notice Set permissions for token property.78 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.79 /// @param key Property key.80 /// @param isMutable Permission to mutate property.81 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.82 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.83 #[solidity(hide)]84 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]85 fn set_token_property_permission(86 &mut self,87 caller: Caller,88 key: String,89 is_mutable: bool,90 collection_admin: bool,91 token_owner: bool,92 ) -> Result<()> {93 let caller = T::CrossAccountId::from_eth(caller);94 <Pallet<T>>::set_token_property_permissions(95 self,96 &caller,97 vec![PropertyKeyPermission {98 key: <Vec<u8>>::from(key)99 .try_into()100 .map_err(|_| "too long key")?,101 permission: PropertyPermission {102 mutable: is_mutable,103 collection_admin,104 token_owner,105 },106 }],107 )108 .map_err(dispatch_to_evm::<T>)109 }110111 /// @notice Set permissions for token property.112 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.113 /// @param permissions Permissions for keys.114 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]115 fn set_token_property_permissions(116 &mut self,117 caller: Caller,118 permissions: Vec<eth::TokenPropertyPermission>,119 ) -> Result<()> {120 let caller = T::CrossAccountId::from_eth(caller);121 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;122123 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)124 .map_err(dispatch_to_evm::<T>)125 }126127 /// @notice Get permissions for token properties.128 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {129 let perms = <Pallet<T>>::token_property_permission(self.id);130 Ok(perms131 .into_iter()132 .map(eth::TokenPropertyPermission::from)133 .collect())134 }135136 /// @notice Set token property value.137 /// @dev Throws error if `msg.sender` has no permission to edit the property.138 /// @param tokenId ID of the token.139 /// @param key Property key.140 /// @param value Property value.141 #[solidity(hide)]142 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]143 fn set_property(144 &mut self,145 caller: Caller,146 token_id: U256,147 key: String,148 value: Bytes,149 ) -> Result<()> {150 let caller = T::CrossAccountId::from_eth(caller);151 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;152 let key = <Vec<u8>>::from(key)153 .try_into()154 .map_err(|_| "key too long")?;155 let value = value.0.try_into().map_err(|_| "value too long")?;156157 let nesting_budget = self158 .recorder159 .weight_calls_budget(<StructureWeight<T>>::find_parent());160161 <Pallet<T>>::set_token_property(162 self,163 &caller,164 TokenId(token_id),165 Property { key, value },166 &nesting_budget,167 )168 .map_err(dispatch_to_evm::<T>)169 }170171 /// @notice Set token properties value.172 /// @dev Throws error if `msg.sender` has no permission to edit the property.173 /// @param tokenId ID of the token.174 /// @param properties settable properties175 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]176 fn set_properties(177 &mut self,178 caller: Caller,179 token_id: U256,180 properties: Vec<eth::Property>,181 ) -> Result<()> {182 let caller = T::CrossAccountId::from_eth(caller);183 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;184185 let nesting_budget = self186 .recorder187 .weight_calls_budget(<StructureWeight<T>>::find_parent());188189 let properties = properties190 .into_iter()191 .map(eth::Property::try_into)192 .collect::<Result<Vec<_>>>()?;193194 <Pallet<T>>::set_token_properties(195 self,196 &caller,197 TokenId(token_id),198 properties.into_iter(),199 false,200 &nesting_budget,201 )202 .map_err(dispatch_to_evm::<T>)203 }204205 /// @notice Delete token property value.206 /// @dev Throws error if `msg.sender` has no permission to edit the property.207 /// @param tokenId ID of the token.208 /// @param key Property key.209 #[solidity(hide)]210 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]211 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {212 let caller = T::CrossAccountId::from_eth(caller);213 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;214 let key = <Vec<u8>>::from(key)215 .try_into()216 .map_err(|_| "key too long")?;217218 let nesting_budget = self219 .recorder220 .weight_calls_budget(<StructureWeight<T>>::find_parent());221222 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)223 .map_err(dispatch_to_evm::<T>)224 }225226 /// @notice Delete token properties value.227 /// @dev Throws error if `msg.sender` has no permission to edit the property.228 /// @param tokenId ID of the token.229 /// @param keys Properties key.230 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]231 fn delete_properties(232 &mut self,233 token_id: U256,234 caller: Caller,235 keys: Vec<String>,236 ) -> Result<()> {237 let caller = T::CrossAccountId::from_eth(caller);238 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;239 let keys = keys240 .into_iter()241 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))242 .collect::<Result<Vec<_>>>()?;243244 let nesting_budget = self245 .recorder246 .weight_calls_budget(<StructureWeight<T>>::find_parent());247248 <Pallet<T>>::delete_token_properties(249 self,250 &caller,251 TokenId(token_id),252 keys.into_iter(),253 &nesting_budget,254 )255 .map_err(dispatch_to_evm::<T>)256 }257258 /// @notice Get token property value.259 /// @dev Throws error if key not found260 /// @param tokenId ID of the token.261 /// @param key Property key.262 /// @return Property value bytes263 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {264 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;265 let key = <Vec<u8>>::from(key)266 .try_into()267 .map_err(|_| "key too long")?;268269 let props = <TokenProperties<T>>::get((self.id, token_id));270 let prop = props.get(&key).ok_or("key not found")?;271272 Ok(prop.to_vec().into())273 }274}275276#[derive(ToLog)]277pub enum ERC721Events {278 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed279 /// (`to` == 0). Exception: during contract creation, any number of RFTs280 /// may be created and assigned without emitting Transfer.281 Transfer {282 #[indexed]283 from: Address,284 #[indexed]285 to: Address,286 #[indexed]287 token_id: U256,288 },289 /// @dev Not supported290 Approval {291 #[indexed]292 owner: Address,293 #[indexed]294 approved: Address,295 #[indexed]296 token_id: U256,297 },298 /// @dev Not supported299 #[allow(dead_code)]300 ApprovalForAll {301 #[indexed]302 owner: Address,303 #[indexed]304 operator: Address,305 approved: bool,306 },307}308309/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension310/// @dev See https://eips.ethereum.org/EIPS/eip-721311#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]312impl<T: Config> RefungibleHandle<T>313where314 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,315{316 /// @notice A descriptive name for a collection of NFTs in this contract317 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`318 #[solidity(hide, rename_selector = "name")]319 fn name_proxy(&self) -> Result<String> {320 self.name()321 }322323 /// @notice An abbreviated name for NFTs in this contract324 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`325 #[solidity(hide, rename_selector = "symbol")]326 fn symbol_proxy(&self) -> Result<String> {327 self.symbol()328 }329330 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.331 ///332 /// @dev If the token has a `url` property and it is not empty, it is returned.333 /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.334 /// If the collection property `baseURI` is empty or absent, return "" (empty string)335 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix336 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).337 ///338 /// @return token's const_metadata339 #[solidity(rename_selector = "tokenURI")]340 fn token_uri(&self, token_id: U256) -> Result<String> {341 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;342343 match get_token_property(self, token_id_u32, &key::url()).as_deref() {344 Err(_) | Ok("") => (),345 Ok(url) => {346 return Ok(url.into());347 }348 };349350 let base_uri =351 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())352 .map(BoundedVec::into_inner)353 .map(String::from_utf8)354 .transpose()355 .map_err(|e| {356 Error::Revert(alloc::format!(357 "Can not convert value \"baseURI\" to string with error \"{e}\""358 ))359 })?;360361 let base_uri = match base_uri.as_deref() {362 None | Some("") => {363 return Ok("".into());364 }365 Some(base_uri) => base_uri.into(),366 };367368 Ok(369 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {370 Err(_) | Ok("") => base_uri,371 Ok(suffix) => base_uri + suffix,372 },373 )374 }375}376377/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension378/// @dev See https://eips.ethereum.org/EIPS/eip-721379#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]380impl<T: Config> RefungibleHandle<T> {381 /// @notice Enumerate valid RFTs382 /// @param index A counter less than `totalSupply()`383 /// @return The token identifier for the `index`th NFT,384 /// (sort order not specified)385 fn token_by_index(&self, index: U256) -> U256 {386 index387 }388389 /// Not implemented390 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {391 // TODO: Not implemetable392 Err("not implemented".into())393 }394395 /// @notice Count RFTs tracked by this contract396 /// @return A count of valid RFTs tracked by this contract, where each one of397 /// them has an assigned and queryable owner not equal to the zero address398 fn total_supply(&self) -> Result<U256> {399 self.consume_store_reads(1)?;400 Ok(<Pallet<T>>::total_supply(self).into())401 }402}403404/// @title ERC-721 Non-Fungible Token Standard405/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md406#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]407impl<T: Config> RefungibleHandle<T> {408 /// @notice Count all RFTs assigned to an owner409 /// @dev RFTs assigned to the zero address are considered invalid, and this410 /// function throws for queries about the zero address.411 /// @param owner An address for whom to query the balance412 /// @return The number of RFTs owned by `owner`, possibly zero413 fn balance_of(&self, owner: Address) -> Result<U256> {414 self.consume_store_reads(1)?;415 let owner = T::CrossAccountId::from_eth(owner);416 let balance = <AccountBalance<T>>::get((self.id, owner));417 Ok(balance.into())418 }419420 /// @notice Find the owner of an RFT421 /// @dev RFTs assigned to zero address are considered invalid, and queries422 /// about them do throw.423 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for424 /// the tokens that are partially owned.425 /// @param tokenId The identifier for an RFT426 /// @return The address of the owner of the RFT427 fn owner_of(&self, token_id: U256) -> Result<Address> {428 self.consume_store_reads(2)?;429 let token = token_id.try_into()?;430 let owner = <Pallet<T>>::token_owner(self.id, token);431 owner432 .map(|address| *address.as_eth())433 .or_else(|err| match err {434 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),435 TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),436 })437 }438439 /// @dev Not implemented440 #[solidity(rename_selector = "safeTransferFrom")]441 fn safe_transfer_from_with_data(442 &mut self,443 _from: Address,444 _to: Address,445 _token_id: U256,446 _data: Bytes,447 ) -> Result<()> {448 // TODO: Not implemetable449 Err("not implemented".into())450 }451452 /// @dev Not implemented453 #[solidity(rename_selector = "safeTransferFrom")]454 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {455 // TODO: Not implemetable456 Err("not implemented".into())457 }458459 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE460 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE461 /// THEY MAY BE PERMANENTLY LOST462 /// @dev Throws unless `msg.sender` is the current owner or an authorized463 /// operator for this RFT. Throws if `from` is not the current owner. Throws464 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.465 /// Throws if RFT pieces have multiple owners.466 /// @param from The current owner of the NFT467 /// @param to The new owner468 /// @param tokenId The NFT to transfer469 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]470 fn transfer_from(471 &mut self,472 caller: Caller,473 from: Address,474 to: Address,475 token_id: U256,476 ) -> Result<()> {477 let caller = T::CrossAccountId::from_eth(caller);478 let from = T::CrossAccountId::from_eth(from);479 let to = T::CrossAccountId::from_eth(to);480 let token = token_id.try_into()?;481 let budget = self482 .recorder483 .weight_calls_budget(<StructureWeight<T>>::find_parent());484485 let balance = balance(self, token, &from)?;486 ensure_single_owner(self, token, balance)?;487488 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)489 .map_err(dispatch_to_evm::<T>)?;490491 Ok(())492 }493494 /// @dev Not implemented495 fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {496 Err("not implemented".into())497 }498499 /// @notice Sets or unsets the approval of a given operator.500 /// The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.501 /// @param operator Operator502 /// @param approved Should operator status be granted or revoked?503 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]504 fn set_approval_for_all(505 &mut self,506 caller: Caller,507 operator: Address,508 approved: bool,509 ) -> Result<()> {510 let caller = T::CrossAccountId::from_eth(caller);511 let operator = T::CrossAccountId::from_eth(operator);512513 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)514 .map_err(dispatch_to_evm::<T>)?;515 Ok(())516 }517518 /// @dev Not implemented519 fn get_approved(&self, _token_id: U256) -> Result<Address> {520 // TODO: Not implemetable521 Err("not implemented".into())522 }523524 /// @notice Tells whether the given `owner` approves the `operator`.525 #[weight(<SelfWeightOf<T>>::allowance_for_all())]526 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {527 let owner = T::CrossAccountId::from_eth(owner);528 let operator = T::CrossAccountId::from_eth(operator);529530 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))531 }532}533534/// Returns amount of pieces of `token` that `owner` have535pub fn balance<T: Config>(536 collection: &RefungibleHandle<T>,537 token: TokenId,538 owner: &T::CrossAccountId,539) -> Result<u128> {540 collection.consume_store_reads(1)?;541 let balance = <Balance<T>>::get((collection.id, token, &owner));542 Ok(balance)543}544545/// Throws if `owner_balance` is lower than total amount of `token` pieces546pub fn ensure_single_owner<T: Config>(547 collection: &RefungibleHandle<T>,548 token: TokenId,549 owner_balance: u128,550) -> Result<()> {551 collection.consume_store_reads(1)?;552 let total_supply = <TotalSupply<T>>::get((collection.id, token));553554 if owner_balance == 0 {555 return Err(dispatch_to_evm::<T>(556 <CommonError<T>>::MustBeTokenOwner.into(),557 ));558 }559560 if total_supply != owner_balance {561 return Err("token has multiple owners".into());562 }563 Ok(())564}565566/// @title ERC721 Token that can be irreversibly burned (destroyed).567#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]568impl<T: Config> RefungibleHandle<T> {569 /// @notice Burns a specific ERC721 token.570 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized571 /// operator of the current owner.572 /// @param tokenId The RFT to approve573 #[weight(<SelfWeightOf<T>>::burn_item_fully())]574 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {575 let caller = T::CrossAccountId::from_eth(caller);576 let token = token_id.try_into()?;577578 let balance = balance(self, token, &caller)?;579 ensure_single_owner(self, token, balance)?;580581 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;582 Ok(())583 }584}585586/// @title ERC721 minting logic.587#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]588impl<T: Config> RefungibleHandle<T> {589 /// @notice Function to mint a token.590 /// @param to The new owner591 /// @return uint256 The id of the newly minted token592 #[weight(<SelfWeightOf<T>>::create_item())]593 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {594 let token_id: U256 = <TokensMinted<T>>::get(self.id)595 .checked_add(1)596 .ok_or("item id overflow")?597 .into();598 self.mint_check_id(caller, to, token_id)?;599 Ok(token_id)600 }601602 /// @notice Function to mint a token.603 /// @dev `tokenId` should be obtained with `nextTokenId` method,604 /// unlike standard, you can't specify it manually605 /// @param to The new owner606 /// @param tokenId ID of the minted RFT607 #[solidity(hide, rename_selector = "mint")]608 #[weight(<SelfWeightOf<T>>::create_item())]609 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {610 let caller = T::CrossAccountId::from_eth(caller);611 let to = T::CrossAccountId::from_eth(to);612 let token_id: u32 = token_id.try_into()?;613 let budget = self614 .recorder615 .weight_calls_budget(<StructureWeight<T>>::find_parent());616617 if <TokensMinted<T>>::get(self.id)618 .checked_add(1)619 .ok_or("item id overflow")?620 != token_id621 {622 return Err("item id should be next".into());623 }624625 let users = [(to, 1)]626 .into_iter()627 .collect::<BTreeMap<_, _>>()628 .try_into()629 .unwrap();630 <Pallet<T>>::create_item(631 self,632 &caller,633 CreateItemData::<T> {634 users,635 properties: CollectionPropertiesVec::default(),636 },637 &budget,638 )639 .map_err(dispatch_to_evm::<T>)?;640641 Ok(true)642 }643644 /// @notice Function to mint token with the given tokenUri.645 /// @param to The new owner646 /// @param tokenUri Token URI that would be stored in the NFT properties647 /// @return uint256 The id of the newly minted token648 #[solidity(rename_selector = "mintWithTokenURI")]649 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]650 fn mint_with_token_uri(651 &mut self,652 caller: Caller,653 to: Address,654 token_uri: String,655 ) -> Result<U256> {656 let token_id: U256 = <TokensMinted<T>>::get(self.id)657 .checked_add(1)658 .ok_or("item id overflow")?659 .into();660 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;661 Ok(token_id)662 }663664 /// @notice Function to mint token with the given tokenUri.665 /// @dev `tokenId` should be obtained with `nextTokenId` method,666 /// unlike standard, you can't specify it manually667 /// @param to The new owner668 /// @param tokenId ID of the minted RFT669 /// @param tokenUri Token URI that would be stored in the RFT properties670 #[solidity(hide, rename_selector = "mintWithTokenURI")]671 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]672 fn mint_with_token_uri_check_id(673 &mut self,674 caller: Caller,675 to: Address,676 token_id: U256,677 token_uri: String,678 ) -> Result<bool> {679 let key = key::url();680 let permission = get_token_permission::<T>(self.id, &key)?;681 if !permission.collection_admin {682 return Err("Operation is not allowed".into());683 }684685 let caller = T::CrossAccountId::from_eth(caller);686 let to = T::CrossAccountId::from_eth(to);687 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;688 let budget = self689 .recorder690 .weight_calls_budget(<StructureWeight<T>>::find_parent());691692 if <TokensMinted<T>>::get(self.id)693 .checked_add(1)694 .ok_or("item id overflow")?695 != token_id696 {697 return Err("item id should be next".into());698 }699700 let mut properties = CollectionPropertiesVec::default();701 properties702 .try_push(Property {703 key,704 value: token_uri705 .into_bytes()706 .try_into()707 .map_err(|_| "token uri is too long")?,708 })709 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;710711 let users = [(to, 1)]712 .into_iter()713 .collect::<BTreeMap<_, _>>()714 .try_into()715 .unwrap();716 <Pallet<T>>::create_item(717 self,718 &caller,719 CreateItemData::<T> { users, properties },720 &budget,721 )722 .map_err(dispatch_to_evm::<T>)?;723 Ok(true)724 }725}726727fn get_token_property<T: Config>(728 collection: &CollectionHandle<T>,729 token_id: u32,730 key: &up_data_structs::PropertyKey,731) -> Result<String> {732 collection.consume_store_reads(1)?;733 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))734 .map_err(|_| Error::Revert("Token properties not found".into()))?;735 if let Some(property) = properties.get(key) {736 return Ok(String::from_utf8_lossy(property).into());737 }738739 Err("Property tokenURI not found".into())740}741742fn get_token_permission<T: Config>(743 collection_id: CollectionId,744 key: &PropertyKey,745) -> Result<PropertyPermission> {746 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)747 .map_err(|_| Error::Revert("No permissions for collection".into()))?;748 let a = token_property_permissions749 .get(key)750 .map(Clone::clone)751 .ok_or_else(|| {752 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();753 Error::Revert(alloc::format!("No permission for key {key}"))754 })?;755 Ok(a)756}757758/// @title Unique extensions for ERC721.759#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]760impl<T: Config> RefungibleHandle<T>761where762 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,763{764 /// @notice A descriptive name for a collection of NFTs in this contract765 fn name(&self) -> Result<String> {766 Ok(decode_utf16(self.name.iter().copied())767 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))768 .collect::<String>())769 }770771 /// @notice An abbreviated name for NFTs in this contract772 fn symbol(&self) -> Result<String> {773 Ok(String::from_utf8_lossy(&self.token_prefix).into())774 }775776 /// @notice A description for the collection.777 fn description(&self) -> Result<String> {778 Ok(decode_utf16(self.description.iter().copied())779 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))780 .collect::<String>())781 }782783 /// Returns the owner (in cross format) of the token.784 ///785 /// @param tokenId Id for the token.786 #[solidity(hide)]787 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {788 Self::owner_of_cross(self, token_id)789 }790791 /// Returns the owner (in cross format) of the token.792 ///793 /// @param tokenId Id for the token.794 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {795 Self::token_owner(self, token_id.try_into()?)796 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))797 .or_else(|err| match err {798 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),799 TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(800 ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,801 )),802 })803 }804805 /// @notice Count all RFTs assigned to an owner806 /// @param owner An cross address for whom to query the balance807 /// @return The number of RFTs owned by `owner`, possibly zero808 fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {809 self.consume_store_reads(1)?;810 let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));811 Ok(balance.into())812 }813814 /// Returns the token properties.815 ///816 /// @param tokenId Id for the token.817 /// @param keys Properties keys. Empty keys for all propertyes.818 /// @return Vector of properties key/value pairs.819 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {820 let keys = keys821 .into_iter()822 .map(|key| {823 <Vec<u8>>::from(key)824 .try_into()825 .map_err(|_| Error::Revert("key too large".into()))826 })827 .collect::<Result<Vec<_>>>()?;828829 <Self as CommonCollectionOperations<T>>::token_properties(830 self,831 token_id.try_into()?,832 if keys.is_empty() { None } else { Some(keys) },833 )834 .into_iter()835 .map(eth::Property::try_from)836 .collect::<Result<Vec<_>>>()837 }838 /// @notice Transfer ownership of an RFT839 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`840 /// is the zero address. Throws if `tokenId` is not a valid RFT.841 /// Throws if RFT pieces have multiple owners.842 /// @param to The new owner843 /// @param tokenId The RFT to transfer844 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]845 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {846 let caller = T::CrossAccountId::from_eth(caller);847 let to = T::CrossAccountId::from_eth(to);848 let token = token_id.try_into()?;849 let budget = self850 .recorder851 .weight_calls_budget(<StructureWeight<T>>::find_parent());852853 let balance = balance(self, token, &caller)?;854 ensure_single_owner(self, token, balance)?;855856 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)857 .map_err(dispatch_to_evm::<T>)?;858 Ok(())859 }860861 /// @notice Transfer ownership of an RFT862 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`863 /// is the zero address. Throws if `tokenId` is not a valid RFT.864 /// Throws if RFT pieces have multiple owners.865 /// @param to The new owner866 /// @param tokenId The RFT to transfer867 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]868 fn transfer_cross(869 &mut self,870 caller: Caller,871 to: eth::CrossAddress,872 token_id: U256,873 ) -> Result<()> {874 let caller = T::CrossAccountId::from_eth(caller);875 let to = to.into_sub_cross_account::<T>()?;876 let token = token_id.try_into()?;877 let budget = self878 .recorder879 .weight_calls_budget(<StructureWeight<T>>::find_parent());880881 let balance = balance(self, token, &caller)?;882 ensure_single_owner(self, token, balance)?;883884 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)885 .map_err(dispatch_to_evm::<T>)?;886 Ok(())887 }888889 /// @notice Transfer ownership of an RFT890 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`891 /// is the zero address. Throws if `tokenId` is not a valid RFT.892 /// Throws if RFT pieces have multiple owners.893 /// @param to The new owner894 /// @param tokenId The RFT to transfer895 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]896 fn transfer_from_cross(897 &mut self,898 caller: Caller,899 from: eth::CrossAddress,900 to: eth::CrossAddress,901 token_id: U256,902 ) -> Result<()> {903 let caller = T::CrossAccountId::from_eth(caller);904 let from = from.into_sub_cross_account::<T>()?;905 let to = to.into_sub_cross_account::<T>()?;906 let token_id = token_id.try_into()?;907 let budget = self908 .recorder909 .weight_calls_budget(<StructureWeight<T>>::find_parent());910911 let balance = balance(self, token_id, &from)?;912 ensure_single_owner(self, token_id, balance)?;913914 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)915 .map_err(dispatch_to_evm::<T>)?;916 Ok(())917 }918919 /// @notice Burns a specific ERC721 token.920 /// @dev Throws unless `msg.sender` is the current owner or an authorized921 /// operator for this RFT. Throws if `from` is not the current owner. Throws922 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.923 /// Throws if RFT pieces have multiple owners.924 /// @param from The current owner of the RFT925 /// @param tokenId The RFT to transfer926 #[solidity(hide)]927 #[weight(<SelfWeightOf<T>>::burn_from())]928 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {929 let caller = T::CrossAccountId::from_eth(caller);930 let from = T::CrossAccountId::from_eth(from);931 let token = token_id.try_into()?;932 let budget = self933 .recorder934 .weight_calls_budget(<StructureWeight<T>>::find_parent());935936 let balance = balance(self, token, &from)?;937 ensure_single_owner(self, token, balance)?;938939 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)940 .map_err(dispatch_to_evm::<T>)?;941 Ok(())942 }943944 /// @notice Burns a specific ERC721 token.945 /// @dev Throws unless `msg.sender` is the current owner or an authorized946 /// operator for this RFT. Throws if `from` is not the current owner. Throws947 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.948 /// Throws if RFT pieces have multiple owners.949 /// @param from The current owner of the RFT950 /// @param tokenId The RFT to transfer951 #[weight(<SelfWeightOf<T>>::burn_from())]952 fn burn_from_cross(953 &mut self,954 caller: Caller,955 from: eth::CrossAddress,956 token_id: U256,957 ) -> Result<()> {958 let caller = T::CrossAccountId::from_eth(caller);959 let from = from.into_sub_cross_account::<T>()?;960 let token = token_id.try_into()?;961 let budget = self962 .recorder963 .weight_calls_budget(<StructureWeight<T>>::find_parent());964965 let balance = balance(self, token, &from)?;966 ensure_single_owner(self, token, balance)?;967968 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)969 .map_err(dispatch_to_evm::<T>)?;970 Ok(())971 }972973 /// @notice Returns next free RFT ID.974 fn next_token_id(&self) -> Result<U256> {975 self.consume_store_reads(1)?;976 Ok(<TokensMinted<T>>::get(self.id)977 .checked_add(1)978 .ok_or("item id overflow")?979 .into())980 }981982 /// @notice Function to mint multiple tokens.983 /// @dev `tokenIds` should be an array of consecutive numbers and first number984 /// should be obtained with `nextTokenId` method985 /// @param to The new owner986 /// @param tokenIds IDs of the minted RFTs987 #[solidity(hide)]988 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]989 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {990 let caller = T::CrossAccountId::from_eth(caller);991 let to = T::CrossAccountId::from_eth(to);992 let mut expected_index = <TokensMinted<T>>::get(self.id)993 .checked_add(1)994 .ok_or("item id overflow")?;995 let budget = self996 .recorder997 .weight_calls_budget(<StructureWeight<T>>::find_parent());998999 let total_tokens = token_ids.len();1000 for id in token_ids.into_iter() {1001 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1002 if id != expected_index {1003 return Err("item id should be next".into());1004 }1005 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1006 }1007 let users = [(to, 1)]1008 .into_iter()1009 .collect::<BTreeMap<_, _>>()1010 .try_into()1011 .unwrap();1012 let create_item_data = CreateItemData::<T> {1013 users,1014 properties: CollectionPropertiesVec::default(),1015 };1016 let data = (0..total_tokens)1017 .map(|_| create_item_data.clone())1018 .collect();10191020 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1021 .map_err(dispatch_to_evm::<T>)?;1022 Ok(true)1023 }10241025 /// @notice Function to mint multiple tokens with the given tokenUris.1026 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1027 /// numbers and first number should be obtained with `nextTokenId` method1028 /// @param to The new owner1029 /// @param tokens array of pairs of token ID and token URI for minted tokens1030 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1031 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1032 fn mint_bulk_with_token_uri(1033 &mut self,1034 caller: Caller,1035 to: Address,1036 tokens: Vec<TokenUri>,1037 ) -> Result<bool> {1038 let key = key::url();1039 let caller = T::CrossAccountId::from_eth(caller);1040 let to = T::CrossAccountId::from_eth(to);1041 let mut expected_index = <TokensMinted<T>>::get(self.id)1042 .checked_add(1)1043 .ok_or("item id overflow")?;1044 let budget = self1045 .recorder1046 .weight_calls_budget(<StructureWeight<T>>::find_parent());10471048 let mut data = Vec::with_capacity(tokens.len());1049 let users: BoundedBTreeMap<_, _, _> = [(to, 1)]1050 .into_iter()1051 .collect::<BTreeMap<_, _>>()1052 .try_into()1053 .unwrap();1054 for TokenUri { id, uri } in tokens {1055 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1056 if id != expected_index {1057 return Err("item id should be next".into());1058 }1059 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10601061 let mut properties = CollectionPropertiesVec::default();1062 properties1063 .try_push(Property {1064 key: key.clone(),1065 value: uri1066 .into_bytes()1067 .try_into()1068 .map_err(|_| "token uri is too long")?,1069 })1070 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;10711072 let create_item_data = CreateItemData::<T> {1073 users: users.clone(),1074 properties,1075 };1076 data.push(create_item_data);1077 }10781079 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1080 .map_err(dispatch_to_evm::<T>)?;1081 Ok(true)1082 }10831084 /// @notice Function to mint a token.1085 /// @param to The new owner crossAccountId1086 /// @param properties Properties of minted token1087 /// @return uint256 The id of the newly minted token1088 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1089 fn mint_cross(1090 &mut self,1091 caller: Caller,1092 to: eth::CrossAddress,1093 properties: Vec<eth::Property>,1094 ) -> Result<U256> {1095 let token_id = <TokensMinted<T>>::get(self.id)1096 .checked_add(1)1097 .ok_or("item id overflow")?;10981099 let to = to.into_sub_cross_account::<T>()?;11001101 let properties = properties1102 .into_iter()1103 .map(eth::Property::try_into)1104 .collect::<Result<Vec<_>>>()?1105 .try_into()1106 .map_err(|_| Error::Revert("too many properties".to_string()))?;11071108 let caller = T::CrossAccountId::from_eth(caller);11091110 let budget = self1111 .recorder1112 .weight_calls_budget(<StructureWeight<T>>::find_parent());11131114 let users = [(to, 1)]1115 .into_iter()1116 .collect::<BTreeMap<_, _>>()1117 .try_into()1118 .unwrap();1119 <Pallet<T>>::create_item(1120 self,1121 &caller,1122 CreateItemData::<T> { users, properties },1123 &budget,1124 )1125 .map_err(dispatch_to_evm::<T>)?;11261127 Ok(token_id.into())1128 }11291130 /// Returns EVM address for refungible token1131 ///1132 /// @param token ID of the token1133 fn token_contract_address(&self, token: U256) -> Result<Address> {1134 Ok(T::EvmTokenAddressMapping::token_to_address(1135 self.id,1136 token.try_into().map_err(|_| "token id overflow")?,1137 ))1138 }11391140 /// @notice Returns collection helper contract address1141 fn collection_helper_address(&self) -> Result<Address> {1142 Ok(T::ContractAddress::get())1143 }1144}11451146#[solidity_interface(1147 name = UniqueRefungible,1148 is(1149 ERC721,1150 ERC721Enumerable,1151 ERC721UniqueExtensions,1152 ERC721UniqueMintable,1153 ERC721Burnable,1154 ERC721Metadata(if(this.flags.erc721metadata)),1155 Collection(via(common_mut returns CollectionHandle<T>)),1156 TokenProperties,1157 ),1158 enum(derive(PreDispatch)),1159)]1160impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11611162// Not a tests, but code generators1163generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1164generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);11651166impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1167where1168 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1169{1170 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1171 fn call(1172 self,1173 handle: &mut impl PrecompileHandle,1174 ) -> Option<pallet_common::erc::PrecompileResult> {1175 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1176 }1177}pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1124,7 +1124,7 @@
if collection.ignores_token_restrictions(spender) {
return Ok(Self::compute_allowance_decrease(
- collection, token, from, &spender, amount,
+ collection, token, from, spender, amount,
));
}
@@ -1143,7 +1143,7 @@
return Ok(None);
}
- let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);
+ let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);
if allowance.is_some() {
return Ok(allowance);
}
pallets/scheduler-v2/src/lib.rsdiffbeforeafterboth--- a/pallets/scheduler-v2/src/lib.rs
+++ b/pallets/scheduler-v2/src/lib.rs
@@ -969,7 +969,7 @@
call: ScheduledCall<T>,
) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
// ensure id it is unique
- if Lookup::<T>::contains_key(&id) {
+ if Lookup::<T>::contains_key(id) {
return Err(Error::<T>::FailedToSchedule.into());
}
pallets/structure/src/lib.rsdiffbeforeafterboth--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -280,7 +280,7 @@
) -> DispatchResultWithPostInfo {
let dispatch = T::CollectionDispatch::dispatch(collection)?;
let dispatch = dispatch.as_dyn();
- dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)
+ dispatch.burn_item_recursively(from, token, self_budget, breadth_budget)
}
/// Check if `token` indirectly owned by `user`
@@ -396,7 +396,7 @@
account: &T::CrossAccountId,
action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,
) -> DispatchResult {
- if is_collection(&account.as_eth()) {
+ if is_collection(account.as_eth()) {
fail!(<Error<T>>::CantNestTokenUnderCollection);
}
let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account) else {
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -113,13 +113,9 @@
let collection_helpers_address =
T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
- let collection_id = T::CollectionDispatch::create(
- caller.clone(),
- collection_helpers_address,
- data,
- Default::default(),
- )
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ let collection_id =
+ T::CollectionDispatch::create(caller, collection_helpers_address, data, Default::default())
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
Ok(address)
}
@@ -132,8 +128,7 @@
.expect("Collection creation price should be convertible to u128");
if value != creation_price {
return Err(format!(
- "Sent amount not equals to collection creation price ({0})",
- creation_price
+ "Sent amount not equals to collection creation price ({creation_price})",
)
.into());
}
@@ -383,8 +378,7 @@
map_eth_to_id(&collection_address)
.map(|id| id.0)
.ok_or(Error::Revert(format!(
- "failed to convert address {} into collectionId.",
- collection_address
+ "failed to convert address {collection_address} into collectionId."
)))
}
}
@@ -422,5 +416,5 @@
generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);
fn error_field_too_long(feild: &str, bound: usize) -> Error {
- Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))
+ Error::Revert(format!("{feild} is too long. Max length is {bound}."))
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -507,7 +507,7 @@
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let new_owner = T::CrossAccountId::from_sub(new_owner);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.change_owner(sender, new_owner.clone())
+ target_collection.change_owner(sender, new_owner)
}
/// Add an admin to a collection.
@@ -667,7 +667,7 @@
/// * `owner`: Address of the initial owner of the item.
/// * `data`: Token data describing the item to store on chain.
#[pallet::call_index(11)]
- #[pallet::weight(T::CommonWeightInfo::create_item(&data))]
+ #[pallet::weight(T::CommonWeightInfo::create_item(data))]
pub fn create_item(
origin: OriginFor<T>,
collection_id: CollectionId,
@@ -701,7 +701,7 @@
/// * `owner`: Address of the initial owner of the tokens.
/// * `items_data`: Vector of data describing each item to be created.
#[pallet::call_index(12)]
- #[pallet::weight(T::CommonWeightInfo::create_multiple_items(&items_data))]
+ #[pallet::weight(T::CommonWeightInfo::create_multiple_items(items_data))]
pub fn create_multiple_items(
origin: OriginFor<T>,
collection_id: CollectionId,
@@ -889,7 +889,7 @@
/// * `collection_id`: ID of the collection to which the tokens would belong.
/// * `data`: Explicit item creation data.
#[pallet::call_index(18)]
- #[pallet::weight(T::CommonWeightInfo::create_multiple_items_ex(&data))]
+ #[pallet::weight(T::CommonWeightInfo::create_multiple_items_ex(data))]
pub fn create_multiple_items_ex(
origin: OriginFor<T>,
collection_id: CollectionId,
@@ -1313,7 +1313,7 @@
collection_id: CollectionId,
) -> DispatchResult {
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- target_collection.force_set_sponsor(sponsor.clone())
+ target_collection.force_set_sponsor(sponsor)
}
/// Force remove `sponsor` for `collection`.
primitives/data-structs/src/bounded.rsdiffbeforeafterboth--- a/primitives/data-structs/src/bounded.rs
+++ b/primitives/data-structs/src/bounded.rs
@@ -63,7 +63,7 @@
V: fmt::Debug,
{
use core::fmt::Debug;
- (&v as &Vec<V>).fmt(f)
+ (v as &Vec<V>).fmt(f)
}
#[cfg(feature = "serde1")]
@@ -114,7 +114,7 @@
V: fmt::Debug,
{
use core::fmt::Debug;
- (&v as &BTreeMap<K, V>).fmt(f)
+ (v as &BTreeMap<K, V>).fmt(f)
}
#[cfg(feature = "serde1")]
@@ -157,5 +157,5 @@
K: fmt::Debug + Ord,
{
use core::fmt::Debug;
- (&v as &BTreeSet<K>).fmt(f)
+ (v as &BTreeSet<K>).fmt(f)
}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -536,7 +536,7 @@
type Target = Vec<u8>;
fn deref(&self) -> &Self::Target {
- return &self.0;
+ &self.0
}
}
@@ -816,6 +816,11 @@
Self(Default::default())
}
}
+impl Default for OwnerRestrictedSet {
+ fn default() -> Self {
+ Self::new()
+ }
+}
impl core::ops::Deref for OwnerRestrictedSet {
type Target = OwnerRestrictedSetInner;
fn deref(&self) -> &Self::Target {
@@ -1098,9 +1103,9 @@
pub value: PropertyValue,
}
-impl Into<(PropertyKey, PropertyValue)> for Property {
- fn into(self) -> (PropertyKey, PropertyValue) {
- (self.key, self.value)
+impl From<Property> for (PropertyKey, PropertyValue) {
+ fn from(value: Property) -> Self {
+ (value.key, value.value)
}
}
@@ -1116,9 +1121,9 @@
pub permission: PropertyPermission,
}
-impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {
- fn into(self) -> (PropertyKey, PropertyPermission) {
- (self.key, self.permission)
+impl From<PropertyKeyPermission> for (PropertyKey, PropertyPermission) {
+ fn from(value: PropertyKeyPermission) -> Self {
+ (value.key, value.permission)
}
}
@@ -1415,7 +1420,7 @@
value: Self::Value,
) -> Result<Option<Self::Value>, PropertiesError> {
let key_size = scoped_slice_size(scope, &key);
- let value_size = slice_size(&value) as u32;
+ let value_size = slice_size(&value);
if self.consumed_space + value_size + key_size > S && !cfg!(feature = "runtime-benchmarks")
{
@@ -1425,7 +1430,7 @@
let old_value = self.map.try_scoped_set(scope, key, value)?;
if let Some(old_value) = old_value.as_ref() {
- let old_value_size = slice_size(&old_value);
+ let old_value_size = slice_size(old_value);
self.consumed_space = self.consumed_space.saturating_sub(old_value_size) + value_size;
} else {
self.consumed_space += key_size + value_size;
runtime/common/config/xcm/foreignassets.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/foreignassets.rs
+++ b/runtime/common/config/xcm/foreignassets.rs
@@ -65,7 +65,7 @@
return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));
}
- match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {
+ match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {
Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {
ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))
}
@@ -206,9 +206,7 @@
return Some(AssetIds::NativeAssetId(NativeCurrency::Parent));
}
- if let Some(currency_id) =
- XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location.clone())
- {
+ if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {
return Some(currency_id);
}
runtime/common/ethereum/precompiles/mod.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/mod.rs
+++ b/runtime/common/ethereum/precompiles/mod.rs
@@ -37,6 +37,16 @@
[hash(1), hash(20482)]
}
}
+
+impl<R> Default for UniquePrecompiles<R>
+where
+ R: pallet_evm::Config,
+{
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl<R> PrecompileSet for UniquePrecompiles<R>
where
R: pallet_evm::Config,
runtime/common/ethereum/precompiles/sr25519.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/sr25519.rs
+++ b/runtime/common/ethereum/precompiles/sr25519.rs
@@ -64,7 +64,7 @@
// Parse arguments
let public: sr25519::Public =
- sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?).into();
+ sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?);
let signature_bytes: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
let message: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
runtime/common/ethereum/precompiles/utils/data.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/utils/data.rs
+++ b/runtime/common/ethereum/precompiles/utils/data.rs
@@ -60,7 +60,7 @@
}
impl Into<Vec<u8>> for Bytes {
- fn into(self: Self) -> Vec<u8> {
+ fn into(self) -> Vec<u8> {
self.0
}
}
runtime/common/ethereum/precompiles/utils/mod.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/utils/mod.rs
+++ b/runtime/common/ethereum/precompiles/utils/mod.rs
@@ -73,7 +73,6 @@
}
}
- #[must_use]
/// Check that a function call is compatible with the context it is
/// called into.
pub fn check_function_modifier(
runtime/common/ethereum/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -78,7 +78,7 @@
let token_id: TokenId = token_id.try_into().ok()?;
withdraw_set_token_property::<T>(
&collection,
- &who,
+ who,
&token_id,
key.len() + value.len(),
)
@@ -88,7 +88,7 @@
ERC721UniqueExtensionsCall::Transfer { token_id, .. },
) => {
let token_id: TokenId = token_id.try_into().ok()?;
- withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
+ withdraw_transfer::<T>(&collection, who, &token_id).map(|()| sponsor)
}
UniqueNFTCall::ERC721UniqueMintable(
ERC721UniqueMintableCall::Mint { .. }
@@ -97,7 +97,7 @@
| ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },
) => withdraw_create_item::<T>(
&collection,
- &who,
+ who,
&CreateItemData::NFT(CreateNftData::default()),
)
.map(|()| sponsor),
runtime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -16,7 +16,6 @@
//! Implements EVM sponsoring logic via TransactionValidityHack
-use core::convert::TryInto;
use pallet_common::CollectionHandle;
use pallet_evm::account::CrossAccountId;
use pallet_fungible::Config as FungibleConfig;
@@ -95,7 +94,7 @@
..
} => {
let token_id = TokenId::try_from(token_id).ok()?;
- withdraw_set_token_property::<T>(&collection, &who, &token_id, key.len() + value.len())
+ withdraw_set_token_property::<T>(&collection, who, &token_id, key.len() + value.len())
}
}
}
@@ -242,7 +241,7 @@
MintCross { .. } => withdraw_create_item::<T>(
&collection,
- &who,
+ who,
&CreateItemData::NFT(CreateNftData::default()),
),
@@ -250,7 +249,7 @@
| TransferFromCross { token_id, .. }
| Transfer { token_id, .. } => {
let token_id = TokenId::try_from(token_id).ok()?;
- withdraw_transfer::<T>(&collection, &who, &token_id)
+ withdraw_transfer::<T>(&collection, who, &token_id)
}
}
}
@@ -275,7 +274,7 @@
| MintWithTokenUri { .. }
| MintWithTokenUriCheckId { .. } => withdraw_create_item::<T>(
&collection,
- &who,
+ who,
&CreateItemData::NFT(CreateNftData::default()),
),
}
@@ -311,18 +310,15 @@
Transfer { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
- withdraw_transfer::<T>(&handle, &who, &token_id)
+ withdraw_transfer::<T>(&handle, who, &token_id)
}
TransferFrom { from, .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
let from = T::CrossAccountId::from_eth(from);
withdraw_transfer::<T>(&handle, &from, &token_id)
}
Approve { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
withdraw_approve::<T>(&handle, who.as_sub(), &token_id)
}
}
@@ -351,13 +347,11 @@
TransferCross { .. } | TransferFromCross { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
- withdraw_transfer::<T>(&handle, &who, &token_id)
+ withdraw_transfer::<T>(&handle, who, &token_id)
}
ApproveCross { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
- let token_id = token_id.try_into().ok()?;
withdraw_approve::<T>(&handle, who.as_sub(), &token_id)
}
}
runtime/common/mod.rsdiffbeforeafterboth--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -204,10 +204,7 @@
&[],
);
- let should_upgrade = match version {
- None => true,
- Some(_) => false,
- };
+ let should_upgrade = version.is_none();
if should_upgrade {
log::info!(
@@ -220,7 +217,7 @@
.cloned()
.filter_map(|authority_id| {
weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));
- let vec = authority_id.clone().to_raw_vec();
+ let vec = authority_id.to_raw_vec();
let slice = vec.as_slice();
let array: Option<[u8; 32]> = match slice.try_into() {
Ok(a) => Some(a),
@@ -248,20 +245,20 @@
.into_iter()
.map(|(acc, aura)| {
(
- acc.clone(), // account id
- acc, // validator id
- SessionKeys { aura: aura.clone() }, // session keys
+ acc.clone(), // account id
+ acc, // validator id
+ SessionKeys { aura }, // session keys
)
})
.collect::<Vec<_>>();
- for (account, val, keys) in keys.iter().cloned() {
+ for (account, val, keys) in keys.iter() {
for id in <Runtime as pallet_session::Config>::Keys::key_ids() {
- <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), &val)
+ <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), val)
}
- <pallet_session::NextKeys<Runtime>>::insert(&val, &keys);
+ <pallet_session::NextKeys<Runtime>>::insert(val, keys);
// todo exercise caution, the following is taken from genesis
- if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(&account)
+ if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(account)
.is_err()
{
log::warn!(
@@ -271,7 +268,7 @@
// genesis) so it's really not a big deal and we assume that the user wants to
// do this since it's the only way a non-endowed account can contain a session
// key.
- frame_system::Pallet::<Runtime>::inc_providers(&account);
+ frame_system::Pallet::<Runtime>::inc_providers(account);
}
}
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -84,7 +84,7 @@
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
let budget = up_data_structs::budget::Value::new(10);
- Ok(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?)
+ <pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)
}
fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {
Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))
runtime/common/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/sponsoring.rs
+++ b/runtime/common/sponsoring.rs
@@ -240,7 +240,7 @@
withdraw_set_token_property(
&collection,
&T::CrossAccountId::from_sub(who.clone()),
- &token_id,
+ token_id,
// No overflow may happen, as data larger than usize can't reach here
properties.iter().map(|p| p.key.len() + p.value.len()).sum(),
)
test-pallets/utils/src/lib.rsdiffbeforeafterboth--- a/test-pallets/utils/src/lib.rs
+++ b/test-pallets/utils/src/lib.rs
@@ -170,7 +170,7 @@
fn ensure_origin_and_enabled(origin: OriginFor<T>) -> DispatchResult {
ensure_signed(origin)?;
<Enabled<T>>::get()
- .then(|| ())
+ .then_some(())
.ok_or(<Error<T>>::TestPalletDisabled.into())
}
}