difftreelog
refactor return CrossAccountId in backing storages
in: master
14 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -75,9 +75,17 @@
) -> Result<String>;
#[rpc(name = "nft_adminlist")]
- fn adminlist(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<Vec<AccountId>>;
+ fn adminlist(
+ &self,
+ collection: CollectionId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<CrossAccountId>>;
#[rpc(name = "nft_allowlist")]
- fn allowlist(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<Vec<AccountId>>;
+ fn allowlist(
+ &self,
+ collection: CollectionId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<CrossAccountId>>;
#[rpc(name = "nft_lastTokenId")]
fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;
}
@@ -150,7 +158,7 @@
pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string());
pass_method!(allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string());
- pass_method!(adminlist(collection: CollectionId) -> Vec<AccountId>);
- pass_method!(allowlist(collection: CollectionId) -> Vec<AccountId>);
+ pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>);
+ pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);
pass_method!(last_token_id(collection: CollectionId) -> TokenId);
}
pallets/common/src/account.rsdiffbeforeafterboth--- a/pallets/common/src/account.rs
+++ b/pallets/common/src/account.rs
@@ -19,6 +19,8 @@
fn from_sub(account: AccountId) -> Self;
fn from_eth(account: H160) -> Self;
+
+ fn conv_eq(&self, other: &Self) -> bool;
}
#[derive(Encode, Decode, Serialize, Deserialize, TypeInfo)]
@@ -28,7 +30,7 @@
Ethereum(H160),
}
-#[derive(Eq)]
+#[derive(PartialEq, Eq)]
pub struct BasicCrossAccountId<T: Config> {
/// If true - then ethereum is canonical encoding
from_ethereum: bool,
@@ -77,18 +79,6 @@
}
}
-impl<T: Config> PartialEq for BasicCrossAccountId<T> {
- fn eq(&self, other: &Self) -> bool {
- if self.from_ethereum == other.from_ethereum {
- self.substrate == other.substrate && self.ethereum == other.ethereum
- } else if self.from_ethereum {
- // ethereum is canonical encoding, but we need to compare derived address
- self.substrate == other.substrate
- } else {
- self.ethereum == other.ethereum
- }
- }
-}
impl<T: Config> Clone for BasicCrossAccountId<T> {
fn clone(&self) -> Self {
Self {
@@ -158,6 +148,16 @@
from_ethereum: true,
}
}
+ fn conv_eq(&self, other: &Self) -> bool {
+ if self.from_ethereum == other.from_ethereum {
+ self.substrate == other.substrate && self.ethereum == other.ethereum
+ } else if self.from_ethereum {
+ // ethereum is canonical encoding, but we need to compare derived address
+ self.substrate == other.substrate
+ } else {
+ self.ethereum == other.ethereum
+ }
+ }
}
impl<T: Config> From<BasicCrossAccountIdRepr<T::AccountId>> for BasicCrossAccountId<T> {
fn from(repr: BasicCrossAccountIdRepr<T::AccountId>) -> Self {
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -98,7 +98,7 @@
pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> Result<bool, DispatchError> {
self.consume_sload()?;
- Ok(*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject.as_sub())))
+ Ok(*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject)))
}
pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {
ensure!(self.is_owner_or_admin(subject)?, <Error<T>>::NoPermission);
@@ -114,7 +114,7 @@
self.consume_sload()?;
ensure!(
- <Allowlist<T>>::get((self.id, user.as_sub())),
+ <Allowlist<T>>::get((self.id, user)),
<Error<T>>::AddressNotInAllowlist
);
Ok(())
@@ -139,8 +139,7 @@
#[frame_support::pallet]
pub mod pallet {
use super::*;
- use frame_support::{pallet_prelude::*};
- use frame_support::{Blake2_128Concat, storage::Key};
+ use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};
use account::{EvmBackwardsAddressMapping, CrossAccountId};
use frame_support::traits::Currency;
use nft_data_structs::TokenId;
@@ -311,7 +310,7 @@
pub type IsAdmin<T: Config> = StorageNMap<
Key = (
Key<Blake2_128Concat, CollectionId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = bool,
QueryKind = ValueQuery,
@@ -322,7 +321,7 @@
pub type Allowlist<T: Config> = StorageNMap<
Key = (
Key<Blake2_128Concat, CollectionId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = bool,
QueryKind = ValueQuery,
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -2,9 +2,7 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use nft_data_structs::TokenId;
-use pallet_common::{
- CommonCollectionOperations, CommonWeightInfo, account::CrossAccountId, with_weight,
-};
+use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
@@ -188,7 +186,7 @@
}
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
- if <Balance<T>>::get((self.id, account.as_sub())) != 0 {
+ if <Balance<T>>::get((self.id, account)) != 0 {
vec![TokenId::default()]
} else {
vec![]
@@ -218,7 +216,7 @@
}
fn account_balance(&self, account: T::CrossAccountId) -> u32 {
- if <Balance<T>>::get((self.id, account.as_sub())) != 0 {
+ if <Balance<T>>::get((self.id, account)) != 0 {
1
} else {
0
@@ -229,7 +227,7 @@
if token != TokenId::default() {
return 0;
}
- <Balance<T>>::get((self.id, account.as_sub()))
+ <Balance<T>>::get((self.id, account))
}
fn allowance(
@@ -241,6 +239,6 @@
if token != TokenId::default() {
return 0;
}
- <Allowance<T>>::get((self.id, sender.as_sub(), spender.as_sub()))
+ <Allowance<T>>::get((self.id, sender, spender))
}
}
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -52,7 +52,7 @@
}
fn balance_of(&self, owner: address) -> Result<uint256> {
let owner = T::CrossAccountId::from_eth(owner);
- let balance = <Balance<T>>::get((self.id, owner.as_sub()));
+ let balance = <Balance<T>>::get((self.id, owner));
Ok(balance.into())
}
fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {
@@ -92,7 +92,7 @@
let owner = T::CrossAccountId::from_eth(owner);
let spender = T::CrossAccountId::from_eth(spender);
- Ok(<Allowance<T>>::get((self.id, owner.as_sub(), spender.as_sub())).into())
+ Ok(<Allowance<T>>::get((self.id, owner, spender)).into())
}
}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -55,7 +55,7 @@
pub(super) type Balance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = u128,
QueryKind = ValueQuery,
@@ -65,8 +65,8 @@
pub(super) type Allowance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
- Key<Blake2_128, T::AccountId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128, T::CrossAccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = u128,
QueryKind = ValueQuery,
@@ -119,7 +119,7 @@
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
- let balance = <Balance<T>>::get((collection.id, owner.as_sub()))
+ let balance = <Balance<T>>::get((collection.id, owner))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
@@ -130,9 +130,9 @@
// =========
if balance == 0 {
- <Balance<T>>::remove((collection.id, owner.as_sub()));
+ <Balance<T>>::remove((collection.id, owner));
} else {
- <Balance<T>>::insert((collection.id, owner.as_sub()), balance);
+ <Balance<T>>::insert((collection.id, owner), balance);
}
<TotalSupply<T>>::insert(collection.id, total_supply);
@@ -167,12 +167,12 @@
}
<PalletCommon<T>>::ensure_correct_receiver(to)?;
- let balance_from = <Balance<T>>::get((collection.id, from.as_sub()))
+ let balance_from = <Balance<T>>::get((collection.id, from))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
let balance_to = if from != to {
Some(
- <Balance<T>>::get((collection.id, to.as_sub()))
+ <Balance<T>>::get((collection.id, to))
.checked_add(amount)
.ok_or(ArithmeticError::Overflow)?,
)
@@ -190,11 +190,11 @@
if let Some(balance_to) = balance_to {
// from != to
if balance_from == 0 {
- <Balance<T>>::remove((collection.id, from.as_sub()));
+ <Balance<T>>::remove((collection.id, from));
} else {
- <Balance<T>>::insert((collection.id, from.as_sub()), balance_from);
+ <Balance<T>>::insert((collection.id, from), balance_from);
}
- <Balance<T>>::insert((collection.id, to.as_sub()), balance_to);
+ <Balance<T>>::insert((collection.id, to), balance_to);
}
collection.log_infallible(ERC20Events::Transfer {
@@ -242,7 +242,7 @@
collection.consume_sload()?;
let balance = balances
.entry(user.clone())
- .or_insert_with(|| <Balance<T>>::get((collection.id, user.as_sub())));
+ .or_insert_with(|| <Balance<T>>::get((collection.id, user)));
*balance = (*balance)
.checked_add(amount)
.ok_or(ArithmeticError::Overflow)?;
@@ -259,7 +259,7 @@
<TotalSupply<T>>::insert(collection.id, total_supply);
for (user, amount) in balances {
- <Balance<T>>::insert((collection.id, user.as_sub()), amount);
+ <Balance<T>>::insert((collection.id, &user), amount);
collection.log_infallible(ERC20Events::Transfer {
from: H160::default(),
@@ -283,7 +283,7 @@
spender: &T::CrossAccountId,
amount: u128,
) {
- <Allowance<T>>::insert((collection.id, owner.as_sub(), spender.as_sub()), amount);
+ <Allowance<T>>::insert((collection.id, owner, spender), amount);
collection.log_infallible(ERC20Events::Approval {
owner: *owner.as_eth(),
@@ -310,7 +310,7 @@
collection.check_allowlist(&spender)?;
}
- if <Balance<T>>::get((collection.id, owner.as_sub())) < amount {
+ if <Balance<T>>::get((collection.id, owner)) < amount {
ensure!(
collection.ignores_owned_amount(owner)?,
<CommonError<T>>::CantApproveMoreThanOwned
@@ -330,7 +330,7 @@
to: &T::CrossAccountId,
amount: u128,
) -> DispatchResult {
- if spender == from {
+ if spender.conv_eq(from) {
return Self::transfer(collection, from, to, amount);
}
if collection.access == AccessMode::WhiteList {
@@ -338,8 +338,7 @@
collection.check_allowlist(spender)?;
}
- let allowance = <Allowance<T>>::get((collection.id, from.as_sub(), spender.as_sub()))
- .checked_sub(amount);
+ let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
collection.ignores_allowance(spender)?,
@@ -362,7 +361,7 @@
from: &T::CrossAccountId,
amount: u128,
) -> DispatchResult {
- if spender == from {
+ if spender.conv_eq(from) {
return Self::burn(collection, from, amount);
}
if collection.access == AccessMode::WhiteList {
@@ -370,8 +369,7 @@
collection.check_allowlist(spender)?;
}
- let allowance = <Allowance<T>>::get((collection.id, from.as_sub(), spender.as_sub()))
- .checked_sub(amount);
+ let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
collection.ignores_allowance(spender)?,
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -948,12 +948,12 @@
// TODO: limit returned entries?
impl<T: Config> Pallet<T> {
- pub fn adminlist(collection: CollectionId) -> Vec<T::AccountId> {
+ pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
<IsAdmin<T>>::iter_prefix((collection,))
.map(|(a, _)| a)
.collect()
}
- pub fn allowlist(collection: CollectionId) -> Vec<T::AccountId> {
+ pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
<Allowlist<T>>::iter_prefix((collection,))
.map(|(a, _)| a)
.collect()
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -2,9 +2,7 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use nft_data_structs::TokenId;
-use pallet_common::{
- CommonCollectionOperations, CommonWeightInfo, account::CrossAccountId, with_weight,
-};
+use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
use sp_std::vec::Vec;
@@ -200,7 +198,7 @@
}
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
- <Owned<T>>::iter_prefix((self.id, account.as_sub()))
+ <Owned<T>>::iter_prefix((self.id, account))
.map(|(id, _)| id)
.collect()
}
@@ -234,7 +232,7 @@
}
fn account_balance(&self, account: T::CrossAccountId) -> u32 {
- <AccountBalance<T>>::get((self.id, account.as_sub()))
+ <AccountBalance<T>>::get((self.id, account))
}
fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -93,7 +93,7 @@
impl<T: Config> NonfungibleHandle<T> {
fn balance_of(&self, owner: address) -> Result<uint256> {
let owner = T::CrossAccountId::from_eth(owner);
- let balance = <AccountBalance<T>>::get((self.id, owner.as_sub()));
+ let balance = <AccountBalance<T>>::get((self.id, owner));
Ok(balance.into())
}
fn owner_of(&self, token_id: uint256) -> Result<address> {
pallets/nonfungible/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use erc::ERC721Events;4use frame_support::{BoundedVec, ensure};5use nft_data_structs::{6 AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit, TokenId,7};8use pallet_common::{9 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,10};11use sp_core::H160;12use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};13use sp_std::{vec::Vec, vec};14use core::ops::Deref;15use sp_std::collections::btree_map::BTreeMap;16use codec::{Encode, Decode};17use scale_info::TypeInfo;1819pub use pallet::*;20#[cfg(feature = "runtime-benchmarks")]21pub mod benchmarking;22pub mod common;23pub mod erc;24pub mod weights;2526pub struct CreateItemData<T: Config> {27 pub const_data: BoundedVec<u8, CustomDataLimit>,28 pub variable_data: BoundedVec<u8, CustomDataLimit>,29 pub owner: T::CrossAccountId,30}31pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;3233#[derive(Encode, Decode, TypeInfo)]34pub struct ItemData<T: Config> {35 pub const_data: Vec<u8>,36 pub variable_data: Vec<u8>,37 pub owner: T::CrossAccountId,38}3940#[frame_support::pallet]41pub mod pallet {42 use super::*;43 use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};44 use nft_data_structs::{CollectionId, TokenId};45 use super::weights::WeightInfo;4647 #[pallet::error]48 pub enum Error<T> {49 /// Not Nonfungible item data used to mint in Nonfungible collection.50 NotNonfungibleDataUsedToMintFungibleCollectionToken,51 /// Used amount > 1 with NFT52 NonfungibleItemsHaveNoAmount,53 }5455 #[pallet::config]56 pub trait Config: frame_system::Config + pallet_common::Config {57 type WeightInfo: WeightInfo;58 }5960 #[pallet::pallet]61 #[pallet::generate_store(pub(super) trait Store)]62 pub struct Pallet<T>(_);6364 #[pallet::storage]65 pub(super) type TokensMinted<T: Config> =66 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;67 #[pallet::storage]68 pub(super) type TokensBurnt<T: Config> =69 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;7071 #[pallet::storage]72 pub(super) type TokenData<T: Config> = StorageNMap<73 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),74 Value = ItemData<T>,75 QueryKind = OptionQuery,76 >;7778 /// Used to enumerate tokens owned by account79 #[pallet::storage]80 pub(super) type Owned<T: Config> = StorageNMap<81 Key = (82 Key<Twox64Concat, CollectionId>,83 Key<Blake2_128Concat, T::AccountId>,84 Key<Twox64Concat, TokenId>,85 ),86 Value = bool,87 QueryKind = ValueQuery,88 >;8990 #[pallet::storage]91 pub(super) type AccountBalance<T: Config> = StorageNMap<92 Key = (93 Key<Twox64Concat, CollectionId>,94 Key<Blake2_128Concat, T::AccountId>,95 ),96 Value = u32,97 QueryKind = ValueQuery,98 >;99100 #[pallet::storage]101 pub(super) type Allowance<T: Config> = StorageNMap<102 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),103 Value = T::CrossAccountId,104 QueryKind = OptionQuery,105 >;106}107108pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);109impl<T: Config> NonfungibleHandle<T> {110 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {111 Self(inner)112 }113 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {114 self.0115 }116}117impl<T: Config> Deref for NonfungibleHandle<T> {118 type Target = pallet_common::CollectionHandle<T>;119120 fn deref(&self) -> &Self::Target {121 &self.0122 }123}124125impl<T: Config> Pallet<T> {126 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {127 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)128 }129 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {130 <TokenData<T>>::contains_key((collection.id, token))131 }132}133134// unchecked calls skips any permission checks135impl<T: Config> Pallet<T> {136 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {137 PalletCommon::init_collection(data)138 }139 pub fn destroy_collection(140 collection: NonfungibleHandle<T>,141 sender: &T::CrossAccountId,142 ) -> DispatchResult {143 let id = collection.id;144145 // =========146147 PalletCommon::destroy_collection(collection.0, sender)?;148149 <TokenData<T>>::remove_prefix((id,), None);150 <Owned<T>>::remove_prefix((id,), None);151 <TokensMinted<T>>::remove(id);152 <TokensBurnt<T>>::remove(id);153 <Allowance<T>>::remove_prefix((id,), None);154 <AccountBalance<T>>::remove_prefix((id,), None);155 Ok(())156 }157158 pub fn burn(159 collection: &NonfungibleHandle<T>,160 sender: &T::CrossAccountId,161 token: TokenId,162 ) -> DispatchResult {163 let token_data = <TokenData<T>>::get((collection.id, token))164 .ok_or_else(|| <CommonError<T>>::TokenNotFound)?;165 ensure!(166 &token_data.owner == sender167 || (collection.limits.owner_can_transfer()168 && collection.is_owner_or_admin(sender)?),169 <CommonError<T>>::NoPermission170 );171172 if collection.access == AccessMode::WhiteList {173 collection.check_allowlist(sender)?;174 }175176 let burnt = <TokensBurnt<T>>::get(collection.id)177 .checked_add(1)178 .ok_or(ArithmeticError::Overflow)?;179180 // =========181182 <Owned<T>>::remove((collection.id, token_data.owner.as_sub(), token));183 <TokensBurnt<T>>::insert(collection.id, burnt);184 <TokenData<T>>::remove((collection.id, token));185 let old_spender = <Allowance<T>>::take((collection.id, token));186187 if let Some(old_spender) = old_spender {188 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(189 collection.id,190 token,191 sender.clone(),192 old_spender.clone(),193 0,194 ));195 }196197 collection.log_infallible(ERC721Events::Transfer {198 from: *token_data.owner.as_eth(),199 to: H160::default(),200 token_id: token.into(),201 });202 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(203 collection.id,204 token,205 token_data.owner,206 1,207 ));208 return Ok(());209 }210211 pub fn transfer(212 collection: &NonfungibleHandle<T>,213 from: &T::CrossAccountId,214 to: &T::CrossAccountId,215 token: TokenId,216 ) -> DispatchResult {217 ensure!(218 collection.limits.transfers_enabled(),219 <CommonError<T>>::TransferNotAllowed220 );221222 let token_data = <TokenData<T>>::get((collection.id, token))223 .ok_or_else(|| <CommonError<T>>::TokenNotFound)?;224 ensure!(225 &token_data.owner == from226 || (collection.limits.owner_can_transfer()227 && collection.is_owner_or_admin(from)?),228 <CommonError<T>>::NoPermission229 );230231 if collection.access == AccessMode::WhiteList {232 collection.check_allowlist(from)?;233 collection.check_allowlist(to)?;234 }235 <PalletCommon<T>>::ensure_correct_receiver(to)?;236237 let balance_from = <AccountBalance<T>>::get((collection.id, from.as_sub()))238 .checked_sub(1)239 .ok_or(<CommonError<T>>::TokenValueTooLow)?;240 let balance_to = if from != to {241 let balance_to = <AccountBalance<T>>::get((collection.id, to.as_sub()))242 .checked_add(1)243 .ok_or(ArithmeticError::Overflow)?;244245 ensure!(246 balance_to < collection.limits.account_token_ownership_limit(),247 <CommonError<T>>::AccountTokenLimitExceeded,248 );249250 Some(balance_to)251 } else {252 None253 };254255 collection.consume_sstores(4)?;256 collection.consume_log(3, 0)?;257258 // =========259260 <TokenData<T>>::insert(261 (collection.id, token),262 ItemData {263 owner: to.clone(),264 ..token_data265 },266 );267268 if let Some(balance_to) = balance_to {269 // from != to270 if balance_from == 0 {271 <AccountBalance<T>>::remove((collection.id, from.as_sub()));272 } else {273 <AccountBalance<T>>::insert((collection.id, from.as_sub()), balance_from);274 }275 <AccountBalance<T>>::insert((collection.id, to.as_sub()), balance_to);276 <Owned<T>>::remove((collection.id, from.as_sub(), token));277 <Owned<T>>::insert((collection.id, to.as_sub(), token), true);278 }279 Self::set_allowance_unchecked(collection, from, token, None, true);280281 collection.log_infallible(ERC721Events::Transfer {282 from: *from.as_eth(),283 to: *to.as_eth(),284 token_id: token.into(),285 });286 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(287 collection.id,288 token,289 from.clone(),290 to.clone(),291 1,292 ));293 Ok(())294 }295296 pub fn create_multiple_items(297 collection: &NonfungibleHandle<T>,298 sender: &T::CrossAccountId,299 data: Vec<CreateItemData<T>>,300 ) -> DispatchResult {301 let unrestricted_minting = collection.is_owner_or_admin(sender)?;302 if !unrestricted_minting {303 ensure!(304 collection.mint_mode,305 <CommonError<T>>::PublicMintingNotAllowed306 );307 collection.check_allowlist(sender)?;308309 for item in data.iter() {310 collection.check_allowlist(&item.owner)?;311 }312 }313314 for data in data.iter() {315 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;316 if !data.const_data.is_empty() {317 collection.consume_sstore()?;318 }319 if !data.variable_data.is_empty() {320 collection.consume_sstore()?;321 }322 collection.consume_sstore()?;323 collection.consume_log(3, 0)?;324 }325326 let first_token = <TokensMinted<T>>::get(collection.id);327 let tokens_minted = first_token328 .checked_add(data.len() as u32)329 .ok_or(ArithmeticError::Overflow)?;330 ensure!(331 tokens_minted < collection.limits.token_limit(),332 <CommonError<T>>::CollectionTokenLimitExceeded333 );334 collection.consume_sstore()?;335336 let mut balances = BTreeMap::new();337 for data in &data {338 let balance = balances339 .entry(data.owner.as_sub())340 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, data.owner.as_sub())));341 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;342343 ensure!(344 *balance <= collection.limits.account_token_ownership_limit(),345 <CommonError<T>>::AccountTokenLimitExceeded,346 );347 }348 collection.consume_sstores(balances.len())?;349350 // =========351352 <TokensMinted<T>>::insert(collection.id, tokens_minted);353 for (account, balance) in balances {354 <AccountBalance<T>>::insert((collection.id, account), balance);355 }356 for (i, data) in data.into_iter().enumerate() {357 let token = first_token + i as u32 + 1;358359 <TokenData<T>>::insert(360 (collection.id, token),361 ItemData {362 const_data: data.const_data.into(),363 variable_data: data.variable_data.into(),364 owner: data.owner.clone(),365 },366 );367 <Owned<T>>::insert((collection.id, data.owner.as_sub(), token), true);368369 collection.log_infallible(ERC721Events::Transfer {370 from: H160::default(),371 to: *data.owner.as_eth(),372 token_id: token.into(),373 });374 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(375 collection.id,376 TokenId(token),377 data.owner.clone(),378 1,379 ));380 }381 Ok(())382 }383384 pub fn set_allowance_unchecked(385 collection: &NonfungibleHandle<T>,386 sender: &T::CrossAccountId,387 token: TokenId,388 spender: Option<&T::CrossAccountId>,389 assume_implicit_eth: bool,390 ) {391 if let Some(spender) = spender {392 let old_spender = <Allowance<T>>::get((collection.id, token));393 <Allowance<T>>::insert((collection.id, token), spender);394 // In ERC721 there is only one possible approved user of token, so we set395 // approved user to spender396 collection.log_infallible(ERC721Events::Approval {397 owner: *sender.as_eth(),398 approved: *spender.as_eth(),399 token_id: token.into(),400 });401 // In Unique chain, any token can have any amount of approved users, so we need to402 // set allowance of old owner to 0, and allowance of new owner to 1403 if old_spender.as_ref() != Some(spender) {404 if let Some(old_owner) = old_spender {405 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(406 collection.id,407 token,408 sender.clone(),409 old_owner.clone(),410 0,411 ));412 }413 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(414 collection.id,415 token,416 sender.clone(),417 spender.clone(),418 1,419 ));420 }421 } else {422 let old_spender = <Allowance<T>>::take((collection.id, token));423 if !assume_implicit_eth {424 // In ERC721 there is only one possible approved user of token, so we set425 // approved user to zero address426 collection.log_infallible(ERC721Events::Approval {427 owner: *sender.as_eth(),428 approved: H160::default(),429 token_id: token.into(),430 });431 }432 // In Unique chain, any token can have any amount of approved users, so we need to433 // set allowance of old owner to 0434 if let Some(old_spender) = old_spender {435 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(436 collection.id,437 token,438 sender.clone(),439 old_spender.clone(),440 0,441 ));442 }443 }444 }445446 pub fn set_allowance(447 collection: &NonfungibleHandle<T>,448 sender: &T::CrossAccountId,449 token: TokenId,450 spender: Option<&T::CrossAccountId>,451 ) -> DispatchResult {452 if collection.access == AccessMode::WhiteList {453 collection.check_allowlist(&sender)?;454 if let Some(spender) = spender {455 collection.check_allowlist(&spender)?;456 }457 }458459 if let Some(spender) = spender {460 <PalletCommon<T>>::ensure_correct_receiver(spender)?;461 }462 let token_data =463 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;464 if &token_data.owner != sender {465 ensure!(466 collection.ignores_owned_amount(sender)?,467 <CommonError<T>>::CantApproveMoreThanOwned468 );469 }470471 // =========472473 Self::set_allowance_unchecked(collection, sender, token, spender, false);474 Ok(())475 }476477 pub fn transfer_from(478 collection: &NonfungibleHandle<T>,479 spender: &T::CrossAccountId,480 from: &T::CrossAccountId,481 to: &T::CrossAccountId,482 token: TokenId,483 ) -> DispatchResult {484 if spender == from {485 return Self::transfer(collection, from, to, token);486 }487 if collection.access == AccessMode::WhiteList {488 // `from`, `to` checked in [`transfer`]489 collection.check_allowlist(spender)?;490 }491492 if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {493 ensure!(494 collection.ignores_allowance(spender)?,495 <CommonError<T>>::TokenValueNotEnough496 );497 }498499 // =========500501 Self::transfer(collection, &from, to, token)?;502 // Allowance is reset in [`transfer`]503 Ok(())504 }505506 pub fn burn_from(507 collection: &NonfungibleHandle<T>,508 spender: &T::CrossAccountId,509 from: &T::CrossAccountId,510 token: TokenId,511 ) -> DispatchResult {512 if spender == from {513 return Self::burn(collection, from, token);514 }515 if collection.access == AccessMode::WhiteList {516 // `from` checked in [`burn`]517 collection.check_allowlist(spender)?;518 }519520 if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {521 ensure!(522 collection.ignores_allowance(spender)?,523 <CommonError<T>>::TokenValueNotEnough524 );525 }526527 // =========528529 Self::burn(collection, &from, token)530 }531532 pub fn set_variable_metadata(533 collection: &NonfungibleHandle<T>,534 sender: &T::CrossAccountId,535 token: TokenId,536 data: Vec<u8>,537 ) -> DispatchResult {538 ensure!(539 data.len() as u32 <= CUSTOM_DATA_LIMIT,540 <CommonError<T>>::TokenVariableDataLimitExceeded541 );542 let token_data =543 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;544 collection.check_can_update_meta(sender, &token_data.owner)?;545546 collection.consume_sstore()?;547548 // =========549550 <TokenData<T>>::insert(551 (collection.id, token),552 ItemData {553 variable_data: data,554 ..token_data555 },556 );557 Ok(())558 }559560 /// Delegated to `create_multiple_items`561 pub fn create_item(562 collection: &NonfungibleHandle<T>,563 sender: &T::CrossAccountId,564 data: CreateItemData<T>,565 ) -> DispatchResult {566 Self::create_multiple_items(collection, sender, vec![data])567 }568}1#![cfg_attr(not(feature = "std"), no_std)]23use erc::ERC721Events;4use frame_support::{BoundedVec, ensure};5use nft_data_structs::{6 AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit, TokenId,7};8use pallet_common::{9 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,10};11use sp_core::H160;12use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};13use sp_std::{vec::Vec, vec};14use core::ops::Deref;15use sp_std::collections::btree_map::BTreeMap;16use codec::{Encode, Decode};17use scale_info::TypeInfo;1819pub use pallet::*;20#[cfg(feature = "runtime-benchmarks")]21pub mod benchmarking;22pub mod common;23pub mod erc;24pub mod weights;2526pub struct CreateItemData<T: Config> {27 pub const_data: BoundedVec<u8, CustomDataLimit>,28 pub variable_data: BoundedVec<u8, CustomDataLimit>,29 pub owner: T::CrossAccountId,30}31pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;3233#[derive(Encode, Decode, TypeInfo)]34pub struct ItemData<T: Config> {35 pub const_data: Vec<u8>,36 pub variable_data: Vec<u8>,37 pub owner: T::CrossAccountId,38}3940#[frame_support::pallet]41pub mod pallet {42 use super::*;43 use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};44 use nft_data_structs::{CollectionId, TokenId};45 use super::weights::WeightInfo;4647 #[pallet::error]48 pub enum Error<T> {49 /// Not Nonfungible item data used to mint in Nonfungible collection.50 NotNonfungibleDataUsedToMintFungibleCollectionToken,51 /// Used amount > 1 with NFT52 NonfungibleItemsHaveNoAmount,53 }5455 #[pallet::config]56 pub trait Config: frame_system::Config + pallet_common::Config {57 type WeightInfo: WeightInfo;58 }5960 #[pallet::pallet]61 #[pallet::generate_store(pub(super) trait Store)]62 pub struct Pallet<T>(_);6364 #[pallet::storage]65 pub(super) type TokensMinted<T: Config> =66 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;67 #[pallet::storage]68 pub(super) type TokensBurnt<T: Config> =69 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;7071 #[pallet::storage]72 pub(super) type TokenData<T: Config> = StorageNMap<73 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),74 Value = ItemData<T>,75 QueryKind = OptionQuery,76 >;7778 /// Used to enumerate tokens owned by account79 #[pallet::storage]80 pub(super) type Owned<T: Config> = StorageNMap<81 Key = (82 Key<Twox64Concat, CollectionId>,83 Key<Blake2_128Concat, T::CrossAccountId>,84 Key<Twox64Concat, TokenId>,85 ),86 Value = bool,87 QueryKind = ValueQuery,88 >;8990 #[pallet::storage]91 pub(super) type AccountBalance<T: Config> = StorageNMap<92 Key = (93 Key<Twox64Concat, CollectionId>,94 Key<Blake2_128Concat, T::CrossAccountId>,95 ),96 Value = u32,97 QueryKind = ValueQuery,98 >;99100 #[pallet::storage]101 pub(super) type Allowance<T: Config> = StorageNMap<102 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),103 Value = T::CrossAccountId,104 QueryKind = OptionQuery,105 >;106}107108pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);109impl<T: Config> NonfungibleHandle<T> {110 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {111 Self(inner)112 }113 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {114 self.0115 }116}117impl<T: Config> Deref for NonfungibleHandle<T> {118 type Target = pallet_common::CollectionHandle<T>;119120 fn deref(&self) -> &Self::Target {121 &self.0122 }123}124125impl<T: Config> Pallet<T> {126 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {127 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)128 }129 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {130 <TokenData<T>>::contains_key((collection.id, token))131 }132}133134// unchecked calls skips any permission checks135impl<T: Config> Pallet<T> {136 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {137 PalletCommon::init_collection(data)138 }139 pub fn destroy_collection(140 collection: NonfungibleHandle<T>,141 sender: &T::CrossAccountId,142 ) -> DispatchResult {143 let id = collection.id;144145 // =========146147 PalletCommon::destroy_collection(collection.0, sender)?;148149 <TokenData<T>>::remove_prefix((id,), None);150 <Owned<T>>::remove_prefix((id,), None);151 <TokensMinted<T>>::remove(id);152 <TokensBurnt<T>>::remove(id);153 <Allowance<T>>::remove_prefix((id,), None);154 <AccountBalance<T>>::remove_prefix((id,), None);155 Ok(())156 }157158 pub fn burn(159 collection: &NonfungibleHandle<T>,160 sender: &T::CrossAccountId,161 token: TokenId,162 ) -> DispatchResult {163 let token_data = <TokenData<T>>::get((collection.id, token))164 .ok_or_else(|| <CommonError<T>>::TokenNotFound)?;165 ensure!(166 &token_data.owner == sender167 || (collection.limits.owner_can_transfer()168 && collection.is_owner_or_admin(sender)?),169 <CommonError<T>>::NoPermission170 );171172 if collection.access == AccessMode::WhiteList {173 collection.check_allowlist(sender)?;174 }175176 let burnt = <TokensBurnt<T>>::get(collection.id)177 .checked_add(1)178 .ok_or(ArithmeticError::Overflow)?;179180 // =========181182 <Owned<T>>::remove((collection.id, &token_data.owner, token));183 <TokensBurnt<T>>::insert(collection.id, burnt);184 <TokenData<T>>::remove((collection.id, token));185 let old_spender = <Allowance<T>>::take((collection.id, token));186187 if let Some(old_spender) = old_spender {188 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(189 collection.id,190 token,191 sender.clone(),192 old_spender.clone(),193 0,194 ));195 }196197 collection.log_infallible(ERC721Events::Transfer {198 from: *token_data.owner.as_eth(),199 to: H160::default(),200 token_id: token.into(),201 });202 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(203 collection.id,204 token,205 token_data.owner,206 1,207 ));208 return Ok(());209 }210211 pub fn transfer(212 collection: &NonfungibleHandle<T>,213 from: &T::CrossAccountId,214 to: &T::CrossAccountId,215 token: TokenId,216 ) -> DispatchResult {217 ensure!(218 collection.limits.transfers_enabled(),219 <CommonError<T>>::TransferNotAllowed220 );221222 let token_data = <TokenData<T>>::get((collection.id, token))223 .ok_or_else(|| <CommonError<T>>::TokenNotFound)?;224 ensure!(225 &token_data.owner == from226 || (collection.limits.owner_can_transfer()227 && collection.is_owner_or_admin(from)?),228 <CommonError<T>>::NoPermission229 );230231 if collection.access == AccessMode::WhiteList {232 collection.check_allowlist(from)?;233 collection.check_allowlist(to)?;234 }235 <PalletCommon<T>>::ensure_correct_receiver(to)?;236237 let balance_from = <AccountBalance<T>>::get((collection.id, from))238 .checked_sub(1)239 .ok_or(<CommonError<T>>::TokenValueTooLow)?;240 let balance_to = if from != to {241 let balance_to = <AccountBalance<T>>::get((collection.id, to))242 .checked_add(1)243 .ok_or(ArithmeticError::Overflow)?;244245 ensure!(246 balance_to < collection.limits.account_token_ownership_limit(),247 <CommonError<T>>::AccountTokenLimitExceeded,248 );249250 Some(balance_to)251 } else {252 None253 };254255 collection.consume_sstores(4)?;256 collection.consume_log(3, 0)?;257258 // =========259260 <TokenData<T>>::insert(261 (collection.id, token),262 ItemData {263 owner: to.clone(),264 ..token_data265 },266 );267268 if let Some(balance_to) = balance_to {269 // from != to270 if balance_from == 0 {271 <AccountBalance<T>>::remove((collection.id, from));272 } else {273 <AccountBalance<T>>::insert((collection.id, from), balance_from);274 }275 <AccountBalance<T>>::insert((collection.id, to), balance_to);276 <Owned<T>>::remove((collection.id, from, token));277 <Owned<T>>::insert((collection.id, to, token), true);278 }279 Self::set_allowance_unchecked(collection, from, token, None, true);280281 collection.log_infallible(ERC721Events::Transfer {282 from: *from.as_eth(),283 to: *to.as_eth(),284 token_id: token.into(),285 });286 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(287 collection.id,288 token,289 from.clone(),290 to.clone(),291 1,292 ));293 Ok(())294 }295296 pub fn create_multiple_items(297 collection: &NonfungibleHandle<T>,298 sender: &T::CrossAccountId,299 data: Vec<CreateItemData<T>>,300 ) -> DispatchResult {301 let unrestricted_minting = collection.is_owner_or_admin(sender)?;302 if !unrestricted_minting {303 ensure!(304 collection.mint_mode,305 <CommonError<T>>::PublicMintingNotAllowed306 );307 collection.check_allowlist(sender)?;308309 for item in data.iter() {310 collection.check_allowlist(&item.owner)?;311 }312 }313314 for data in data.iter() {315 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;316 if !data.const_data.is_empty() {317 collection.consume_sstore()?;318 }319 if !data.variable_data.is_empty() {320 collection.consume_sstore()?;321 }322 collection.consume_sstore()?;323 collection.consume_log(3, 0)?;324 }325326 let first_token = <TokensMinted<T>>::get(collection.id);327 let tokens_minted = first_token328 .checked_add(data.len() as u32)329 .ok_or(ArithmeticError::Overflow)?;330 ensure!(331 tokens_minted < collection.limits.token_limit(),332 <CommonError<T>>::CollectionTokenLimitExceeded333 );334 collection.consume_sstore()?;335336 let mut balances = BTreeMap::new();337 for data in &data {338 let balance = balances339 .entry(&data.owner)340 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));341 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;342343 ensure!(344 *balance <= collection.limits.account_token_ownership_limit(),345 <CommonError<T>>::AccountTokenLimitExceeded,346 );347 }348 collection.consume_sstores(balances.len())?;349350 // =========351352 <TokensMinted<T>>::insert(collection.id, tokens_minted);353 for (account, balance) in balances {354 <AccountBalance<T>>::insert((collection.id, account), balance);355 }356 for (i, data) in data.into_iter().enumerate() {357 let token = first_token + i as u32 + 1;358359 <TokenData<T>>::insert(360 (collection.id, token),361 ItemData {362 const_data: data.const_data.into(),363 variable_data: data.variable_data.into(),364 owner: data.owner.clone(),365 },366 );367 <Owned<T>>::insert((collection.id, &data.owner, token), true);368369 collection.log_infallible(ERC721Events::Transfer {370 from: H160::default(),371 to: *data.owner.as_eth(),372 token_id: token.into(),373 });374 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(375 collection.id,376 TokenId(token),377 data.owner.clone(),378 1,379 ));380 }381 Ok(())382 }383384 pub fn set_allowance_unchecked(385 collection: &NonfungibleHandle<T>,386 sender: &T::CrossAccountId,387 token: TokenId,388 spender: Option<&T::CrossAccountId>,389 assume_implicit_eth: bool,390 ) {391 if let Some(spender) = spender {392 let old_spender = <Allowance<T>>::get((collection.id, token));393 <Allowance<T>>::insert((collection.id, token), spender);394 // In ERC721 there is only one possible approved user of token, so we set395 // approved user to spender396 collection.log_infallible(ERC721Events::Approval {397 owner: *sender.as_eth(),398 approved: *spender.as_eth(),399 token_id: token.into(),400 });401 // In Unique chain, any token can have any amount of approved users, so we need to402 // set allowance of old owner to 0, and allowance of new owner to 1403 if old_spender.as_ref() != Some(spender) {404 if let Some(old_owner) = old_spender {405 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(406 collection.id,407 token,408 sender.clone(),409 old_owner.clone(),410 0,411 ));412 }413 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(414 collection.id,415 token,416 sender.clone(),417 spender.clone(),418 1,419 ));420 }421 } else {422 let old_spender = <Allowance<T>>::take((collection.id, token));423 if !assume_implicit_eth {424 // In ERC721 there is only one possible approved user of token, so we set425 // approved user to zero address426 collection.log_infallible(ERC721Events::Approval {427 owner: *sender.as_eth(),428 approved: H160::default(),429 token_id: token.into(),430 });431 }432 // In Unique chain, any token can have any amount of approved users, so we need to433 // set allowance of old owner to 0434 if let Some(old_spender) = old_spender {435 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(436 collection.id,437 token,438 sender.clone(),439 old_spender.clone(),440 0,441 ));442 }443 }444 }445446 pub fn set_allowance(447 collection: &NonfungibleHandle<T>,448 sender: &T::CrossAccountId,449 token: TokenId,450 spender: Option<&T::CrossAccountId>,451 ) -> DispatchResult {452 if collection.access == AccessMode::WhiteList {453 collection.check_allowlist(&sender)?;454 if let Some(spender) = spender {455 collection.check_allowlist(&spender)?;456 }457 }458459 if let Some(spender) = spender {460 <PalletCommon<T>>::ensure_correct_receiver(spender)?;461 }462 let token_data =463 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;464 if &token_data.owner != sender {465 ensure!(466 collection.ignores_owned_amount(sender)?,467 <CommonError<T>>::CantApproveMoreThanOwned468 );469 }470471 // =========472473 Self::set_allowance_unchecked(collection, sender, token, spender, false);474 Ok(())475 }476477 pub fn transfer_from(478 collection: &NonfungibleHandle<T>,479 spender: &T::CrossAccountId,480 from: &T::CrossAccountId,481 to: &T::CrossAccountId,482 token: TokenId,483 ) -> DispatchResult {484 if spender.conv_eq(from) {485 return Self::transfer(collection, from, to, token);486 }487 if collection.access == AccessMode::WhiteList {488 // `from`, `to` checked in [`transfer`]489 collection.check_allowlist(spender)?;490 }491492 if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {493 ensure!(494 collection.ignores_allowance(spender)?,495 <CommonError<T>>::TokenValueNotEnough496 );497 }498499 // =========500501 Self::transfer(collection, &from, to, token)?;502 // Allowance is reset in [`transfer`]503 Ok(())504 }505506 pub fn burn_from(507 collection: &NonfungibleHandle<T>,508 spender: &T::CrossAccountId,509 from: &T::CrossAccountId,510 token: TokenId,511 ) -> DispatchResult {512 if spender.conv_eq(from) {513 return Self::burn(collection, from, token);514 }515 if collection.access == AccessMode::WhiteList {516 // `from` checked in [`burn`]517 collection.check_allowlist(spender)?;518 }519520 if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {521 ensure!(522 collection.ignores_allowance(spender)?,523 <CommonError<T>>::TokenValueNotEnough524 );525 }526527 // =========528529 Self::burn(collection, &from, token)530 }531532 pub fn set_variable_metadata(533 collection: &NonfungibleHandle<T>,534 sender: &T::CrossAccountId,535 token: TokenId,536 data: Vec<u8>,537 ) -> DispatchResult {538 ensure!(539 data.len() as u32 <= CUSTOM_DATA_LIMIT,540 <CommonError<T>>::TokenVariableDataLimitExceeded541 );542 let token_data =543 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;544 collection.check_can_update_meta(sender, &token_data.owner)?;545546 collection.consume_sstore()?;547548 // =========549550 <TokenData<T>>::insert(551 (collection.id, token),552 ItemData {553 variable_data: data,554 ..token_data555 },556 );557 Ok(())558 }559560 /// Delegated to `create_multiple_items`561 pub fn create_item(562 collection: &NonfungibleHandle<T>,563 sender: &T::CrossAccountId,564 data: CreateItemData<T>,565 ) -> DispatchResult {566 Self::create_multiple_items(collection, sender, vec![data])567 }568}pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -3,9 +3,7 @@
use sp_std::collections::btree_map::BTreeMap;
use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};
use nft_data_structs::TokenId;
-use pallet_common::{
- CommonCollectionOperations, CommonWeightInfo, account::CrossAccountId, with_weight,
-};
+use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
use sp_std::vec::Vec;
@@ -196,7 +194,7 @@
}
fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
- <Owned<T>>::iter_prefix((self.id, account.as_sub()))
+ <Owned<T>>::iter_prefix((self.id, account))
.map(|(id, _)| id)
.collect()
}
@@ -224,11 +222,11 @@
}
fn account_balance(&self, account: T::CrossAccountId) -> u32 {
- <AccountBalance<T>>::get((self.id, account.as_sub()))
+ <AccountBalance<T>>::get((self.id, account))
}
fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {
- <Balance<T>>::get((self.id, token, account.as_sub()))
+ <Balance<T>>::get((self.id, token, account))
}
fn allowance(
@@ -237,6 +235,6 @@
spender: T::CrossAccountId,
token: TokenId,
) -> u128 {
- <Allowance<T>>::get((self.id, token, sender.as_sub(), spender))
+ <Allowance<T>>::get((self.id, token, sender, spender))
}
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -83,7 +83,7 @@
pub(super) type Owned<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
Key<Twox64Concat, TokenId>,
),
Value = bool,
@@ -95,7 +95,7 @@
Key = (
Key<Twox64Concat, CollectionId>,
// Owner
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = u32,
QueryKind = ValueQuery,
@@ -107,7 +107,7 @@
Key<Twox64Concat, CollectionId>,
Key<Twox64Concat, TokenId>,
// Owner
- Key<Blake2_128Concat, T::AccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>,
),
Value = u128,
QueryKind = ValueQuery,
@@ -119,7 +119,7 @@
Key<Twox64Concat, CollectionId>,
Key<Twox64Concat, TokenId>,
// Owner
- Key<Blake2_128, T::AccountId>,
+ Key<Blake2_128, T::CrossAccountId>,
// Spender
Key<Blake2_128Concat, T::CrossAccountId>,
),
@@ -206,18 +206,18 @@
if total_supply == 0 {
// Ensure user actually owns this amount
ensure!(
- <Balance<T>>::get((collection.id, token, owner.as_sub())) == amount,
+ <Balance<T>>::get((collection.id, token, owner)) == amount,
<CommonError<T>>::TokenValueTooLow
);
- let account_balance = <AccountBalance<T>>::get((collection.id, owner.as_sub()))
+ let account_balance = <AccountBalance<T>>::get((collection.id, owner))
.checked_sub(1)
// Should not occur
.ok_or(ArithmeticError::Underflow)?;
// =========
- <Owned<T>>::remove((collection.id, owner.as_sub(), token));
- <AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);
+ <Owned<T>>::remove((collection.id, owner, token));
+ <AccountBalance<T>>::insert((collection.id, owner), account_balance);
Self::burn_token(collection, token)?;
<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
collection.id,
@@ -228,11 +228,11 @@
return Ok(());
}
- let balance = <Balance<T>>::get((collection.id, token, owner.as_sub()))
+ let balance = <Balance<T>>::get((collection.id, token, owner))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
let account_balance = if balance == 0 {
- <AccountBalance<T>>::get((collection.id, owner.as_sub()))
+ <AccountBalance<T>>::get((collection.id, owner))
.checked_sub(1)
// Should not occur
.ok_or(ArithmeticError::Underflow)?
@@ -243,11 +243,11 @@
// =========
if balance == 0 {
- <Owned<T>>::remove((collection.id, owner.as_sub(), token));
- <Balance<T>>::remove((collection.id, token, owner.as_sub()));
- <AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);
+ <Owned<T>>::remove((collection.id, owner, token));
+ <Balance<T>>::remove((collection.id, token, owner));
+ <AccountBalance<T>>::insert((collection.id, owner), account_balance);
} else {
- <Balance<T>>::insert((collection.id, token, owner.as_sub()), balance);
+ <Balance<T>>::insert((collection.id, token, owner), balance);
}
<TotalSupply<T>>::insert((collection.id, token), total_supply);
// TODO: ERC20 transfer event
@@ -278,13 +278,13 @@
}
<PalletCommon<T>>::ensure_correct_receiver(to)?;
- let balance_from = <Balance<T>>::get((collection.id, token, from.as_sub()))
+ let balance_from = <Balance<T>>::get((collection.id, token, from))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
let mut create_target = false;
let from_to_differ = from != to;
let balance_to = if from != to {
- let old_balance = <Balance<T>>::get((collection.id, token, to.as_sub()));
+ let old_balance = <Balance<T>>::get((collection.id, token, to));
if old_balance == 0 {
create_target = true;
}
@@ -299,7 +299,7 @@
let account_balance_from = if balance_from == 0 {
Some(
- <AccountBalance<T>>::get((collection.id, from.as_sub()))
+ <AccountBalance<T>>::get((collection.id, from))
.checked_sub(1)
// Should not occur
.ok_or(ArithmeticError::Underflow)?,
@@ -310,7 +310,7 @@
// Account data is created in token, AccountBalance should be increased
// But only if from != to as we shouldn't check overflow in this case
let account_balance_to = if create_target && from_to_differ {
- let account_balance_to = <AccountBalance<T>>::get((collection.id, to.as_sub()))
+ let account_balance_to = <AccountBalance<T>>::get((collection.id, to))
.checked_add(1)
.ok_or(ArithmeticError::Overflow)?;
ensure!(
@@ -328,18 +328,18 @@
if let Some(balance_to) = balance_to {
// from != to
if balance_from == 0 {
- <Balance<T>>::remove((collection.id, token, from.as_sub()));
+ <Balance<T>>::remove((collection.id, token, from));
} else {
- <Balance<T>>::insert((collection.id, token, from.as_sub()), balance_from);
+ <Balance<T>>::insert((collection.id, token, from), balance_from);
}
- <Balance<T>>::insert((collection.id, token, to.as_sub()), balance_to);
+ <Balance<T>>::insert((collection.id, token, to), balance_to);
if let Some(account_balance_from) = account_balance_from {
- <AccountBalance<T>>::insert((collection.id, from.as_sub()), account_balance_from);
- <Owned<T>>::remove((collection.id, from.as_sub(), token));
+ <AccountBalance<T>>::insert((collection.id, from), account_balance_from);
+ <Owned<T>>::remove((collection.id, from, token));
}
if let Some(account_balance_to) = account_balance_to {
- <AccountBalance<T>>::insert((collection.id, to.as_sub()), account_balance_to);
- <Owned<T>>::insert((collection.id, to.as_sub(), token), true);
+ <AccountBalance<T>>::insert((collection.id, to), account_balance_to);
+ <Owned<T>>::insert((collection.id, to, token), true);
}
}
@@ -412,8 +412,8 @@
for data in &data {
for (owner, _) in &data.users {
let balance = balances
- .entry(owner.as_sub())
- .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner.as_sub())));
+ .entry(owner)
+ .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));
*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;
ensure!(
@@ -444,8 +444,8 @@
if amount == 0 {
continue;
}
- <Balance<T>>::insert((collection.id, token_id, user.as_sub()), amount);
- <Owned<T>>::insert((collection.id, user.as_sub(), TokenId(token_id)), true);
+ <Balance<T>>::insert((collection.id, token_id, &user), amount);
+ <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);
// TODO: ERC20 transfer event
<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
collection.id,
@@ -465,7 +465,7 @@
token: TokenId,
amount: u128,
) {
- <Allowance<T>>::insert((collection.id, token, sender.as_sub(), spender), amount);
+ <Allowance<T>>::insert((collection.id, token, sender, spender), amount);
// TODO: ERC20 approval event
<PalletCommon<T>>::deposit_event(CommonEvent::Approved(
collection.id,
@@ -490,7 +490,7 @@
<PalletCommon<T>>::ensure_correct_receiver(spender)?;
- if <Balance<T>>::get((collection.id, token, sender.as_sub())) < amount {
+ if <Balance<T>>::get((collection.id, token, sender)) < amount {
ensure!(
collection.ignores_owned_amount(sender)? && Self::token_exists(collection, token),
<CommonError<T>>::CantApproveMoreThanOwned
@@ -511,7 +511,7 @@
token: TokenId,
amount: u128,
) -> DispatchResult {
- if spender == from {
+ if spender.conv_eq(from) {
return Self::transfer(collection, from, to, token, amount);
}
if collection.access == AccessMode::WhiteList {
@@ -519,8 +519,8 @@
collection.check_allowlist(spender)?;
}
- let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))
- .checked_sub(amount);
+ let allowance =
+ <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
collection.ignores_allowance(spender)?,
@@ -544,7 +544,7 @@
token: TokenId,
amount: u128,
) -> DispatchResult {
- if spender == from {
+ if spender.conv_eq(from) {
return Self::burn(collection, from, token, amount);
}
if collection.access == AccessMode::WhiteList {
@@ -552,8 +552,8 @@
collection.check_allowlist(spender)?;
}
- let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))
- .checked_sub(amount);
+ let allowance =
+ <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);
if allowance.is_none() {
ensure!(
collection.ignores_allowance(spender)?,
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -30,8 +30,8 @@
/// Used for ethereum integration
fn eth_contract_code(account: H160) -> Option<Vec<u8>>;
- fn adminlist(collection: CollectionId) -> Vec<AccountId>;
- fn allowlist(collection: CollectionId) -> Vec<AccountId>;
+ fn adminlist(collection: CollectionId) -> Vec<CrossAccountId>;
+ fn allowlist(collection: CollectionId) -> Vec<CrossAccountId>;
fn last_token_id(collection: CollectionId) -> TokenId;
}
}
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -1033,12 +1033,14 @@
}
fn eth_contract_code(account: H160) -> Option<Vec<u8>> {
- <pallet_nft::NftErcSupport<Runtime>>::get_code(&account).or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account)).or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))
+ <pallet_nft::NftErcSupport<Runtime>>::get_code(&account)
+ .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))
+ .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))
}
- fn adminlist(collection: CollectionId) -> Vec<AccountId> {
+ fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {
<pallet_nft::Pallet<Runtime>>::adminlist(collection)
}
- fn allowlist(collection: CollectionId) -> Vec<AccountId> {
+ fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {
<pallet_nft::Pallet<Runtime>>::allowlist(collection)
}
fn last_token_id(collection: CollectionId) -> TokenId {