difftreelog
refactor Remove variable data from tokens
in: master
23 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -71,13 +71,6 @@
token: TokenId,
at: Option<BlockHash>,
) -> Result<Vec<u8>>;
- #[rpc(name = "unique_variableMetadata")]
- fn variable_metadata(
- &self,
- collection: CollectionId,
- token: TokenId,
- at: Option<BlockHash>,
- ) -> Result<Vec<u8>>;
#[rpc(name = "unique_collectionProperties")]
fn collection_properties(
@@ -279,7 +272,6 @@
);
pass_method!(topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>);
pass_method!(const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);
- pass_method!(variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);
pass_method!(collection_properties(
collection: CollectionId,
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -33,7 +33,7 @@
MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId,
CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,
FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,
- CUSTOM_DATA_LIMIT, CollectionLimits, CustomDataLimit, CreateCollectionData, SponsorshipState,
+ CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState,
CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,
PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyPermission,
PropertiesError, PropertyKeyPermission, TokenData, TrySet,
@@ -312,8 +312,6 @@
CollectionTokenPrefixLimitExceeded,
/// Total collections bound exceeded.
TotalCollectionsLimitExceeded,
- /// variable_data exceeded data limit.
- TokenVariableDataLimitExceeded,
/// Exceeded max admin count
CollectionAdminCountExceeded,
/// Collection limit bounds per collection exceeded
@@ -1073,7 +1071,6 @@
fn approve() -> Weight;
fn transfer_from() -> Weight;
fn burn_from() -> Weight;
- fn set_variable_metadata(bytes: u32) -> Weight;
}
pub trait CommonCollectionOperations<T: Config> {
@@ -1163,13 +1160,6 @@
nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo;
- fn set_variable_metadata(
- &self,
- sender: T::CrossAccountId,
- token: TokenId,
- data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResultWithPostInfo;
-
fn check_nesting(
&self,
sender: T::CrossAccountId,
@@ -1185,7 +1175,6 @@
fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;
fn const_metadata(&self, token: TokenId) -> Vec<u8>;
- fn variable_metadata(&self, token: TokenId) -> Vec<u8>;
fn token_properties(&self, token_id: TokenId, keys: Vec<PropertyKey>) -> Vec<Property>;
/// Amount of unique collection tokens
fn total_supply(&self) -> u32;
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -16,12 +16,12 @@
use core::marker::PhantomData;
-use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
+use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
-use up_data_structs::{CustomDataLimit, Property, PropertyKey, PropertyKeyPermission};
+use up_data_structs::{Property, PropertyKey, PropertyKeyPermission};
use crate::{
Allowance, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf, weights::WeightInfo,
@@ -85,11 +85,6 @@
fn burn_from() -> Weight {
<SelfWeightOf<T>>::burn_from()
}
-
- fn set_variable_metadata(_bytes: u32) -> Weight {
- // Error
- 0
- }
}
impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {
@@ -287,15 +282,6 @@
fail!(<Error<T>>::SettingPropertiesNotAllowed)
}
- fn set_variable_metadata(
- &self,
- _sender: T::CrossAccountId,
- _token: TokenId,
- _data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::FungibleItemsDontHaveData)
- }
-
fn check_nesting(
&self,
_sender: <T>::CrossAccountId,
@@ -330,9 +316,6 @@
None
}
fn const_metadata(&self, _token: TokenId) -> Vec<u8> {
- Vec::new()
- }
- fn variable_metadata(&self, _token: TokenId) -> Vec<u8> {
Vec::new()
}
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -27,6 +27,7 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
+struct-versioning = { path = "../../crates/struct-versioning" }
[features]
default = ["std"]
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -28,10 +28,8 @@
fn create_max_item_data<T: Config>(owner: T::CrossAccountId) -> CreateItemData<T> {
let const_data = create_data::<CUSTOM_DATA_LIMIT>();
- let variable_data = create_data::<CUSTOM_DATA_LIMIT>();
CreateItemData::<T> {
const_data,
- variable_data,
owner,
}
}
@@ -125,14 +123,4 @@
let item = create_max_item(&collection, &owner, sender.clone())?;
<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&burner))?;
}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, &Unlimited)?}
-
- set_variable_metadata {
- let b in 0..CUSTOM_DATA_LIMIT;
- bench_init!{
- owner: sub; collection: collection(owner);
- owner: cross_from_sub; sender: cross_sub;
- };
- let item = create_max_item(&collection, &owner, sender.clone())?;
- let data = create_var_data(b).try_into().unwrap();
- }: {<Pallet<T>>::set_variable_metadata(&collection, &sender, item, data)?}
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -16,9 +16,9 @@
use core::marker::PhantomData;
-use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
+use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use up_data_structs::{
- TokenId, CustomDataLimit, CreateItemExData, CollectionId, budget::Budget, Property,
+ TokenId, CreateItemExData, CollectionId, budget::Budget, Property,
PropertyKey, PropertyKeyPermission,
};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
@@ -85,10 +85,6 @@
fn burn_from() -> Weight {
<SelfWeightOf<T>>::burn_from()
- }
-
- fn set_variable_metadata(bytes: u32) -> Weight {
- <SelfWeightOf<T>>::set_variable_metadata(bytes)
}
}
@@ -99,7 +95,6 @@
match data {
up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {
const_data: data.const_data,
- variable_data: data.variable_data,
properties: data.properties,
owner: to.clone(),
}),
@@ -325,19 +320,6 @@
} else {
Ok(().into())
}
- }
-
- fn set_variable_metadata(
- &self,
- sender: T::CrossAccountId,
- token: TokenId,
- data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResultWithPostInfo {
- let len = data.len();
- with_weight(
- <Pallet<T>>::set_variable_metadata(self, &sender, token, data),
- <CommonWeights<T>>::set_variable_metadata(len as u32),
- )
}
fn check_nesting(
@@ -376,12 +358,6 @@
fn const_metadata(&self, token: TokenId) -> Vec<u8> {
<TokenData<T>>::get((self.id, token))
.map(|t| t.const_data)
- .unwrap_or_default()
- .into_inner()
- }
- fn variable_metadata(&self, token: TokenId) -> Vec<u8> {
- <TokenData<T>>::get((self.id, token))
- .map(|t| t.variable_data)
.unwrap_or_default()
.into_inner()
}
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -24,7 +24,7 @@
use up_data_structs::{TokenId, SchemaVersion};
use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_core::{H160, U256};
-use sp_std::{vec::Vec, vec};
+use sp_std::vec::Vec;
use pallet_common::{
erc::{CommonEvmHandler, PrecompileResult, CollectionPropertiesCall},
CollectionHandle,
@@ -274,7 +274,6 @@
&caller,
CreateItemData::<T> {
const_data: BoundedVec::default(),
- variable_data: BoundedVec::default(),
properties: BoundedVec::default(),
owner: to,
},
@@ -322,7 +321,6 @@
const_data: Vec::<u8>::from(token_uri)
.try_into()
.map_err(|_| "token uri is too long")?,
- variable_data: BoundedVec::default(),
properties: BoundedVec::default(),
owner: to,
},
@@ -387,37 +385,6 @@
.into())
}
- #[weight(<SelfWeightOf<T>>::set_variable_metadata(data.len() as u32))]
- fn set_variable_metadata(
- &mut self,
- caller: caller,
- token_id: uint256,
- data: bytes,
- ) -> Result<void> {
- let caller = T::CrossAccountId::from_eth(caller);
- let token = token_id.try_into()?;
-
- <Pallet<T>>::set_variable_metadata(
- self,
- &caller,
- token,
- data.try_into()
- .map_err(|_| "metadata size exceeded limit")?,
- )
- .map_err(dispatch_to_evm::<T>)?;
- Ok(())
- }
-
- fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {
- self.consume_store_reads(1)?;
- let token: TokenId = token_id.try_into()?;
-
- Ok(<TokenData<T>>::get((self.id, token))
- .ok_or("token not found")?
- .variable_data
- .into_inner())
- }
-
#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]
fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -440,7 +407,6 @@
let data = (0..total_tokens)
.map(|_| CreateItemData::<T> {
const_data: BoundedVec::default(),
- variable_data: BoundedVec::default(),
properties: BoundedVec::default(),
owner: to.clone(),
})
@@ -484,7 +450,6 @@
const_data: Vec::<u8>::from(token_uri)
.try_into()
.map_err(|_| "token uri is too long")?,
- variable_data: vec![].try_into().unwrap(),
properties: BoundedVec::default(),
owner: to.clone(),
});
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -49,17 +49,22 @@
pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;
pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
+#[struct_versioning::versioned(version = 2, upper)]
#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]
pub struct ItemData<CrossAccountId> {
pub const_data: BoundedVec<u8, CustomDataLimit>,
+
+ #[version(..2)]
pub variable_data: BoundedVec<u8, CustomDataLimit>,
+
pub owner: CrossAccountId,
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
- use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};
+ use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};
+ use frame_system::pallet_prelude::*;
use up_data_structs::{CollectionId, TokenId};
use super::weights::WeightInfo;
@@ -78,7 +83,10 @@
type WeightInfo: WeightInfo;
}
+ const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
+
#[pallet::pallet]
+ #[pallet::storage_version(STORAGE_VERSION)]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
@@ -133,6 +141,19 @@
Value = T::CrossAccountId,
QueryKind = OptionQuery,
>;
+
+ #[pallet::hooks]
+ impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
+ fn on_runtime_upgrade() -> Weight {
+ if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
+ <TokenData<T>>::translate_values::<ItemDataVersion1<T::CrossAccountId>, _>(|v| {
+ Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))
+ })
+ }
+
+ 0
+ }
+ }
}
pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);
@@ -577,7 +598,6 @@
(collection.id, token),
ItemData {
const_data: data.const_data,
- variable_data: data.variable_data,
owner: data.owner.clone(),
},
);
@@ -773,28 +793,6 @@
// =========
Self::burn(collection, from, token)
- }
-
- pub fn set_variable_metadata(
- collection: &NonfungibleHandle<T>,
- sender: &T::CrossAccountId,
- token: TokenId,
- data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResult {
- let token_data =
- <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
- collection.check_can_update_meta(sender, &token_data.owner)?;
-
- // =========
-
- <TokenData<T>>::insert(
- (collection.id, token),
- ItemData {
- variable_data: data,
- ..token_data
- },
- );
- Ok(())
}
pub fn check_nesting(
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -61,6 +61,24 @@
}
}
+// Selector: 56fd500b
+contract CollectionProperties is Dummy, ERC165 {
+ // Selector: setProperty(string,string) 62d9491f
+ function setProperty(string memory key, string memory value) public {
+ require(false, stub_error);
+ key;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: deleteProperty(string) 34241914
+ function deleteProperty(string memory key) public {
+ require(false, stub_error);
+ key;
+ dummy = 0;
+ }
+}
+
// Selector: 58800161
contract ERC721 is Dummy, ERC165, ERC721Events {
// Selector: balanceOf(address) 70a08231
@@ -276,7 +294,7 @@
}
}
-// Selector: e562194d
+// Selector: d74d154f
contract ERC721UniqueExtensions is Dummy, ERC165 {
// Selector: transfer(address,uint256) a9059cbb
function transfer(address to, uint256 tokenId) public {
@@ -301,26 +319,6 @@
return 0;
}
- // Selector: setVariableMetadata(uint256,bytes) d4eac26d
- function setVariableMetadata(uint256 tokenId, bytes memory data) public {
- require(false, stub_error);
- tokenId;
- data;
- dummy = 0;
- }
-
- // Selector: getVariableMetadata(uint256) e6c5ce6f
- function getVariableMetadata(uint256 tokenId)
- public
- view
- returns (bytes memory)
- {
- require(false, stub_error);
- tokenId;
- dummy;
- return hex"";
- }
-
// Selector: mintBulk(address,uint256[]) 44a9945e
function mintBulk(address to, uint256[] memory tokenIds)
public
@@ -354,5 +352,6 @@
ERC721Enumerable,
ERC721UniqueExtensions,
ERC721Mintable,
- ERC721Burnable
+ ERC721Burnable,
+ CollectionProperties
{}
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -45,7 +45,6 @@
fn approve() -> Weight;
fn transfer_from() -> Weight;
fn burn_from() -> Weight;
- fn set_variable_metadata(b: u32, ) -> Weight;
}
/// Weights for pallet_nonfungible using the Substrate node and recommended hardware.
@@ -155,12 +154,6 @@
(27_580_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
- }
- // Storage: Nonfungible TokenData (r:1 w:1)
- fn set_variable_metadata(_b: u32, ) -> Weight {
- (7_700_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(1 as Weight))
- .saturating_add(T::DbWeight::get().writes(1 as Weight))
}
}
@@ -270,11 +263,5 @@
(27_580_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
- }
- // Storage: Nonfungible TokenData (r:1 w:1)
- fn set_variable_metadata(_b: u32, ) -> Weight {
- (7_700_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(1 as Weight))
- .saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
}
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -24,6 +24,7 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
+struct-versioning = { path = "../../crates/struct-versioning" }
[features]
default = ["std"]
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -31,10 +31,8 @@
users: impl IntoIterator<Item = (CrossAccountId, u128)>,
) -> CreateRefungibleExData<CrossAccountId> {
let const_data = create_data::<CUSTOM_DATA_LIMIT>();
- let variable_data = create_data::<CUSTOM_DATA_LIMIT>();
CreateRefungibleExData {
const_data,
- variable_data,
users: users
.into_iter()
.collect::<BTreeMap<_, _>>()
@@ -203,14 +201,4 @@
let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
<Pallet<T>>::set_allowance(&collection, &sender, &burner, item, 200)?;
}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, 200, &Unlimited)?}
-
- set_variable_metadata {
- let b in 0..CUSTOM_DATA_LIMIT;
- bench_init!{
- owner: sub; collection: collection(owner);
- sender: cross_from_sub(owner);
- };
- let item = create_max_item(&collection, &sender, [(sender.clone(), 200)])?;
- let data = create_var_data(b).try_into().unwrap();
- }: {<Pallet<T>>::set_variable_metadata(&collection, &sender, item, data)?}
}
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -17,9 +17,9 @@
use core::marker::PhantomData;
use sp_std::collections::btree_map::BTreeMap;
-use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight, BoundedVec};
+use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};
use up_data_structs::{
- CollectionId, TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData,
+ CollectionId, TokenId, CreateItemExData, CreateRefungibleExData,
budget::Budget, Property, PropertyKey, PropertyKeyPermission,
};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
@@ -110,10 +110,6 @@
fn burn_from() -> Weight {
<SelfWeightOf<T>>::burn_from()
- }
-
- fn set_variable_metadata(bytes: u32) -> Weight {
- <SelfWeightOf<T>>::set_variable_metadata(bytes)
}
}
@@ -124,7 +120,6 @@
match data {
up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateRefungibleExData {
const_data: data.const_data,
- variable_data: data.variable_data,
users: {
let mut out = BTreeMap::new();
out.insert(to.clone(), data.pieces);
@@ -306,19 +301,6 @@
fail!(<Error<T>>::SettingPropertiesNotAllowed)
}
- fn set_variable_metadata(
- &self,
- sender: T::CrossAccountId,
- token: TokenId,
- data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResultWithPostInfo {
- let len = data.len();
- with_weight(
- <Pallet<T>>::set_variable_metadata(self, &sender, token, data),
- <CommonWeights<T>>::set_variable_metadata(len as u32),
- )
- }
-
fn check_nesting(
&self,
_sender: <T>::CrossAccountId,
@@ -355,11 +337,6 @@
fn const_metadata(&self, token: TokenId) -> Vec<u8> {
<TokenData<T>>::get((self.id, token))
.const_data
- .into_inner()
- }
- fn variable_metadata(&self, token: TokenId) -> Vec<u8> {
- <TokenData<T>>::get((self.id, token))
- .variable_data
.into_inner()
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -41,16 +41,20 @@
pub mod weights;
pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
+#[struct_versioning::versioned(version = 2, upper)]
#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]
pub struct ItemData {
pub const_data: BoundedVec<u8, CustomDataLimit>,
+
+ #[version(..2)]
pub variable_data: BoundedVec<u8, CustomDataLimit>,
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
- use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};
+ use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};
+ use frame_system::pallet_prelude::*;
use up_data_structs::{CollectionId, TokenId};
use super::weights::WeightInfo;
@@ -73,7 +77,10 @@
type WeightInfo: WeightInfo;
}
+ const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
+
#[pallet::pallet]
+ #[pallet::storage_version(STORAGE_VERSION)]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
@@ -146,6 +153,19 @@
Value = u128,
QueryKind = ValueQuery,
>;
+
+ #[pallet::hooks]
+ impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
+ fn on_runtime_upgrade() -> Weight {
+ if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
+ <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {
+ Some(<ItemDataVersion2>::from(v))
+ })
+ }
+
+ 0
+ }
+ }
}
pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);
@@ -494,7 +514,6 @@
(collection.id, token_id),
ItemData {
const_data: token.const_data,
- variable_data: token.variable_data,
},
);
for (user, amount) in token.users.into_iter() {
@@ -643,31 +662,6 @@
if let Some(allowance) = allowance {
Self::set_allowance_unchecked(collection, from, spender, token, allowance);
}
- Ok(())
- }
-
- pub fn set_variable_metadata(
- collection: &RefungibleHandle<T>,
- sender: &T::CrossAccountId,
- token: TokenId,
- data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResult {
- collection.check_can_update_meta(
- sender,
- &T::CrossAccountId::from_sub(collection.owner.clone()),
- )?;
-
- let token_data = <TokenData<T>>::get((collection.id, token));
-
- // =========
-
- <TokenData<T>>::insert(
- (collection.id, token),
- ItemData {
- variable_data: data,
- ..token_data
- },
- );
Ok(())
}
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -53,7 +53,6 @@
fn transfer_from_removing() -> Weight;
fn transfer_from_creating_removing() -> Weight;
fn burn_from() -> Weight;
- fn set_variable_metadata(b: u32, ) -> Weight;
}
/// Weights for pallet_refungible using the Substrate node and recommended hardware.
@@ -242,12 +241,6 @@
(42_043_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(7 as Weight))
- }
- // Storage: Refungible TokenData (r:1 w:1)
- fn set_variable_metadata(_b: u32, ) -> Weight {
- (7_364_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(1 as Weight))
- .saturating_add(T::DbWeight::get().writes(1 as Weight))
}
}
@@ -436,11 +429,5 @@
(42_043_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(7 as Weight))
- }
- // Storage: Refungible TokenData (r:1 w:1)
- fn set_variable_metadata(_b: u32, ) -> Weight {
- (7_364_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(1 as Weight))
- .saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -38,7 +38,7 @@
CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
- SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData, CustomDataLimit,
+ SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData,
CreateItemExData, budget, CollectionField, Property, PropertyKey, PropertyKeyPermission,
};
use pallet_evm::account::CrossAccountId;
@@ -238,9 +238,6 @@
pub ReFungibleTransferBasket get(fn refungible_transfer_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;
//#endregion
- /// Variable metadata sponsoring
- /// Collection id (controlled?2), token id (controlled?2)
- pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;
/// Approval sponsoring
pub NftApproveBasket get(fn nft_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;
pub FungibleApproveBasket get(fn fungible_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;
@@ -333,7 +330,6 @@
<FungibleTransferBasket<T>>::remove_prefix(collection_id, None);
<ReFungibleTransferBasket<T>>::remove_prefix((collection_id,), None);
- <VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);
<NftApproveBasket<T>>::remove_prefix(collection_id, None);
<FungibleApproveBasket<T>>::remove_prefix(collection_id, None);
<RefungibleApproveBasket<T>>::remove_prefix((collection_id,), None);
@@ -929,31 +925,6 @@
let budget = budget::Value::new(2);
dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
- }
-
- /// Set off-chain data schema.
- ///
- /// # Permissions
- ///
- /// * Collection Owner
- /// * Collection Admin
- ///
- /// # Arguments
- ///
- /// * collection_id.
- ///
- /// * schema: String representing the offchain data schema.
- #[weight = T::CommonWeightInfo::set_variable_metadata(data.len() as u32)]
- #[transactional]
- pub fn set_variable_meta_data (
- origin,
- collection_id: CollectionId,
- item_id: TokenId,
- data: BoundedVec<u8, CustomDataLimit>,
- ) -> DispatchResultWithPostInfo {
- let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
- dispatch_call::<T, _>(collection_id, |d| d.set_variable_metadata(sender, item_id, data))
}
/// Set meta_update_permission value for particular collection
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -364,28 +364,6 @@
pub type CollectionPropertiesVec =
BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;
-#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct NftItemType<AccountId> {
- pub owner: AccountId,
- pub const_data: Vec<u8>,
- pub variable_data: Vec<u8>,
-}
-
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct FungibleItemType {
- pub value: u128,
-}
-
-#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct ReFungibleItemType<AccountId> {
- pub owner: Vec<Ownership<AccountId>>,
- pub const_data: Vec<u8>,
- pub variable_data: Vec<u8>,
-}
-
/// All fields are wrapped in `Option`s, where None means chain default
#[struct_versioning::versioned(version = 2, upper)]
#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
@@ -393,6 +371,8 @@
pub struct CollectionLimits {
pub account_token_ownership_limit: Option<u32>,
pub sponsored_data_size: Option<u32>,
+
+ /// FIXME should we delete this or repurpose it?
/// None - setVariableMetadata is not sponsored
/// Some(v) - setVariableMetadata is sponsored
/// if there is v block between txs
@@ -490,9 +470,6 @@
#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub const_data: BoundedVec<u8, CustomDataLimit>,
- #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
- #[derivative(Debug(format_with = "bounded::vec_debug"))]
- pub variable_data: BoundedVec<u8, CustomDataLimit>,
#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
#[derivative(Debug(format_with = "bounded::vec_debug"))]
@@ -512,9 +489,6 @@
#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub const_data: BoundedVec<u8, CustomDataLimit>,
- #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
- #[derivative(Debug(format_with = "bounded::vec_debug"))]
- pub variable_data: BoundedVec<u8, CustomDataLimit>,
pub pieces: u128,
}
@@ -545,8 +519,6 @@
pub struct CreateNftExData<CrossAccountId> {
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub const_data: BoundedVec<u8, CustomDataLimit>,
- #[derivative(Debug(format_with = "bounded::vec_debug"))]
- pub variable_data: BoundedVec<u8, CustomDataLimit>,
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub properties: CollectionPropertiesVec,
pub owner: CrossAccountId,
@@ -557,8 +529,6 @@
pub struct CreateRefungibleExData<CrossAccountId> {
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub const_data: BoundedVec<u8, CustomDataLimit>,
- #[derivative(Debug(format_with = "bounded::vec_debug"))]
- pub variable_data: BoundedVec<u8, CustomDataLimit>,
#[derivative(Debug(format_with = "bounded::map_debug"))]
pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
}
@@ -586,8 +556,8 @@
impl CreateItemData {
pub fn data_size(&self) -> usize {
match self {
- CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),
- CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),
+ CreateItemData::NFT(data) => data.const_data.len(),
+ CreateItemData::ReFungible(data) => data.const_data.len(),
_ => 0,
}
}
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -42,7 +42,6 @@
fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>>;
- fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>>;
fn collection_properties(collection: CollectionId, properties: Vec<Vec<u8>>) -> Result<Vec<Property>>;
runtime/common/src/runtime_apis.rsdiffbeforeafterboth1#[macro_export]2macro_rules! impl_common_runtime_apis {3 (4 $(5 #![custom_apis]67 $($custom_apis:tt)+8 )?9 ) => {10 impl_runtime_apis! {11 $($($custom_apis)+)?1213 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {14 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {15 dispatch_unique_runtime!(collection.account_tokens(account))16 }17 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {18 dispatch_unique_runtime!(collection.collection_tokens())19 }20 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {21 dispatch_unique_runtime!(collection.token_exists(token))22 }2324 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {25 dispatch_unique_runtime!(collection.token_owner(token))26 }27 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {28 let budget = up_data_structs::budget::Value::new(5);2930 Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))31 }32 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {33 dispatch_unique_runtime!(collection.const_metadata(token))34 }35 fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {36 dispatch_unique_runtime!(collection.variable_metadata(token))37 }3839 fn collection_properties(40 collection: CollectionId,41 keys: Vec<Vec<u8>>42 ) -> Result<Vec<Property>, DispatchError> {43 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;4445 pallet_common::Pallet::<Runtime>::filter_collection_properties(collection, keys)46 }4748 fn token_properties(49 collection: CollectionId,50 token_id: TokenId,51 keys: Vec<Vec<u8>>52 ) -> Result<Vec<Property>, DispatchError> {53 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;54 dispatch_unique_runtime!(collection.token_properties(token_id, keys))55 }5657 fn property_permissions(58 collection: CollectionId,59 keys: Vec<Vec<u8>>60 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {61 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;6263 pallet_common::Pallet::<Runtime>::filter_property_permissions(collection, keys)64 }6566 fn token_data(67 collection: CollectionId,68 token_id: TokenId,69 keys: Vec<Vec<u8>>70 ) -> Result<TokenData<CrossAccountId>, DispatchError> {71 let token_data = TokenData {72 const_data: Self::const_metadata(collection, token_id)?,73 properties: Self::token_properties(collection, token_id, keys)?,74 owner: Self::token_owner(collection, token_id)?75 };7677 Ok(token_data)78 }7980 fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {81 dispatch_unique_runtime!(collection.total_supply())82 }83 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {84 dispatch_unique_runtime!(collection.account_balance(account))85 }86 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {87 dispatch_unique_runtime!(collection.balance(account, token))88 }89 fn allowance(90 collection: CollectionId,91 sender: CrossAccountId,92 spender: CrossAccountId,93 token: TokenId,94 ) -> Result<u128, DispatchError> {95 dispatch_unique_runtime!(collection.allowance(sender, spender, token))96 }9798 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {99 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))100 }101 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {102 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))103 }104 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {105 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))106 }107 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {108 dispatch_unique_runtime!(collection.last_token_id())109 }110 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {111 Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))112 }113 fn collection_stats() -> Result<CollectionStats, DispatchError> {114 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())115 }116 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {117 Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as118 $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(119 collection,120 account,121 token))122 }123124 fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {125 Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))126 }127 }128129 impl sp_api::Core<Block> for Runtime {130 fn version() -> RuntimeVersion {131 VERSION132 }133134 fn execute_block(block: Block) {135 Executive::execute_block(block)136 }137138 fn initialize_block(header: &<Block as BlockT>::Header) {139 Executive::initialize_block(header)140 }141 }142143 impl sp_api::Metadata<Block> for Runtime {144 fn metadata() -> OpaqueMetadata {145 OpaqueMetadata::new(Runtime::metadata().into())146 }147 }148149 impl sp_block_builder::BlockBuilder<Block> for Runtime {150 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {151 Executive::apply_extrinsic(extrinsic)152 }153154 fn finalize_block() -> <Block as BlockT>::Header {155 Executive::finalize_block()156 }157158 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {159 data.create_extrinsics()160 }161162 fn check_inherents(163 block: Block,164 data: sp_inherents::InherentData,165 ) -> sp_inherents::CheckInherentsResult {166 data.check_extrinsics(&block)167 }168169 // fn random_seed() -> <Block as BlockT>::Hash {170 // RandomnessCollectiveFlip::random_seed().0171 // }172 }173174 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {175 fn validate_transaction(176 source: TransactionSource,177 tx: <Block as BlockT>::Extrinsic,178 hash: <Block as BlockT>::Hash,179 ) -> TransactionValidity {180 Executive::validate_transaction(source, tx, hash)181 }182 }183184 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {185 fn offchain_worker(header: &<Block as BlockT>::Header) {186 Executive::offchain_worker(header)187 }188 }189190 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {191 fn chain_id() -> u64 {192 <Runtime as pallet_evm::Config>::ChainId::get()193 }194195 fn account_basic(address: H160) -> EVMAccount {196 EVM::account_basic(&address)197 }198199 fn gas_price() -> U256 {200 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()201 }202203 fn account_code_at(address: H160) -> Vec<u8> {204 EVM::account_codes(address)205 }206207 fn author() -> H160 {208 <pallet_evm::Pallet<Runtime>>::find_author()209 }210211 fn storage_at(address: H160, index: U256) -> H256 {212 let mut tmp = [0u8; 32];213 index.to_big_endian(&mut tmp);214 EVM::account_storages(address, H256::from_slice(&tmp[..]))215 }216217 #[allow(clippy::redundant_closure)]218 fn call(219 from: H160,220 to: H160,221 data: Vec<u8>,222 value: U256,223 gas_limit: U256,224 max_fee_per_gas: Option<U256>,225 max_priority_fee_per_gas: Option<U256>,226 nonce: Option<U256>,227 estimate: bool,228 access_list: Option<Vec<(H160, Vec<H256>)>>,229 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {230 let config = if estimate {231 let mut config = <Runtime as pallet_evm::Config>::config().clone();232 config.estimate = true;233 Some(config)234 } else {235 None236 };237238 let is_transactional = false;239 <Runtime as pallet_evm::Config>::Runner::call(240 CrossAccountId::from_eth(from),241 to,242 data,243 value,244 gas_limit.low_u64(),245 max_fee_per_gas,246 max_priority_fee_per_gas,247 nonce,248 access_list.unwrap_or_default(),249 is_transactional,250 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),251 ).map_err(|err| err.into())252 }253254 #[allow(clippy::redundant_closure)]255 fn create(256 from: H160,257 data: Vec<u8>,258 value: U256,259 gas_limit: U256,260 max_fee_per_gas: Option<U256>,261 max_priority_fee_per_gas: Option<U256>,262 nonce: Option<U256>,263 estimate: bool,264 access_list: Option<Vec<(H160, Vec<H256>)>>,265 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {266 let config = if estimate {267 let mut config = <Runtime as pallet_evm::Config>::config().clone();268 config.estimate = true;269 Some(config)270 } else {271 None272 };273274 let is_transactional = false;275 <Runtime as pallet_evm::Config>::Runner::create(276 CrossAccountId::from_eth(from),277 data,278 value,279 gas_limit.low_u64(),280 max_fee_per_gas,281 max_priority_fee_per_gas,282 nonce,283 access_list.unwrap_or_default(),284 is_transactional,285 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),286 ).map_err(|err| err.into())287 }288289 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {290 Ethereum::current_transaction_statuses()291 }292293 fn current_block() -> Option<pallet_ethereum::Block> {294 Ethereum::current_block()295 }296297 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {298 Ethereum::current_receipts()299 }300301 fn current_all() -> (302 Option<pallet_ethereum::Block>,303 Option<Vec<pallet_ethereum::Receipt>>,304 Option<Vec<TransactionStatus>>305 ) {306 (307 Ethereum::current_block(),308 Ethereum::current_receipts(),309 Ethereum::current_transaction_statuses()310 )311 }312313 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {314 xts.into_iter().filter_map(|xt| match xt.0.function {315 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),316 _ => None317 }).collect()318 }319320 fn elasticity() -> Option<Permill> {321 None322 }323 }324325 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {326 fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic {327 UncheckedExtrinsic::new_unsigned(328 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),329 )330 }331 }332333 impl sp_session::SessionKeys<Block> for Runtime {334 fn decode_session_keys(335 encoded: Vec<u8>,336 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {337 SessionKeys::decode_into_raw_public_keys(&encoded)338 }339340 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {341 SessionKeys::generate(seed)342 }343 }344345 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {346 fn slot_duration() -> sp_consensus_aura::SlotDuration {347 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())348 }349350 fn authorities() -> Vec<AuraId> {351 Aura::authorities().to_vec()352 }353 }354355 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {356 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {357 ParachainSystem::collect_collation_info(header)358 }359 }360361 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {362 fn account_nonce(account: AccountId) -> Index {363 System::account_nonce(account)364 }365 }366367 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {368 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {369 TransactionPayment::query_info(uxt, len)370 }371 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {372 TransactionPayment::query_fee_details(uxt, len)373 }374 }375376 /*377 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>378 for Runtime379 {380 fn call(381 origin: AccountId,382 dest: AccountId,383 value: Balance,384 gas_limit: u64,385 input_data: Vec<u8>,386 ) -> pallet_contracts_primitives::ContractExecResult {387 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)388 }389390 fn instantiate(391 origin: AccountId,392 endowment: Balance,393 gas_limit: u64,394 code: pallet_contracts_primitives::Code<Hash>,395 data: Vec<u8>,396 salt: Vec<u8>,397 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>398 {399 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)400 }401402 fn get_storage(403 address: AccountId,404 key: [u8; 32],405 ) -> pallet_contracts_primitives::GetStorageResult {406 Contracts::get_storage(address, key)407 }408409 fn rent_projection(410 address: AccountId,411 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {412 Contracts::rent_projection(address)413 }414 }415 */416417 #[cfg(feature = "runtime-benchmarks")]418 impl frame_benchmarking::Benchmark<Block> for Runtime {419 fn benchmark_metadata(extra: bool) -> (420 Vec<frame_benchmarking::BenchmarkList>,421 Vec<frame_support::traits::StorageInfo>,422 ) {423 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};424 use frame_support::traits::StorageInfoTrait;425426 let mut list = Vec::<BenchmarkList>::new();427428 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);429 list_benchmark!(list, extra, pallet_unique, Unique);430 list_benchmark!(list, extra, pallet_structure, Structure);431 list_benchmark!(list, extra, pallet_inflation, Inflation);432 list_benchmark!(list, extra, pallet_fungible, Fungible);433 list_benchmark!(list, extra, pallet_refungible, Refungible);434 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);435 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);436437 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();438439 return (list, storage_info)440 }441442 fn dispatch_benchmark(443 config: frame_benchmarking::BenchmarkConfig444 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {445 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};446447 let allowlist: Vec<TrackedStorageKey> = vec![448 // Block Number449 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),450 // Total Issuance451 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),452 // Execution Phase453 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),454 // Event Count455 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),456 // System Events457 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),458459 // Transactional depth460 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),461 ];462463 let mut batches = Vec::<BenchmarkBatch>::new();464 let params = (&config, &allowlist);465466 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);467 add_benchmark!(params, batches, pallet_unique, Unique);468 add_benchmark!(params, batches, pallet_structure, Structure);469 add_benchmark!(params, batches, pallet_inflation, Inflation);470 add_benchmark!(params, batches, pallet_fungible, Fungible);471 add_benchmark!(params, batches, pallet_refungible, Refungible);472 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);473 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);474475 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }476 Ok(batches)477 }478 }479480 #[cfg(feature = "try-runtime")]481 impl frame_try_runtime::TryRuntime<Block> for Runtime {482 fn on_runtime_upgrade() -> (Weight, Weight) {483 log::info!("try-runtime::on_runtime_upgrade unique-chain.");484 let weight = Executive::try_runtime_upgrade().unwrap();485 (weight, RuntimeBlockWeights::get().max_block)486 }487488 fn execute_block_no_check(block: Block) -> Weight {489 Executive::execute_block_no_check(block)490 }491 }492 }493 }494}1#[macro_export]2macro_rules! impl_common_runtime_apis {3 (4 $(5 #![custom_apis]67 $($custom_apis:tt)+8 )?9 ) => {10 impl_runtime_apis! {11 $($($custom_apis)+)?1213 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {14 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {15 dispatch_unique_runtime!(collection.account_tokens(account))16 }17 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {18 dispatch_unique_runtime!(collection.collection_tokens())19 }20 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {21 dispatch_unique_runtime!(collection.token_exists(token))22 }2324 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {25 dispatch_unique_runtime!(collection.token_owner(token))26 }27 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {28 let budget = up_data_structs::budget::Value::new(5);2930 Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))31 }32 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {33 dispatch_unique_runtime!(collection.const_metadata(token))34 }3536 fn collection_properties(37 collection: CollectionId,38 keys: Vec<Vec<u8>>39 ) -> Result<Vec<Property>, DispatchError> {40 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;4142 pallet_common::Pallet::<Runtime>::filter_collection_properties(collection, keys)43 }4445 fn token_properties(46 collection: CollectionId,47 token_id: TokenId,48 keys: Vec<Vec<u8>>49 ) -> Result<Vec<Property>, DispatchError> {50 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;51 dispatch_unique_runtime!(collection.token_properties(token_id, keys))52 }5354 fn property_permissions(55 collection: CollectionId,56 keys: Vec<Vec<u8>>57 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {58 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;5960 pallet_common::Pallet::<Runtime>::filter_property_permissions(collection, keys)61 }6263 fn token_data(64 collection: CollectionId,65 token_id: TokenId,66 keys: Vec<Vec<u8>>67 ) -> Result<TokenData<CrossAccountId>, DispatchError> {68 let token_data = TokenData {69 const_data: Self::const_metadata(collection, token_id)?,70 properties: Self::token_properties(collection, token_id, keys)?,71 owner: Self::token_owner(collection, token_id)?72 };7374 Ok(token_data)75 }7677 fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {78 dispatch_unique_runtime!(collection.total_supply())79 }80 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {81 dispatch_unique_runtime!(collection.account_balance(account))82 }83 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {84 dispatch_unique_runtime!(collection.balance(account, token))85 }86 fn allowance(87 collection: CollectionId,88 sender: CrossAccountId,89 spender: CrossAccountId,90 token: TokenId,91 ) -> Result<u128, DispatchError> {92 dispatch_unique_runtime!(collection.allowance(sender, spender, token))93 }9495 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {96 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))97 }98 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {99 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))100 }101 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {102 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))103 }104 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {105 dispatch_unique_runtime!(collection.last_token_id())106 }107 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {108 Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))109 }110 fn collection_stats() -> Result<CollectionStats, DispatchError> {111 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())112 }113 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {114 Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as115 $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(116 collection,117 account,118 token))119 }120121 fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {122 Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))123 }124 }125126 impl sp_api::Core<Block> for Runtime {127 fn version() -> RuntimeVersion {128 VERSION129 }130131 fn execute_block(block: Block) {132 Executive::execute_block(block)133 }134135 fn initialize_block(header: &<Block as BlockT>::Header) {136 Executive::initialize_block(header)137 }138 }139140 impl sp_api::Metadata<Block> for Runtime {141 fn metadata() -> OpaqueMetadata {142 OpaqueMetadata::new(Runtime::metadata().into())143 }144 }145146 impl sp_block_builder::BlockBuilder<Block> for Runtime {147 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {148 Executive::apply_extrinsic(extrinsic)149 }150151 fn finalize_block() -> <Block as BlockT>::Header {152 Executive::finalize_block()153 }154155 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {156 data.create_extrinsics()157 }158159 fn check_inherents(160 block: Block,161 data: sp_inherents::InherentData,162 ) -> sp_inherents::CheckInherentsResult {163 data.check_extrinsics(&block)164 }165166 // fn random_seed() -> <Block as BlockT>::Hash {167 // RandomnessCollectiveFlip::random_seed().0168 // }169 }170171 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {172 fn validate_transaction(173 source: TransactionSource,174 tx: <Block as BlockT>::Extrinsic,175 hash: <Block as BlockT>::Hash,176 ) -> TransactionValidity {177 Executive::validate_transaction(source, tx, hash)178 }179 }180181 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {182 fn offchain_worker(header: &<Block as BlockT>::Header) {183 Executive::offchain_worker(header)184 }185 }186187 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {188 fn chain_id() -> u64 {189 <Runtime as pallet_evm::Config>::ChainId::get()190 }191192 fn account_basic(address: H160) -> EVMAccount {193 EVM::account_basic(&address)194 }195196 fn gas_price() -> U256 {197 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()198 }199200 fn account_code_at(address: H160) -> Vec<u8> {201 EVM::account_codes(address)202 }203204 fn author() -> H160 {205 <pallet_evm::Pallet<Runtime>>::find_author()206 }207208 fn storage_at(address: H160, index: U256) -> H256 {209 let mut tmp = [0u8; 32];210 index.to_big_endian(&mut tmp);211 EVM::account_storages(address, H256::from_slice(&tmp[..]))212 }213214 #[allow(clippy::redundant_closure)]215 fn call(216 from: H160,217 to: H160,218 data: Vec<u8>,219 value: U256,220 gas_limit: U256,221 max_fee_per_gas: Option<U256>,222 max_priority_fee_per_gas: Option<U256>,223 nonce: Option<U256>,224 estimate: bool,225 access_list: Option<Vec<(H160, Vec<H256>)>>,226 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {227 let config = if estimate {228 let mut config = <Runtime as pallet_evm::Config>::config().clone();229 config.estimate = true;230 Some(config)231 } else {232 None233 };234235 let is_transactional = false;236 <Runtime as pallet_evm::Config>::Runner::call(237 CrossAccountId::from_eth(from),238 to,239 data,240 value,241 gas_limit.low_u64(),242 max_fee_per_gas,243 max_priority_fee_per_gas,244 nonce,245 access_list.unwrap_or_default(),246 is_transactional,247 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),248 ).map_err(|err| err.into())249 }250251 #[allow(clippy::redundant_closure)]252 fn create(253 from: H160,254 data: Vec<u8>,255 value: U256,256 gas_limit: U256,257 max_fee_per_gas: Option<U256>,258 max_priority_fee_per_gas: Option<U256>,259 nonce: Option<U256>,260 estimate: bool,261 access_list: Option<Vec<(H160, Vec<H256>)>>,262 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {263 let config = if estimate {264 let mut config = <Runtime as pallet_evm::Config>::config().clone();265 config.estimate = true;266 Some(config)267 } else {268 None269 };270271 let is_transactional = false;272 <Runtime as pallet_evm::Config>::Runner::create(273 CrossAccountId::from_eth(from),274 data,275 value,276 gas_limit.low_u64(),277 max_fee_per_gas,278 max_priority_fee_per_gas,279 nonce,280 access_list.unwrap_or_default(),281 is_transactional,282 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),283 ).map_err(|err| err.into())284 }285286 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {287 Ethereum::current_transaction_statuses()288 }289290 fn current_block() -> Option<pallet_ethereum::Block> {291 Ethereum::current_block()292 }293294 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {295 Ethereum::current_receipts()296 }297298 fn current_all() -> (299 Option<pallet_ethereum::Block>,300 Option<Vec<pallet_ethereum::Receipt>>,301 Option<Vec<TransactionStatus>>302 ) {303 (304 Ethereum::current_block(),305 Ethereum::current_receipts(),306 Ethereum::current_transaction_statuses()307 )308 }309310 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {311 xts.into_iter().filter_map(|xt| match xt.0.function {312 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),313 _ => None314 }).collect()315 }316317 fn elasticity() -> Option<Permill> {318 None319 }320 }321322 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {323 fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic {324 UncheckedExtrinsic::new_unsigned(325 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),326 )327 }328 }329330 impl sp_session::SessionKeys<Block> for Runtime {331 fn decode_session_keys(332 encoded: Vec<u8>,333 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {334 SessionKeys::decode_into_raw_public_keys(&encoded)335 }336337 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {338 SessionKeys::generate(seed)339 }340 }341342 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {343 fn slot_duration() -> sp_consensus_aura::SlotDuration {344 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())345 }346347 fn authorities() -> Vec<AuraId> {348 Aura::authorities().to_vec()349 }350 }351352 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {353 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {354 ParachainSystem::collect_collation_info(header)355 }356 }357358 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {359 fn account_nonce(account: AccountId) -> Index {360 System::account_nonce(account)361 }362 }363364 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {365 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {366 TransactionPayment::query_info(uxt, len)367 }368 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {369 TransactionPayment::query_fee_details(uxt, len)370 }371 }372373 /*374 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>375 for Runtime376 {377 fn call(378 origin: AccountId,379 dest: AccountId,380 value: Balance,381 gas_limit: u64,382 input_data: Vec<u8>,383 ) -> pallet_contracts_primitives::ContractExecResult {384 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)385 }386387 fn instantiate(388 origin: AccountId,389 endowment: Balance,390 gas_limit: u64,391 code: pallet_contracts_primitives::Code<Hash>,392 data: Vec<u8>,393 salt: Vec<u8>,394 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>395 {396 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)397 }398399 fn get_storage(400 address: AccountId,401 key: [u8; 32],402 ) -> pallet_contracts_primitives::GetStorageResult {403 Contracts::get_storage(address, key)404 }405406 fn rent_projection(407 address: AccountId,408 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {409 Contracts::rent_projection(address)410 }411 }412 */413414 #[cfg(feature = "runtime-benchmarks")]415 impl frame_benchmarking::Benchmark<Block> for Runtime {416 fn benchmark_metadata(extra: bool) -> (417 Vec<frame_benchmarking::BenchmarkList>,418 Vec<frame_support::traits::StorageInfo>,419 ) {420 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};421 use frame_support::traits::StorageInfoTrait;422423 let mut list = Vec::<BenchmarkList>::new();424425 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);426 list_benchmark!(list, extra, pallet_unique, Unique);427 list_benchmark!(list, extra, pallet_structure, Structure);428 list_benchmark!(list, extra, pallet_inflation, Inflation);429 list_benchmark!(list, extra, pallet_fungible, Fungible);430 list_benchmark!(list, extra, pallet_refungible, Refungible);431 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);432 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);433434 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();435436 return (list, storage_info)437 }438439 fn dispatch_benchmark(440 config: frame_benchmarking::BenchmarkConfig441 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {442 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};443444 let allowlist: Vec<TrackedStorageKey> = vec![445 // Block Number446 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),447 // Total Issuance448 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),449 // Execution Phase450 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),451 // Event Count452 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),453 // System Events454 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),455456 // Transactional depth457 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),458 ];459460 let mut batches = Vec::<BenchmarkBatch>::new();461 let params = (&config, &allowlist);462463 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);464 add_benchmark!(params, batches, pallet_unique, Unique);465 add_benchmark!(params, batches, pallet_structure, Structure);466 add_benchmark!(params, batches, pallet_inflation, Inflation);467 add_benchmark!(params, batches, pallet_fungible, Fungible);468 add_benchmark!(params, batches, pallet_refungible, Refungible);469 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);470 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);471472 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }473 Ok(batches)474 }475 }476477 #[cfg(feature = "try-runtime")]478 impl frame_try_runtime::TryRuntime<Block> for Runtime {479 fn on_runtime_upgrade() -> (Weight, Weight) {480 log::info!("try-runtime::on_runtime_upgrade unique-chain.");481 let weight = Executive::try_runtime_upgrade().unwrap();482 (weight, RuntimeBlockWeights::get().max_block)483 }484485 fn execute_block_no_check(block: Block) -> Weight {486 Executive::execute_block_no_check(block)487 }488 }489 }490 }491}runtime/common/src/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/src/sponsoring.rs
+++ b/runtime/common/src/sponsoring.rs
@@ -21,7 +21,7 @@
storage::{StorageMap, StorageDoubleMap, StorageNMap},
};
use up_data_structs::{
- CollectionId, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MetaUpdatePermission,
+ CollectionId, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, TokenId, CollectionMode,
CreateItemData,
};
@@ -30,7 +30,7 @@
use pallet_evm::account::CrossAccountId;
use pallet_unique::{
Call as UniqueCall, Config as UniqueConfig, FungibleApproveBasket, RefungibleApproveBasket,
- NftApproveBasket, VariableMetaDataBasket, CreateItemBasket, ReFungibleTransferBasket,
+ NftApproveBasket, CreateItemBasket, ReFungibleTransferBasket,
FungibleTransferBasket, NftTransferBasket,
};
use pallet_fungible::Config as FungibleConfig;
@@ -139,64 +139,7 @@
Some(())
}
-
-pub fn withdraw_set_variable_meta_data<T: Config>(
- who: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- item_id: &TokenId,
- data: &[u8],
-) -> Option<()> {
- // 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
- if matches!(collection.mode, CollectionMode::Fungible(_)) {
- return None;
- }
- if data.len() > collection.limits.sponsored_data_size() as usize {
- return None;
- }
-
- let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
- let limit = collection.limits.sponsored_data_rate_limit()?;
-
- if let Some(last_tx_block) = VariableMetaDataBasket::<T>::get(collection.id, item_id) {
- let timeout = last_tx_block + limit.into();
- if block_number < timeout {
- return None;
- }
- }
-
- <VariableMetaDataBasket<T>>::insert(collection.id, item_id, block_number);
-
- Some(())
-}
-
pub fn withdraw_approve<T: Config>(
collection: &CollectionHandle<T>,
who: &T::AccountId,
@@ -290,20 +233,6 @@
} => {
let (sponsor, collection) = load(*collection_id)?;
withdraw_approve::<T>(&collection, who, item_id).map(|()| sponsor)
- }
- UniqueCall::set_variable_meta_data {
- collection_id,
- item_id,
- data,
- } => {
- let (sponsor, collection) = load(*collection_id)?;
- withdraw_set_variable_meta_data::<T>(
- &T::CrossAccountId::from_sub(who.clone()),
- &collection,
- item_id,
- data,
- )
- .map(|()| sponsor)
}
_ => None,
}
runtime/common/src/weights.rsdiffbeforeafterboth--- a/runtime/common/src/weights.rs
+++ b/runtime/common/src/weights.rs
@@ -86,10 +86,6 @@
dispatch_weight::<T>() + max_weight_of!(transfer_from())
}
- fn set_variable_metadata(bytes: u32) -> Weight {
- dispatch_weight::<T>() + max_weight_of!(set_variable_metadata(bytes))
- }
-
fn burn_from() -> Weight {
dispatch_weight::<T>() + max_weight_of!(burn_from())
}
runtime/tests/src/tests.rsdiffbeforeafterboth--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -47,7 +47,6 @@
fn default_nft_data() -> CreateNftData {
CreateNftData {
const_data: vec![1, 2, 3].try_into().unwrap(),
- variable_data: vec![3, 2, 1].try_into().unwrap(),
}
}
@@ -58,7 +57,6 @@
fn default_re_fungible_data() -> CreateReFungibleData {
CreateReFungibleData {
const_data: vec![1, 2, 3].try_into().unwrap(),
- variable_data: vec![3, 2, 1].try_into().unwrap(),
pieces: 1023,
}
}
@@ -215,7 +213,6 @@
let item = <pallet_nonfungible::TokenData<Test>>::get((collection_id, 1)).unwrap();
assert_eq!(item.const_data, data.const_data.into_inner());
- assert_eq!(item.variable_data, data.variable_data.into_inner());
});
}
@@ -247,7 +244,6 @@
))
.unwrap();
assert_eq!(item.const_data.to_vec(), data.const_data.into_inner());
- assert_eq!(item.variable_data.to_vec(), data.variable_data.into_inner());
}
});
}
@@ -263,7 +259,6 @@
let balance =
<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1)));
assert_eq!(item.const_data, data.const_data.into_inner());
- assert_eq!(item.variable_data, data.variable_data.into_inner());
assert_eq!(balance, 1023);
});
}
@@ -299,7 +294,6 @@
let balance =
<pallet_refungible::Balance<Test>>::get((CollectionId(1), TokenId(1), account(1)));
assert_eq!(item.const_data.to_vec(), data.const_data.into_inner());
- assert_eq!(item.variable_data.to_vec(), data.variable_data.into_inner());
assert_eq!(balance, 1023);
}
});
@@ -413,7 +407,6 @@
create_test_item(collection_id, &data.clone().into());
let item = <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1)));
assert_eq!(item.const_data, data.const_data.into_inner());
- assert_eq!(item.variable_data, data.variable_data.into_inner());
assert_eq!(
<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
1
@@ -2427,117 +2420,6 @@
}
#[test]
-fn set_variable_meta_data_on_nft_token_stores_variable_meta_data() {
- new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
-
- let origin1 = Origin::signed(1);
-
- let data = default_nft_data();
- create_test_item(CollectionId(1), &data.into());
-
- let variable_data = b"test data".to_vec();
- assert_ok!(Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data.clone().try_into().unwrap()
- ));
-
- assert_eq!(
- <pallet_nonfungible::TokenData<Test>>::get((collection_id, 1))
- .unwrap()
- .variable_data,
- variable_data
- );
- });
-}
-
-#[test]
-fn set_variable_meta_data_on_re_fungible_token_stores_variable_meta_data() {
- new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
-
- let origin1 = Origin::signed(1);
-
- let data = default_re_fungible_data();
- create_test_item(collection_id, &data.into());
-
- let variable_data = b"test data".to_vec();
- assert_ok!(Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data.clone().try_into().unwrap()
- ));
-
- assert_eq!(
- <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1))).variable_data,
- variable_data
- );
- });
-}
-
-#[test]
-fn set_variable_meta_data_on_fungible_token_fails() {
- new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
-
- let origin1 = Origin::signed(1);
-
- let data = default_fungible_data();
- create_test_item(collection_id, &data.into());
-
- let variable_data = b"test data".to_vec();
- assert_noop!(
- Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(0),
- variable_data.try_into().unwrap()
- )
- .map_err(|e| e.error),
- <pallet_fungible::Error<Test>>::FungibleItemsDontHaveData
- );
- });
-}
-
-#[test]
-fn set_variable_meta_data_on_nft_with_item_owner_permission_flag() {
- new_test_ext().execute_with(|| {
- //default_limits();
-
- let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
-
- let origin1 = Origin::signed(1);
-
- let data = default_nft_data();
- create_test_item(collection_id, &data.into());
-
- assert_ok!(Unique::set_meta_update_permission_flag(
- origin1.clone(),
- collection_id,
- MetaUpdatePermission::ItemOwner,
- ));
-
- let variable_data = b"ten chars.".to_vec();
- assert_ok!(Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data.clone().try_into().unwrap()
- ));
-
- assert_eq!(
- <pallet_nonfungible::TokenData<Test>>::get((collection_id, TokenId(1)))
- .unwrap()
- .variable_data,
- variable_data
- );
- });
-}
-
-#[test]
fn collection_transfer_flag_works() {
new_test_ext().execute_with(|| {
let origin1 = Origin::signed(1);
@@ -2590,105 +2472,6 @@
}
#[test]
-fn set_variable_meta_data_on_nft_with_admin_flag() {
- new_test_ext().execute_with(|| {
- // default_limits();
-
- let collection_id =
- create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
-
- let origin1 = Origin::signed(1);
- let origin2 = Origin::signed(2);
-
- assert_ok!(Unique::set_mint_permission(
- origin2.clone(),
- collection_id,
- true
- ));
- assert_ok!(Unique::add_to_allow_list(
- origin2.clone(),
- collection_id,
- account(1)
- ));
-
- assert_ok!(Unique::add_collection_admin(
- origin2.clone(),
- collection_id,
- account(1)
- ));
-
- let data = default_nft_data();
- create_test_item(collection_id, &data.into());
-
- assert_ok!(Unique::set_meta_update_permission_flag(
- origin2.clone(),
- collection_id,
- MetaUpdatePermission::Admin,
- ));
-
- let variable_data = b"test.".to_vec();
- assert_ok!(Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data.clone().try_into().unwrap()
- ));
-
- assert_eq!(
- <pallet_nonfungible::TokenData<Test>>::get((collection_id, 1))
- .unwrap()
- .variable_data,
- variable_data
- );
- });
-}
-
-#[test]
-fn set_variable_meta_data_on_nft_with_admin_flag_neg() {
- new_test_ext().execute_with(|| {
- // default_limits();
-
- let collection_id =
- create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
-
- let origin1 = Origin::signed(1);
- let origin2 = Origin::signed(2);
-
- assert_ok!(Unique::set_mint_permission(
- origin2.clone(),
- collection_id,
- true
- ));
- assert_ok!(Unique::add_to_allow_list(
- origin2.clone(),
- collection_id,
- account(1)
- ));
-
- let data = default_nft_data();
- create_test_item(collection_id, &data.into());
-
- assert_ok!(Unique::set_meta_update_permission_flag(
- origin2.clone(),
- collection_id,
- MetaUpdatePermission::Admin,
- ));
-
- let variable_data = b"test.".to_vec();
- assert_noop!(
- Unique::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data.try_into().unwrap()
- )
- .map_err(|e| e.error),
- CommonError::<Test>::NoPermission
- );
- });
-}
-
-#[test]
fn set_variable_meta_flag_after_freeze() {
new_test_ext().execute_with(|| {
// default_limits();
@@ -2710,38 +2493,6 @@
MetaUpdatePermission::Admin
),
CommonError::<Test>::MetadataFlagFrozen
- );
- });
-}
-
-#[test]
-fn set_variable_meta_data_on_nft_with_none_flag_neg() {
- new_test_ext().execute_with(|| {
- // default_limits();
-
- let collection_id =
- create_test_collection_for_owner(&CollectionMode::NFT, 1, CollectionId(1));
- let origin1 = Origin::signed(1);
-
- let data = default_nft_data();
- create_test_item(collection_id, &data.into());
-
- assert_ok!(Unique::set_meta_update_permission_flag(
- origin1.clone(),
- collection_id,
- MetaUpdatePermission::None,
- ));
-
- let variable_data = b"test.".to_vec();
- assert_noop!(
- Unique::set_variable_meta_data(
- origin1.clone(),
- collection_id,
- TokenId(1),
- variable_data.try_into().unwrap()
- )
- .map_err(|e| e.error),
- CommonError::<Test>::NoPermission
);
});
}
smart_contracs/transfer/lib.rsdiffbeforeafterboth--- a/smart_contracs/transfer/lib.rs
+++ b/smart_contracs/transfer/lib.rs
@@ -58,14 +58,12 @@
pub enum CreateItemData {
Nft {
const_data: Vec<u8>,
- variable_data: Vec<u8>,
},
Fungible {
value: u128,
},
ReFungible {
const_data: Vec<u8>,
- variable_data: Vec<u8>,
pieces: u128,
},
}
@@ -88,8 +86,6 @@
fn approve(spender: DefaultAccountId, collection_id: u32, item_id: u32, amount: u128);
#[ink(extension = 4, returns_result = false)]
fn transfer_from(owner: DefaultAccountId, recipient: DefaultAccountId, collection_id: u32, item_id: u32, amount: u128);
- #[ink(extension = 5, returns_result = false)]
- fn set_variable_meta_data(collection_id: u32, item_id: u32, data: Vec<u8>);
#[ink(extension = 6, returns_result = false)]
fn toggle_allow_list(collection_id: u32, address: DefaultAccountId, allowlisted: bool);
}
@@ -143,12 +139,6 @@
let _ = self.env()
.extension()
.transfer_from(owner, recipient, collection_id, item_id, amount);
- }
- #[ink(message)]
- pub fn set_variable_meta_data(&mut self, collection_id: u32, item_id: u32, data: Vec<u8>) {
- let _ = self.env()
- .extension()
- .set_variable_meta_data(collection_id, item_id, data);
}
#[ink(message)]
pub fn toggle_allow_list(&mut self, collection_id: u32, address: AccountId, allowlisted: bool) {