difftreelog
CORE-302 Clean code
in: master
7 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -153,7 +153,7 @@
pub fn set_sponsor(&mut self, sponsor: T::AccountId) {
self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);
}
-
+
pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> bool {
if self.collection.sponsorship.pending_sponsor() != Some(sender) {
return false;
pallets/evm-collection/src/eth.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use core::marker::PhantomData;18use evm_coder::{abi::AbiWriter, execution::*, generate_stubgen, solidity_interface, types::*, ToLog};19use ethereum as _;20use pallet_common::CollectionById;21use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};22use pallet_evm::{23 ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure,24 account::CrossAccountId, Pallet as PalletEvm,25};26use sp_core::H160;27use up_data_structs::{28 CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,29 MAX_COLLECTION_NAME_LENGTH, OFFCHAIN_SCHEMA_LIMIT, VARIABLE_ON_CHAIN_SCHEMA_LIMIT,30 CONST_ON_CHAIN_SCHEMA_LIMIT,31};32use crate::{Config, Pallet};33use frame_support::traits::Get;3435use sp_std::{vec::Vec, rc::Rc};36use alloc::format;3738struct EvmCollection<T: Config>(SubstrateRecorder<T>);39impl<T: Config> WithRecorder<T> for EvmCollection<T> {40 fn recorder(&self) -> &SubstrateRecorder<T> {41 &self.042 }4344 fn into_recorder(self) -> SubstrateRecorder<T> {45 self.046 }47}4849#[derive(ToLog)]50pub enum CollectionEvent {51 CollectionCreated {52 #[indexed]53 owner: address,54 #[indexed]55 collection_id: address,56 },57}5859#[solidity_interface(name = "Collection")]60impl<T: Config> EvmCollection<T> {61 fn create_721_collection(62 &self,63 caller: caller,64 name: string,65 description: string,66 token_prefix: string,67 ) -> Result<address> {68 let caller = T::CrossAccountId::from_eth(caller);69 let name = name70 .encode_utf16()71 .collect::<Vec<u16>>()72 .try_into()73 .map_err(|_| error_feild_too_long("name", MAX_COLLECTION_NAME_LENGTH))?;74 let description = description75 .encode_utf16()76 .collect::<Vec<u16>>()77 .try_into()78 .map_err(|_| error_feild_too_long("description", MAX_COLLECTION_DESCRIPTION_LENGTH))?;79 let token_prefix = token_prefix80 .into_bytes()81 .try_into()82 .map_err(|_| error_feild_too_long("token_prefix", MAX_TOKEN_PREFIX_LENGTH))?;8384 let data = CreateCollectionData {85 name,86 description,87 token_prefix,88 ..Default::default()89 };9091 let collection_id =92 <pallet_nonfungible::Pallet<T>>::init_collection(caller.as_sub().clone(), data)93 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;9495 let address = pallet_common::eth::collection_id_to_address(collection_id);96 <PalletEvm<T>>::deposit_log(97 CollectionEvent::CollectionCreated {98 owner: *caller.as_eth(),99 collection_id: address,100 }101 .to_log(address),102 );103 Ok(address)104 }105106 fn set_sponsor(107 &self,108 caller: caller,109 collection_address: address,110 sponsor: address,111 ) -> Result<void> {112 let mut collection = collection_from_address(collection_address, &self.0)?;113 check_is_owner(caller, &collection)?;114115 fn set_offchain_shema(shema: string) -> Result<void> {116 let shema = shema117 .into_bytes()118 .try_into()119 .map_err(|_| error_feild_too_long(stringify!(shema), OFFCHAIN_SCHEMA_LIMIT))?;120 collection.offchain_schema = shema;121 save(collection)122 }123124 fn confirm_sponsorship(&self, caller: caller, collection_address: address) -> Result<void> {125 let mut collection = collection_from_address(collection_address, &self.0)?;126 let caller = T::CrossAccountId::from_eth(caller);127 if !collection.confirm_sponsorship(caller.as_sub()) {128 return Err(Error::Revert("Caller is not set as sponsor".into()));129 }130 save(collection)131 }132133 fn set_offchain_shema(134 &self,135 caller: caller,136 collection_address: address,137 shema: string,138 ) -> Result<void> {139 let mut collection = collection_from_address(collection_address, &self.0)?;140 check_is_owner(caller, &collection)?;141142 let shema = shema143 .into_bytes()144 .try_into()145 .map_err(|_| error_feild_too_long(stringify!(shema), OFFCHAIN_SCHEMA_LIMIT))?;146 collection.offchain_schema = shema;147 save(collection)148 }149150 fn set_variable_on_chain_schema(151 &self,152 caller: caller,153 collection_address: address,154 variable: string,155 ) -> Result<void> {156 let mut collection = collection_from_address(collection_address, &self.0)?;157 check_is_owner(caller, &collection)?;158159 let variable = variable.into_bytes().try_into().map_err(|_| {160 error_feild_too_long(stringify!(variable), VARIABLE_ON_CHAIN_SCHEMA_LIMIT)161 })?;162 collection.variable_on_chain_schema = variable;163 save(collection)164 }165166 fn set_const_on_chain_schema(167 &self,168 caller: caller,169 collection_address: address,170 const_on_chain: string,171 ) -> Result<void> {172 let mut collection = collection_from_address(collection_address, &self.0)?;173 check_is_owner(caller, &collection)?;174175 let const_on_chain = const_on_chain.into_bytes().try_into().map_err(|_| {176 error_feild_too_long(stringify!(const_on_chain), CONST_ON_CHAIN_SCHEMA_LIMIT)177 })?;178 collection.const_on_chain_schema = const_on_chain;179 save(collection)180 }181182 fn set_limits(183 &self,184 caller: caller,185 collection_address: address,186 limits_json: string,187 ) -> Result<void> {188 let mut collection = collection_from_address(collection_address, &self.0)?;189 check_is_owner(caller, &collection)?;190191 let limits = serde_json::from_str(limits_json.as_ref())192 .map_err(|e| Error::Revert(format!("Parse JSON error: {}", e)))?;193 collection.limits = limits;194 save(collection)195 }196}197198fn error_feild_too_long(feild: &str, bound: u32) -> Error {199 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))200}201202fn collection_from_address<T: Config>(203 collection_address: address,204 recorder: &Rc<SubstrateRecorder<T>>,205) -> Result<CollectionHandle<T>> {206 let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)207 .ok_or(Error::Revert("Bad ETH prefix".into()))?;208 let collection =209 pallet_common::CollectionHandle::new_with_recorder(collection_id, recorder.clone())210 .ok_or(Error::Revert("Create collection handle error".into()))?;211 Ok(collection)212}213214fn check_is_owner<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<()> {215 let caller = T::CrossAccountId::from_eth(caller);216 collection217 .check_is_owner(&caller)218 .map_err(|e| Error::Revert(format!("{:?}", e)))?;219 Ok(())220}221222fn save<T: Config>(collection: CollectionHandle<T>) -> Result<()> {223 collection224 .save()225 .map_err(|e| Error::Revert(format!("{:?}", e)))226}227228pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);229impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {230 fn is_reserved(contract: &sp_core::H160) -> bool {231 contract == &T::ContractAddress::get()232 }233234 fn is_used(contract: &sp_core::H160) -> bool {235 contract == &T::ContractAddress::get()236 }237238 fn call(239 source: &sp_core::H160,240 target: &sp_core::H160,241 gas_left: u64,242 input: &[u8],243 value: sp_core::U256,244 ) -> Option<PrecompileResult> {245 // TODO: Extract to another OnMethodCall handler246 if target != &T::ContractAddress::get() {247 return None;248 }249250 let helpers = EvmCollection::<T>(SubstrateRecorder::new(gas_left));251 pallet_evm_coder_substrate::call(*source, helpers, value, input)252 }253254 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {255 (contract == &T::ContractAddress::get())256 .then(|| include_bytes!("./stubs/Collection.raw").to_vec())257 }258}259260generate_stubgen!(collection_impl, CollectionCall<()>, true);261generate_stubgen!(collection_iface, CollectionCall<()>, false);1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use core::marker::PhantomData;18use evm_coder::{abi::AbiWriter, execution::*, generate_stubgen, solidity_interface, types::*, ToLog};19use ethereum as _;20use pallet_common::CollectionById;21use pallet_common::CollectionHandle;22use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};23use pallet_evm::{24 ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure,25 account::CrossAccountId, Pallet as PalletEvm,26};27use sp_core::H160;28use up_data_structs::{29 CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,30 MAX_COLLECTION_NAME_LENGTH, OFFCHAIN_SCHEMA_LIMIT, VARIABLE_ON_CHAIN_SCHEMA_LIMIT,31 CONST_ON_CHAIN_SCHEMA_LIMIT,32};33use crate::{Config, Pallet};34use frame_support::traits::Get;3536use sp_std::{vec::Vec, rc::Rc};37use alloc::format;3839struct EvmCollection<T: Config>(SubstrateRecorder<T>);40impl<T: Config> WithRecorder<T> for EvmCollection<T> {41 fn recorder(&self) -> &SubstrateRecorder<T> {42 &self.043 }4445 fn into_recorder(self) -> SubstrateRecorder<T> {46 self.047 }48}4950#[derive(ToLog)]51pub enum CollectionEvent {52 CollectionCreated {53 #[indexed]54 owner: address,55 #[indexed]56 collection_id: address,57 },58}5960#[solidity_interface(name = "Collection")]61impl<T: Config> EvmCollection<T> {62 fn create_721_collection(63 &self,64 caller: caller,65 name: string,66 description: string,67 token_prefix: string,68 ) -> Result<address> {69 let caller = T::CrossAccountId::from_eth(caller);70 let name = name71 .encode_utf16()72 .collect::<Vec<u16>>()73 .try_into()74 .map_err(|_| error_feild_too_long("name", MAX_COLLECTION_NAME_LENGTH))?;75 let description = description76 .encode_utf16()77 .collect::<Vec<u16>>()78 .try_into()79 .map_err(|_| error_feild_too_long("description", MAX_COLLECTION_DESCRIPTION_LENGTH))?;80 let token_prefix = token_prefix81 .into_bytes()82 .try_into()83 .map_err(|_| error_feild_too_long("token_prefix", MAX_TOKEN_PREFIX_LENGTH))?;8485 let data = CreateCollectionData {86 name,87 description,88 token_prefix,89 ..Default::default()90 };9192 let collection_id =93 <pallet_nonfungible::Pallet<T>>::init_collection(caller.as_sub().clone(), data)94 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;9596 let address = pallet_common::eth::collection_id_to_address(collection_id);97 <PalletEvm<T>>::deposit_log(98 CollectionEvent::CollectionCreated {99 owner: *caller.as_eth(),100 collection_id: address,101 }102 .to_log(address),103 );104 Ok(address)105 }106107 fn set_sponsor(108 &self,109 caller: caller,110 collection_address: address,111 sponsor: address,112 ) -> Result<void> {113 let mut collection = collection_from_address(collection_address, &self.0)?;114 check_is_owner(caller, &collection)?;115116 fn set_offchain_shema(shema: string) -> Result<void> {117 let shema = shema118 .into_bytes()119 .try_into()120 .map_err(|_| error_feild_too_long(stringify!(shema), OFFCHAIN_SCHEMA_LIMIT))?;121 collection.offchain_schema = shema;122 save(collection)123 }124125 fn confirm_sponsorship(&self, caller: caller, collection_address: address) -> Result<void> {126 let mut collection = collection_from_address(collection_address, &self.0)?;127 let caller = T::CrossAccountId::from_eth(caller);128 if !collection.confirm_sponsorship(caller.as_sub()) {129 return Err(Error::Revert("Caller is not set as sponsor".into()));130 }131 save(collection)132 }133134 fn set_offchain_shema(135 &self,136 caller: caller,137 collection_address: address,138 shema: string,139 ) -> Result<void> {140 let mut collection = collection_from_address(collection_address, &self.0)?;141 check_is_owner(caller, &collection)?;142143 let shema = shema144 .into_bytes()145 .try_into()146 .map_err(|_| error_feild_too_long(stringify!(shema), OFFCHAIN_SCHEMA_LIMIT))?;147 collection.offchain_schema = shema;148 save(collection)149 }150151 fn set_variable_on_chain_schema(152 &self,153 caller: caller,154 collection_address: address,155 variable: string,156 ) -> Result<void> {157 let mut collection = collection_from_address(collection_address, &self.0)?;158 check_is_owner(caller, &collection)?;159160 let variable = variable.into_bytes().try_into().map_err(|_| {161 error_feild_too_long(stringify!(variable), VARIABLE_ON_CHAIN_SCHEMA_LIMIT)162 })?;163 collection.variable_on_chain_schema = variable;164 save(collection)165 }166167 fn set_const_on_chain_schema(168 &self,169 caller: caller,170 collection_address: address,171 const_on_chain: string,172 ) -> Result<void> {173 let mut collection = collection_from_address(collection_address, &self.0)?;174 check_is_owner(caller, &collection)?;175176 let const_on_chain = const_on_chain.into_bytes().try_into().map_err(|_| {177 error_feild_too_long(stringify!(const_on_chain), CONST_ON_CHAIN_SCHEMA_LIMIT)178 })?;179 collection.const_on_chain_schema = const_on_chain;180 save(collection)181 }182183 fn set_limits(184 &self,185 caller: caller,186 collection_address: address,187 limits_json: string,188 ) -> Result<void> {189 let mut collection = collection_from_address(collection_address, &self.0)?;190 check_is_owner(caller, &collection)?;191192 let limits = serde_json::from_str(limits_json.as_ref())193 .map_err(|e| Error::Revert(format!("Parse JSON error: {}", e)))?;194 collection.limits = limits;195 save(collection)196 }197}198199fn error_feild_too_long(feild: &str, bound: u32) -> Error {200 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))201}202203fn collection_from_address<T: Config>(204 collection_address: address,205 recorder: &Rc<SubstrateRecorder<T>>,206) -> Result<CollectionHandle<T>> {207 let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)208 .ok_or(Error::Revert("Bad ETH prefix".into()))?;209 let collection =210 pallet_common::CollectionHandle::new_with_recorder(collection_id, recorder.clone())211 .ok_or(Error::Revert("Create collection handle error".into()))?;212 Ok(collection)213}214215fn check_is_owner<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<()> {216 let caller = T::CrossAccountId::from_eth(caller);217 collection218 .check_is_owner(&caller)219 .map_err(|e| Error::Revert(format!("{:?}", e)))?;220 Ok(())221}222223fn save<T: Config>(collection: CollectionHandle<T>) -> Result<()> {224 collection225 .save()226 .map_err(|e| Error::Revert(format!("{:?}", e)))227}228229pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);230impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {231 fn is_reserved(contract: &sp_core::H160) -> bool {232 contract == &T::ContractAddress::get()233 }234235 fn is_used(contract: &sp_core::H160) -> bool {236 contract == &T::ContractAddress::get()237 }238239 fn call(240 source: &sp_core::H160,241 target: &sp_core::H160,242 gas_left: u64,243 input: &[u8],244 value: sp_core::U256,245 ) -> Option<PrecompileResult> {246 // TODO: Extract to another OnMethodCall handler247 if target != &T::ContractAddress::get() {248 return None;249 }250251 let helpers = EvmCollection::<T>(SubstrateRecorder::new(gas_left));252 pallet_evm_coder_substrate::call(*source, helpers, value, input)253 }254255 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {256 (contract == &T::ContractAddress::get())257 .then(|| include_bytes!("./stubs/Collection.raw").to_vec())258 }259}260261generate_stubgen!(collection_impl, CollectionCall<()>, true);262generate_stubgen!(collection_iface, CollectionCall<()>, false);pallets/evm-collection/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-collection/src/lib.rs
+++ b/pallets/evm-collection/src/lib.rs
@@ -18,22 +18,22 @@
extern crate alloc;
-use codec::{Decode, Encode, MaxEncodedLen};
pub use pallet::*;
pub use eth::*;
-use scale_info::TypeInfo;
pub mod eth;
#[frame_support::pallet]
pub mod pallet {
pub use super::*;
- use evm_coder::execution::Result;
use frame_support::pallet_prelude::*;
use sp_core::H160;
#[pallet::config]
pub trait Config:
- frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::account::Config + pallet_nonfungible::Config
+ frame_system::Config
+ + pallet_evm_coder_substrate::Config
+ + pallet_evm::account::Config
+ + pallet_nonfungible::Config
{
type ContractAddress: Get<H160>;
}
@@ -47,7 +47,6 @@
#[pallet::pallet]
// #[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
-
impl<T: Config> Pallet<T> {}
}
pallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -31,7 +31,10 @@
#[pallet::config]
pub trait Config:
- frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::account::Config + pallet_nonfungible::Config
+ frame_system::Config
+ + pallet_evm_coder_substrate::Config
+ + pallet_evm::account::Config
+ + pallet_nonfungible::Config
{
type ContractAddress: Get<H160>;
type DefaultSponsoringRateLimit: Get<Self::BlockNumber>;
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -368,30 +368,30 @@
#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct CollectionLimits {
- #[serde(alias="accountTokenOwnershipLimit")]
+ #[serde(alias = "accountTokenOwnershipLimit")]
pub account_token_ownership_limit: Option<u32>,
- #[serde(alias="sponsoredDataSize")]
+ #[serde(alias = "sponsoredDataSize")]
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
- #[serde(alias="sponsoredDataRateLimit")]
+ #[serde(alias = "sponsoredDataRateLimit")]
pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,
- #[serde(alias="tokenLimit")]
+ #[serde(alias = "tokenLimit")]
pub token_limit: Option<u32>,
-
+
// Timeouts for item types in passed blocks
- #[serde(alias="sponsorTransferTimeout")]
+ #[serde(alias = "sponsorTransferTimeout")]
pub sponsor_transfer_timeout: Option<u32>,
- #[serde(alias="sponsorApproveTimeout")]
+ #[serde(alias = "sponsorApproveTimeout")]
pub sponsor_approve_timeout: Option<u32>,
- #[serde(alias="ownerCanTransfer")]
+ #[serde(alias = "ownerCanTransfer")]
pub owner_can_transfer: Option<bool>,
- #[serde(alias="ownerCanDestroy")]
+ #[serde(alias = "ownerCanDestroy")]
pub owner_can_destroy: Option<bool>,
- #[serde(alias="transfersEnabled")]
+ #[serde(alias = "transfersEnabled")]
pub transfers_enabled: Option<bool>,
}
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -975,7 +975,7 @@
pub const HelpersContractAddress: H160 = H160([
0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,
]);
-
+
// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
pub const EvmCollectionAddress: H160 = H160([
0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
tests/src/eth/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -101,7 +101,7 @@
expect(collection.constOnChainSchema.toHuman()).to.be.eq(constShema);
});
- itWeb3.only('Set limits', async ({api, web3}) => {
+ itWeb3('Set limits', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
const helper = collectionHelper(web3, owner);
const result = await helper.methods.create721Collection('Const collection', '4', '4').send();