difftreelog
fix sponsoring token ownership check
in: master
3 files changed
pallets/fungible/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::Deref;4use frame_support::{ensure};5use nft_data_structs::{AccessMode, Collection, CollectionId, TokenId};6use pallet_common::{7 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,8};9use sp_core::H160;10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};1213pub use pallet::*;1415use crate::erc::ERC20Events;16#[cfg(feature = "runtime-benchmarks")]17pub mod benchmarking;18pub mod common;19pub mod erc;20pub mod weights;2122pub type CreateItemData<T> = (<T as pallet_common::Config>::CrossAccountId, u128);23pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2425#[frame_support::pallet]26pub mod pallet {27 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};28 use nft_data_structs::CollectionId;29 use super::weights::WeightInfo;3031 #[pallet::error]32 pub enum Error<T> {33 /// Not Fungible item data used to mint in Fungible collection.34 NotFungibleDataUsedToMintFungibleCollectionToken,35 /// Not default id passed as TokenId argument36 FungibleItemsHaveNoId,37 /// Tried to set data for fungible item38 FungibleItemsHaveData,39 }4041 #[pallet::config]42 pub trait Config: frame_system::Config + pallet_common::Config {43 type WeightInfo: WeightInfo;44 }4546 #[pallet::pallet]47 #[pallet::generate_store(pub(super) trait Store)]48 pub struct Pallet<T>(_);4950 #[pallet::storage]51 pub(super) type TotalSupply<T: Config> =52 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;5354 #[pallet::storage]55 pub(super) type Balance<T: Config> = StorageNMap<56 Key = (57 Key<Twox64Concat, CollectionId>,58 Key<Blake2_128Concat, T::CrossAccountId>,59 ),60 Value = u128,61 QueryKind = ValueQuery,62 >;6364 #[pallet::storage]65 pub(super) type Allowance<T: Config> = StorageNMap<66 Key = (67 Key<Twox64Concat, CollectionId>,68 Key<Blake2_128, T::CrossAccountId>,69 Key<Blake2_128Concat, T::CrossAccountId>,70 ),71 Value = u128,72 QueryKind = ValueQuery,73 >;74}7576pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);77impl<T: Config> FungibleHandle<T> {78 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {79 Self(inner)80 }81 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {82 self.083 }84}85impl<T: Config> Deref for FungibleHandle<T> {86 type Target = pallet_common::CollectionHandle<T>;8788 fn deref(&self) -> &Self::Target {89 &self.090 }91}9293impl<T: Config> Pallet<T> {94 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {95 PalletCommon::init_collection(data)96 }97 pub fn destroy_collection(98 collection: FungibleHandle<T>,99 sender: &T::CrossAccountId,100 ) -> DispatchResult {101 let id = collection.id;102103 // =========104105 PalletCommon::destroy_collection(collection.0, sender)?;106107 <TotalSupply<T>>::remove(id);108 <Balance<T>>::remove_prefix((id,), None);109 <Allowance<T>>::remove_prefix((id,), None);110 Ok(())111 }112113 pub fn burn(114 collection: &FungibleHandle<T>,115 owner: &T::CrossAccountId,116 amount: u128,117 ) -> DispatchResult {118 let total_supply = <TotalSupply<T>>::get(collection.id)119 .checked_sub(amount)120 .ok_or(<CommonError<T>>::TokenValueTooLow)?;121122 let balance = <Balance<T>>::get((collection.id, owner))123 .checked_sub(amount)124 .ok_or(<CommonError<T>>::TokenValueTooLow)?;125126 if collection.access == AccessMode::AllowList {127 collection.check_allowlist(owner)?;128 }129130 // =========131132 if balance == 0 {133 <Balance<T>>::remove((collection.id, owner));134 } else {135 <Balance<T>>::insert((collection.id, owner), balance);136 }137 <TotalSupply<T>>::insert(collection.id, total_supply);138139 collection.log_infallible(ERC20Events::Transfer {140 from: *owner.as_eth(),141 to: H160::default(),142 value: amount.into(),143 });144 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(145 collection.id,146 TokenId::default(),147 owner.clone(),148 amount,149 ));150 Ok(())151 }152153 pub fn transfer(154 collection: &FungibleHandle<T>,155 from: &T::CrossAccountId,156 to: &T::CrossAccountId,157 amount: u128,158 ) -> DispatchResult {159 ensure!(160 collection.limits.transfers_enabled(),161 <CommonError<T>>::TransferNotAllowed,162 );163164 if collection.access == AccessMode::AllowList {165 collection.check_allowlist(from)?;166 collection.check_allowlist(to)?;167 }168 <PalletCommon<T>>::ensure_correct_receiver(to)?;169170 let balance_from = <Balance<T>>::get((collection.id, from))171 .checked_sub(amount)172 .ok_or(<CommonError<T>>::TokenValueTooLow)?;173 let balance_to = if from != to {174 Some(175 <Balance<T>>::get((collection.id, to))176 .checked_add(amount)177 .ok_or(ArithmeticError::Overflow)?,178 )179 } else {180 None181 };182183 collection.consume_sstore()?;184 collection.consume_sstore()?;185 collection.consume_log(2, 32)?;186 collection.consume_sstore()?;187188 // =========189190 if let Some(balance_to) = balance_to {191 // from != to192 if balance_from == 0 {193 <Balance<T>>::remove((collection.id, from));194 } else {195 <Balance<T>>::insert((collection.id, from), balance_from);196 }197 <Balance<T>>::insert((collection.id, to), balance_to);198 }199200 collection.log_infallible(ERC20Events::Transfer {201 from: *from.as_eth(),202 to: *to.as_eth(),203 value: amount.into(),204 });205 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(206 collection.id,207 TokenId::default(),208 from.clone(),209 to.clone(),210 amount,211 ));212 Ok(())213 }214215 pub fn create_multiple_items(216 collection: &FungibleHandle<T>,217 sender: &T::CrossAccountId,218 data: Vec<CreateItemData<T>>,219 ) -> DispatchResult {220 let unrestricted_minting = collection.is_owner_or_admin(sender)?;221 if !unrestricted_minting {222 ensure!(223 collection.mint_mode,224 <CommonError<T>>::PublicMintingNotAllowed225 );226 collection.check_allowlist(sender)?;227228 for (owner, _) in data.iter() {229 collection.check_allowlist(owner)?;230 }231 }232233 let mut balances = BTreeMap::new();234235 let total_supply = data236 .iter()237 .map(|u| u.1)238 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {239 acc.checked_add(v)240 })241 .ok_or(ArithmeticError::Overflow)?;242243 for (user, amount) in data.into_iter() {244 collection.consume_sload()?;245 let balance = balances246 .entry(user.clone())247 .or_insert_with(|| <Balance<T>>::get((collection.id, user)));248 *balance = (*balance)249 .checked_add(amount)250 .ok_or(ArithmeticError::Overflow)?;251 }252253 collection.consume_sstore()?;254 for _ in &balances {255 collection.consume_sstore()?;256 collection.consume_log(2, 32)?;257 collection.consume_sstore()?;258 }259260 // =========261262 <TotalSupply<T>>::insert(collection.id, total_supply);263 for (user, amount) in balances {264 <Balance<T>>::insert((collection.id, &user), amount);265266 collection.log_infallible(ERC20Events::Transfer {267 from: H160::default(),268 to: *user.as_eth(),269 value: amount.into(),270 });271 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(272 collection.id,273 TokenId::default(),274 user.clone(),275 amount,276 ));277 }278279 Ok(())280 }281282 fn set_allowance_unchecked(283 collection: &FungibleHandle<T>,284 owner: &T::CrossAccountId,285 spender: &T::CrossAccountId,286 amount: u128,287 ) {288 <Allowance<T>>::insert((collection.id, owner, spender), amount);289290 collection.log_infallible(ERC20Events::Approval {291 owner: *owner.as_eth(),292 spender: *spender.as_eth(),293 value: amount.into(),294 });295 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(296 collection.id,297 TokenId(0),298 owner.clone(),299 spender.clone(),300 amount,301 ));302 }303304 pub fn set_allowance(305 collection: &FungibleHandle<T>,306 owner: &T::CrossAccountId,307 spender: &T::CrossAccountId,308 amount: u128,309 ) -> DispatchResult {310 if collection.access == AccessMode::AllowList {311 collection.check_allowlist(&owner)?;312 collection.check_allowlist(&spender)?;313 }314315 if <Balance<T>>::get((collection.id, owner)) < amount {316 ensure!(317 collection.ignores_owned_amount(owner)?,318 <CommonError<T>>::CantApproveMoreThanOwned319 );320 }321322 // =========323324 Self::set_allowance_unchecked(collection, owner, spender, amount);325 Ok(())326 }327328 pub fn transfer_from(329 collection: &FungibleHandle<T>,330 spender: &T::CrossAccountId,331 from: &T::CrossAccountId,332 to: &T::CrossAccountId,333 amount: u128,334 ) -> DispatchResult {335 if spender.conv_eq(from) {336 return Self::transfer(collection, from, to, amount);337 }338 if collection.access == AccessMode::AllowList {339 // `from`, `to` checked in [`transfer`]340 collection.check_allowlist(spender)?;341 }342343 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);344 if allowance.is_none() {345 ensure!(346 collection.ignores_allowance(spender)?,347 <CommonError<T>>::TokenValueNotEnough348 );349 }350351 // =========352353 Self::transfer(collection, from, to, amount)?;354 if let Some(allowance) = allowance {355 Self::set_allowance_unchecked(collection, from, spender, allowance);356 }357 Ok(())358 }359360 pub fn burn_from(361 collection: &FungibleHandle<T>,362 spender: &T::CrossAccountId,363 from: &T::CrossAccountId,364 amount: u128,365 ) -> DispatchResult {366 if spender.conv_eq(from) {367 return Self::burn(collection, from, amount);368 }369 if collection.access == AccessMode::AllowList {370 // `from` checked in [`burn`]371 collection.check_allowlist(spender)?;372 }373374 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);375 if allowance.is_none() {376 ensure!(377 collection.ignores_allowance(spender)?,378 <CommonError<T>>::TokenValueNotEnough379 );380 }381382 // =========383384 Self::burn(collection, from, amount)?;385 if let Some(allowance) = allowance {386 Self::set_allowance_unchecked(collection, from, spender, allowance);387 }388 Ok(())389 }390391 /// Delegated to `create_multiple_items`392 pub fn create_item(393 collection: &FungibleHandle<T>,394 sender: &T::CrossAccountId,395 data: CreateItemData<T>,396 ) -> DispatchResult {397 Self::create_multiple_items(collection, sender, vec![data])398 }399}1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::Deref;4use frame_support::{ensure};5use nft_data_structs::{AccessMode, Collection, CollectionId, TokenId};6use pallet_common::{7 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,8};9use sp_core::H160;10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};1213pub use pallet::*;1415use crate::erc::ERC20Events;16#[cfg(feature = "runtime-benchmarks")]17pub mod benchmarking;18pub mod common;19pub mod erc;20pub mod weights;2122pub type CreateItemData<T> = (<T as pallet_common::Config>::CrossAccountId, u128);23pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2425#[frame_support::pallet]26pub mod pallet {27 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};28 use nft_data_structs::CollectionId;29 use super::weights::WeightInfo;3031 #[pallet::error]32 pub enum Error<T> {33 /// Not Fungible item data used to mint in Fungible collection.34 NotFungibleDataUsedToMintFungibleCollectionToken,35 /// Not default id passed as TokenId argument36 FungibleItemsHaveNoId,37 /// Tried to set data for fungible item38 FungibleItemsHaveData,39 }4041 #[pallet::config]42 pub trait Config: frame_system::Config + pallet_common::Config {43 type WeightInfo: WeightInfo;44 }4546 #[pallet::pallet]47 #[pallet::generate_store(pub(super) trait Store)]48 pub struct Pallet<T>(_);4950 #[pallet::storage]51 pub(super) type TotalSupply<T: Config> =52 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;5354 #[pallet::storage]55 pub type Balance<T: Config> = StorageNMap<56 Key = (57 Key<Twox64Concat, CollectionId>,58 Key<Blake2_128Concat, T::CrossAccountId>,59 ),60 Value = u128,61 QueryKind = ValueQuery,62 >;6364 #[pallet::storage]65 pub(super) type Allowance<T: Config> = StorageNMap<66 Key = (67 Key<Twox64Concat, CollectionId>,68 Key<Blake2_128, T::CrossAccountId>,69 Key<Blake2_128Concat, T::CrossAccountId>,70 ),71 Value = u128,72 QueryKind = ValueQuery,73 >;74}7576pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);77impl<T: Config> FungibleHandle<T> {78 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {79 Self(inner)80 }81 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {82 self.083 }84}85impl<T: Config> Deref for FungibleHandle<T> {86 type Target = pallet_common::CollectionHandle<T>;8788 fn deref(&self) -> &Self::Target {89 &self.090 }91}9293impl<T: Config> Pallet<T> {94 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {95 PalletCommon::init_collection(data)96 }97 pub fn destroy_collection(98 collection: FungibleHandle<T>,99 sender: &T::CrossAccountId,100 ) -> DispatchResult {101 let id = collection.id;102103 // =========104105 PalletCommon::destroy_collection(collection.0, sender)?;106107 <TotalSupply<T>>::remove(id);108 <Balance<T>>::remove_prefix((id,), None);109 <Allowance<T>>::remove_prefix((id,), None);110 Ok(())111 }112113 pub fn burn(114 collection: &FungibleHandle<T>,115 owner: &T::CrossAccountId,116 amount: u128,117 ) -> DispatchResult {118 let total_supply = <TotalSupply<T>>::get(collection.id)119 .checked_sub(amount)120 .ok_or(<CommonError<T>>::TokenValueTooLow)?;121122 let balance = <Balance<T>>::get((collection.id, owner))123 .checked_sub(amount)124 .ok_or(<CommonError<T>>::TokenValueTooLow)?;125126 if collection.access == AccessMode::AllowList {127 collection.check_allowlist(owner)?;128 }129130 // =========131132 if balance == 0 {133 <Balance<T>>::remove((collection.id, owner));134 } else {135 <Balance<T>>::insert((collection.id, owner), balance);136 }137 <TotalSupply<T>>::insert(collection.id, total_supply);138139 collection.log_infallible(ERC20Events::Transfer {140 from: *owner.as_eth(),141 to: H160::default(),142 value: amount.into(),143 });144 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(145 collection.id,146 TokenId::default(),147 owner.clone(),148 amount,149 ));150 Ok(())151 }152153 pub fn transfer(154 collection: &FungibleHandle<T>,155 from: &T::CrossAccountId,156 to: &T::CrossAccountId,157 amount: u128,158 ) -> DispatchResult {159 ensure!(160 collection.limits.transfers_enabled(),161 <CommonError<T>>::TransferNotAllowed,162 );163164 if collection.access == AccessMode::AllowList {165 collection.check_allowlist(from)?;166 collection.check_allowlist(to)?;167 }168 <PalletCommon<T>>::ensure_correct_receiver(to)?;169170 let balance_from = <Balance<T>>::get((collection.id, from))171 .checked_sub(amount)172 .ok_or(<CommonError<T>>::TokenValueTooLow)?;173 let balance_to = if from != to {174 Some(175 <Balance<T>>::get((collection.id, to))176 .checked_add(amount)177 .ok_or(ArithmeticError::Overflow)?,178 )179 } else {180 None181 };182183 collection.consume_sstore()?;184 collection.consume_sstore()?;185 collection.consume_log(2, 32)?;186 collection.consume_sstore()?;187188 // =========189190 if let Some(balance_to) = balance_to {191 // from != to192 if balance_from == 0 {193 <Balance<T>>::remove((collection.id, from));194 } else {195 <Balance<T>>::insert((collection.id, from), balance_from);196 }197 <Balance<T>>::insert((collection.id, to), balance_to);198 }199200 collection.log_infallible(ERC20Events::Transfer {201 from: *from.as_eth(),202 to: *to.as_eth(),203 value: amount.into(),204 });205 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(206 collection.id,207 TokenId::default(),208 from.clone(),209 to.clone(),210 amount,211 ));212 Ok(())213 }214215 pub fn create_multiple_items(216 collection: &FungibleHandle<T>,217 sender: &T::CrossAccountId,218 data: Vec<CreateItemData<T>>,219 ) -> DispatchResult {220 let unrestricted_minting = collection.is_owner_or_admin(sender)?;221 if !unrestricted_minting {222 ensure!(223 collection.mint_mode,224 <CommonError<T>>::PublicMintingNotAllowed225 );226 collection.check_allowlist(sender)?;227228 for (owner, _) in data.iter() {229 collection.check_allowlist(owner)?;230 }231 }232233 let mut balances = BTreeMap::new();234235 let total_supply = data236 .iter()237 .map(|u| u.1)238 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {239 acc.checked_add(v)240 })241 .ok_or(ArithmeticError::Overflow)?;242243 for (user, amount) in data.into_iter() {244 collection.consume_sload()?;245 let balance = balances246 .entry(user.clone())247 .or_insert_with(|| <Balance<T>>::get((collection.id, user)));248 *balance = (*balance)249 .checked_add(amount)250 .ok_or(ArithmeticError::Overflow)?;251 }252253 collection.consume_sstore()?;254 for _ in &balances {255 collection.consume_sstore()?;256 collection.consume_log(2, 32)?;257 collection.consume_sstore()?;258 }259260 // =========261262 <TotalSupply<T>>::insert(collection.id, total_supply);263 for (user, amount) in balances {264 <Balance<T>>::insert((collection.id, &user), amount);265266 collection.log_infallible(ERC20Events::Transfer {267 from: H160::default(),268 to: *user.as_eth(),269 value: amount.into(),270 });271 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(272 collection.id,273 TokenId::default(),274 user.clone(),275 amount,276 ));277 }278279 Ok(())280 }281282 fn set_allowance_unchecked(283 collection: &FungibleHandle<T>,284 owner: &T::CrossAccountId,285 spender: &T::CrossAccountId,286 amount: u128,287 ) {288 <Allowance<T>>::insert((collection.id, owner, spender), amount);289290 collection.log_infallible(ERC20Events::Approval {291 owner: *owner.as_eth(),292 spender: *spender.as_eth(),293 value: amount.into(),294 });295 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(296 collection.id,297 TokenId(0),298 owner.clone(),299 spender.clone(),300 amount,301 ));302 }303304 pub fn set_allowance(305 collection: &FungibleHandle<T>,306 owner: &T::CrossAccountId,307 spender: &T::CrossAccountId,308 amount: u128,309 ) -> DispatchResult {310 if collection.access == AccessMode::AllowList {311 collection.check_allowlist(&owner)?;312 collection.check_allowlist(&spender)?;313 }314315 if <Balance<T>>::get((collection.id, owner)) < amount {316 ensure!(317 collection.ignores_owned_amount(owner)?,318 <CommonError<T>>::CantApproveMoreThanOwned319 );320 }321322 // =========323324 Self::set_allowance_unchecked(collection, owner, spender, amount);325 Ok(())326 }327328 pub fn transfer_from(329 collection: &FungibleHandle<T>,330 spender: &T::CrossAccountId,331 from: &T::CrossAccountId,332 to: &T::CrossAccountId,333 amount: u128,334 ) -> DispatchResult {335 if spender.conv_eq(from) {336 return Self::transfer(collection, from, to, amount);337 }338 if collection.access == AccessMode::AllowList {339 // `from`, `to` checked in [`transfer`]340 collection.check_allowlist(spender)?;341 }342343 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);344 if allowance.is_none() {345 ensure!(346 collection.ignores_allowance(spender)?,347 <CommonError<T>>::TokenValueNotEnough348 );349 }350351 // =========352353 Self::transfer(collection, from, to, amount)?;354 if let Some(allowance) = allowance {355 Self::set_allowance_unchecked(collection, from, spender, allowance);356 }357 Ok(())358 }359360 pub fn burn_from(361 collection: &FungibleHandle<T>,362 spender: &T::CrossAccountId,363 from: &T::CrossAccountId,364 amount: u128,365 ) -> DispatchResult {366 if spender.conv_eq(from) {367 return Self::burn(collection, from, amount);368 }369 if collection.access == AccessMode::AllowList {370 // `from` checked in [`burn`]371 collection.check_allowlist(spender)?;372 }373374 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);375 if allowance.is_none() {376 ensure!(377 collection.ignores_allowance(spender)?,378 <CommonError<T>>::TokenValueNotEnough379 );380 }381382 // =========383384 Self::burn(collection, from, amount)?;385 if let Some(allowance) = allowance {386 Self::set_allowance_unchecked(collection, from, spender, allowance);387 }388 Ok(())389 }390391 /// Delegated to `create_multiple_items`392 pub fn create_item(393 collection: &FungibleHandle<T>,394 sender: &T::CrossAccountId,395 data: CreateItemData<T>,396 ) -> DispatchResult {397 Self::create_multiple_items(collection, sender, vec![data])398 }399}pallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth--- a/pallets/nft/src/eth/sponsoring.rs
+++ b/pallets/nft/src/eth/sponsoring.rs
@@ -10,7 +10,7 @@
use core::convert::TryInto;
use nft_data_structs::TokenId;
use up_evm_mapping::EvmBackwardsAddressMapping;
-use pallet_evm::AddressMapping;
+use pallet_common::account::CrossAccountId;
use pallet_nonfungible::erc::{UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721Call};
use pallet_fungible::erc::{UniqueFungibleCall, ERC20Call};
@@ -23,7 +23,7 @@
let sponsor = collection.sponsorship.sponsor()?.clone();
let sponsor =
<T as pallet_common::Config>::EvmBackwardsAddressMapping::from_account_id(sponsor);
- let who = <T as pallet_common::Config>::EvmAddressMapping::into_account_id(*who);
+ let who = T::CrossAccountId::from_eth(*who);
let (method_id, mut reader) = AbiReader::new_call(&call.1).ok()?;
match &collection.mode {
crate::CollectionMode::NFT => {
@@ -31,14 +31,19 @@
match call {
UniqueNFTCall::ERC721UniqueExtensions(
ERC721UniqueExtensionsCall::Transfer { token_id, .. },
- )
- | UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, .. }) => {
+ ) => {
let token_id: TokenId = token_id.try_into().ok()?;
withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
}
+ UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, from, .. }) => {
+ let token_id: TokenId = token_id.try_into().ok()?;
+ let from = T::CrossAccountId::from_eth(from);
+ withdraw_transfer::<T>(&collection, &from, &token_id).map(|()| sponsor)
+ }
UniqueNFTCall::ERC721(ERC721Call::Approve { token_id, .. }) => {
let token_id: TokenId = token_id.try_into().ok()?;
- withdraw_approve::<T>(&collection, &who, &token_id).map(|()| sponsor)
+ withdraw_approve::<T>(&collection, who.as_sub(), &token_id)
+ .map(|()| sponsor)
}
_ => None,
}
@@ -47,12 +52,17 @@
let call = UniqueFungibleCall::parse(method_id, &mut reader).ok()??;
#[allow(clippy::single_match)]
match call {
- UniqueFungibleCall::ERC20(
- ERC20Call::Transfer { .. } | ERC20Call::TransferFrom { .. },
- ) => withdraw_transfer::<T>(&collection, &who, &TokenId::default())
- .map(|()| sponsor),
+ UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {
+ withdraw_transfer::<T>(&collection, &who, &TokenId::default())
+ .map(|()| sponsor)
+ }
+ UniqueFungibleCall::ERC20(ERC20Call::TransferFrom { from, .. }) => {
+ let from = T::CrossAccountId::from_eth(from);
+ withdraw_transfer::<T>(&collection, &from, &TokenId::default())
+ .map(|()| sponsor)
+ }
UniqueFungibleCall::ERC20(ERC20Call::Approve { .. }) => {
- withdraw_approve::<T>(&collection, &who, &TokenId::default())
+ withdraw_approve::<T>(&collection, who.as_sub(), &TokenId::default())
.map(|()| sponsor)
}
_ => None,
pallets/nft/src/sponsorship.rsdiffbeforeafterboth--- a/pallets/nft/src/sponsorship.rs
+++ b/pallets/nft/src/sponsorship.rs
@@ -10,25 +10,38 @@
storage::{StorageMap, StorageDoubleMap, StorageNMap},
};
use nft_data_structs::{
- CollectionId, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, NFT_SPONSOR_TRANSFER_TIMEOUT,
- REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, TokenId,
+ CollectionId, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MetaUpdatePermission,
+ NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, TokenId,
};
use pallet_common::{CollectionHandle};
use pallet_common::account::CrossAccountId;
pub fn withdraw_transfer<T: Config>(
collection: &CollectionHandle<T>,
- who: &T::AccountId,
+ who: &T::CrossAccountId,
item_id: &TokenId,
) -> Option<()> {
// preliminary sponsoring correctness check
- if !((pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner).as_sub() == who)
- || (pallet_refungible::Owned::<T>::get((
- collection.id,
- T::CrossAccountId::from_sub(who.clone()),
- item_id,
- ))) {
- return None;
+ match collection.mode {
+ CollectionMode::NFT => {
+ let owner = pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner;
+ if !owner.conv_eq(who) {
+ return None;
+ }
+ }
+ CollectionMode::Fungible(_) => {
+ if item_id != &TokenId::default() {
+ return None;
+ }
+ if <pallet_fungible::Balance<T>>::get((collection.id, who)) == 0 {
+ return None;
+ }
+ }
+ CollectionMode::ReFungible => {
+ if !<pallet_refungible::Owned<T>>::get((collection.id, who, item_id)) {
+ return None;
+ }
+ }
}
// sponsor timeout
@@ -43,9 +56,11 @@
let last_tx_block = match collection.mode {
CollectionMode::NFT => <NftTransferBasket<T>>::get(collection.id, item_id),
- CollectionMode::Fungible(_) => <FungibleTransferBasket<T>>::get(collection.id, who),
+ CollectionMode::Fungible(_) => {
+ <FungibleTransferBasket<T>>::get(collection.id, who.as_sub())
+ }
CollectionMode::ReFungible => {
- <ReFungibleTransferBasket<T>>::get((collection.id, item_id, who))
+ <ReFungibleTransferBasket<T>>::get((collection.id, item_id, who.as_sub()))
}
};
@@ -59,11 +74,12 @@
match collection.mode {
CollectionMode::NFT => <NftTransferBasket<T>>::insert(collection.id, item_id, block_number),
CollectionMode::Fungible(_) => {
- <FungibleTransferBasket<T>>::insert(collection.id, who, block_number)
- }
- CollectionMode::ReFungible => {
- <ReFungibleTransferBasket<T>>::insert((collection.id, item_id, who), block_number)
+ <FungibleTransferBasket<T>>::insert(collection.id, who.as_sub(), block_number)
}
+ CollectionMode::ReFungible => <ReFungibleTransferBasket<T>>::insert(
+ (collection.id, item_id, who.as_sub()),
+ block_number,
+ ),
};
Some(())
@@ -101,20 +117,37 @@
}
pub fn withdraw_set_variable_meta_data<T: Config>(
- who: &T::AccountId,
+ who: &T::CrossAccountId,
collection: &CollectionHandle<T>,
item_id: &TokenId,
data: &[u8],
) -> Option<()> {
- // preliminary sponsoring correctness check
- if !((pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner).as_sub() == who)
- || (pallet_refungible::Owned::<T>::get((
- collection.id,
- T::CrossAccountId::from_sub(who.clone()),
- item_id,
- ))) {
+ // TODO: make it work for admins
+ if collection.meta_update_permission != MetaUpdatePermission::ItemOwner {
return None;
}
+ // preliminary sponsoring correctness check
+ match collection.mode {
+ CollectionMode::NFT => {
+ let owner = pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner;
+ if !owner.conv_eq(who) {
+ return None;
+ }
+ }
+ CollectionMode::Fungible(_) => {
+ if item_id != &TokenId::default() {
+ return None;
+ }
+ if <pallet_fungible::Balance<T>>::get((collection.id, who)) == 0 {
+ return None;
+ }
+ }
+ CollectionMode::ReFungible => {
+ if !<pallet_refungible::Owned<T>>::get((collection.id, who, item_id)) {
+ return None;
+ }
+ }
+ }
// Can't sponsor fungible collection, this tx will be rejected
// as invalid
@@ -203,14 +236,23 @@
collection_id,
item_id,
..
+ } => {
+ let (sponsor, collection) = load(*collection_id)?;
+ withdraw_transfer::<T>(
+ &collection,
+ &T::CrossAccountId::from_sub(who.clone()),
+ item_id,
+ )
+ .map(|()| sponsor)
}
- | Call::transfer_from {
+ Call::transfer_from {
collection_id,
item_id,
+ from,
..
} => {
let (sponsor, collection) = load(*collection_id)?;
- withdraw_transfer::<T>(&collection, who, item_id).map(|()| sponsor)
+ withdraw_transfer::<T>(&collection, from, item_id).map(|()| sponsor)
}
Call::approve {
collection_id,
@@ -226,8 +268,13 @@
data,
} => {
let (sponsor, collection) = load(*collection_id)?;
- withdraw_set_variable_meta_data::<T>(&who, &collection, item_id, data)
- .map(|()| sponsor)
+ withdraw_set_variable_meta_data::<T>(
+ &T::CrossAccountId::from_sub(who.clone()),
+ &collection,
+ item_id,
+ data,
+ )
+ .map(|()| sponsor)
}
_ => None,
}