git.delta.rocks / unique-network / refs/commits / e077e7804a83

difftreelog

Merge pull request #208 from UniqueNetwork/feature/split-collection-pallets

Yaroslav Bolyukin2021-11-02parents: #0151032 #b11eb43.patch.diff
in: master
Split collection pallets

71 files changed

modified.maintain/frame-weight-template.hbsdiffbeforeafterboth
92 {{~/each}}92 {{~/each}}
93 }93 }
94 {{~/each}}94 {{~/each}}
95}95}
96
modified.maintain/scripts/compile_stub.shdiffbeforeafterboth
6tmp=$(mktemp -d)6tmp=$(mktemp -d)
7cd $tmp7cd $tmp
8cp $dir/$INPUT input.sol8cp $dir/$INPUT input.sol
9solcjs --optimize --bin input.sol9solcjs --optimize --bin input.sol -o $PWD
1010
11mv input_sol_$(basename $OUTPUT .raw).bin out.bin11mv input_sol_$(basename $OUTPUT .raw).bin out.bin
12xxd -r -p out.bin out.raw12xxd -r -p out.bin out.raw
modified.maintain/scripts/generate_api.shdiffbeforeafterboth

no syntactic changes

modifiedCargo.tomldiffbeforeafterboth
3members = [3members = [
4 'node/*',4 'node/*',
5 'pallets/*',5 'pallets/*',
6 'client/*',
6 'primitives/*',7 'primitives/*',
7 'runtime',8 'runtime',
8 'crates/*',9 'crates/*',
modifiedMakefilediffbeforeafterboth
88
9.PHONY: regenerate_solidity9.PHONY: regenerate_solidity
10regenerate_solidity:10regenerate_solidity:
11 PACKAGE=pallet-nft NAME=eth::erc::fungible_iface OUTPUT=./tests/src/eth/api/UniqueFungible.sol ./.maintain/scripts/generate_api.sh11 PACKAGE=pallet-fungible NAME=erc::gen_iface OUTPUT=./tests/src/eth/api/UniqueFungible.sol ./.maintain/scripts/generate_api.sh
12 PACKAGE=pallet-nft NAME=eth::erc::nft_iface OUTPUT=./tests/src/eth/api/UniqueNFT.sol ./.maintain/scripts/generate_api.sh12 PACKAGE=pallet-nonfungible NAME=erc::gen_iface OUTPUT=./tests/src/eth/api/UniqueNFT.sol ./.maintain/scripts/generate_api.sh
13 PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_iface OUTPUT=./tests/src/eth/api/ContractHelpers.sol ./.maintain/scripts/generate_api.sh13 PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_iface OUTPUT=./tests/src/eth/api/ContractHelpers.sol ./.maintain/scripts/generate_api.sh
1414
15 PACKAGE=pallet-nft NAME=eth::erc::fungible_impl OUTPUT=./pallets/nft/src/eth/stubs/UniqueFungible.sol ./.maintain/scripts/generate_api.sh15 PACKAGE=pallet-fungible NAME=erc::gen_impl OUTPUT=./pallets/fungible/src/stubs/UniqueFungible.sol ./.maintain/scripts/generate_api.sh
16 PACKAGE=pallet-nft NAME=eth::erc::nft_impl OUTPUT=./pallets/nft/src/eth/stubs/UniqueNFT.sol ./.maintain/scripts/generate_api.sh16 PACKAGE=pallet-nonfungible NAME=erc::gen_impl OUTPUT=./pallets/nonfungible/src/stubs/UniqueNFT.sol ./.maintain/scripts/generate_api.sh
17 PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_impl OUTPUT=./pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol ./.maintain/scripts/generate_api.sh17 PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_impl OUTPUT=./pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol ./.maintain/scripts/generate_api.sh
1818
19FUNGIBLE_EVM_STUBS=./pallets/fungible/src/stubs
19NFT_EVM_STUBS=./pallets/nft/src/eth/stubs20NONFUNGIBLE_EVM_STUBS=./pallets/nonfungible/src/stubs
20CONTRACT_HELPERS_STUBS=./pallets/evm-contract-helpers/src/stubs/21CONTRACT_HELPERS_STUBS=./pallets/evm-contract-helpers/src/stubs/
2122
22$(NFT_EVM_STUBS)/UniqueFungible.raw: $(NFT_EVM_STUBS)/UniqueFungible.sol23$(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw: $(FUNGIBLE_EVM_STUBS)/UniqueFungible.sol
23 INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh24 INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh
24$(NFT_EVM_STUBS)/UniqueNFT.raw: $(NFT_EVM_STUBS)/UniqueNFT.sol25$(NONFUNGIBLE_EVM_STUBS)/UniqueNFT.raw: $(NONFUNGIBLE_EVM_STUBS)/UniqueNFT.sol
25 INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh26 INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh
26$(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw: $(CONTRACT_HELPERS_STUBS)/ContractHelpers.sol27$(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw: $(CONTRACT_HELPERS_STUBS)/ContractHelpers.sol
27 INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh28 INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh
2829
29evm_stubs: $(NFT_EVM_STUBS)/UniqueFungible.raw $(NFT_EVM_STUBS)/UniqueNFT.raw $(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw30evm_stubs: $(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw $(NONFUNGIBLE_EVM_STUBS)/UniqueNFT.raw $(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw
3031
31.PHONY: _bench32.PHONY: _bench
32_bench:33_bench:
44bench-nft:45bench-nft:
45 make _bench PALLET=nft46 make _bench PALLET=nft
47
48.PHONY: bench-fungible
49bench-fungible:
50 make _bench PALLET=fungible
51
52.PHONY: bench-refungible
53bench-refungible:
54 make _bench PALLET=refungible
55
56.PHONY: bench-nonfungible
57bench-nonfungible:
58 make _bench PALLET=nonfungible
4659
47.PHONY: bench60.PHONY: bench
48bench: bench-evm-migration bench-nft61bench: bench-evm-migration bench-nft bench-fungible bench-refungible bench-nonfungible
4962
addedclient/rpc/Cargo.tomldiffbeforeafterboth

no changes

addedclient/rpc/src/lib.rsdiffbeforeafterboth

no changes

modifiedcrates/evm-coder-macros/src/solidity_interface.rsdiffbeforeafterboth
672 quote! {672 quote! {
673 #[derive(Debug)]673 #[derive(Debug)]
674 pub enum #call_name {674 pub enum #call_name {
675 ERC165Call(::evm_coder::ERC165Call),
675 #(676 #(
676 #calls,677 #calls,
677 )*678 )*
691 }692 }
692 pub fn supports_interface(interface_id: u32) -> bool {693 pub fn supports_interface(interface_id: u32) -> bool {
693 interface_id != 0xffffff && (694 interface_id != 0xffffff && (
695 interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||
694 interface_id == Self::interface_id()696 interface_id == Self::interface_id()
695 #(697 #(
696 || #supports_interface698 || #supports_interface
702 use core::fmt::Write;704 use core::fmt::Write;
703 let interface = SolidityInterface {705 let interface = SolidityInterface {
704 name: #solidity_name,706 name: #solidity_name,
705 is: &["Dummy", #(707 is: &["Dummy", "ERC165", #(
706 #solidity_is,708 #solidity_is,
707 )* #(709 )* #(
708 #solidity_events_is,710 #solidity_events_is,
712 )*),714 )*),
713 };715 };
714 if is_impl {716 if is_impl {
715 tc.collect("// Common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\n".into());717 tc.collect("// Common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\ncontract ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool) {\n\t\trequire(false, stub_error);\n\t\tinterfaceID;\n\t\treturn true;\n\t}\n}\n".into());
716 } else {718 } else {
717 tc.collect("// Common stubs holder\ninterface Dummy {\n}\n".into());719 tc.collect("// Common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());
718 }720 }
719 #(721 #(
720 #solidity_generators722 #solidity_generators
737 fn parse(method_id: u32, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {739 fn parse(method_id: u32, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {
738 use ::evm_coder::abi::AbiRead;740 use ::evm_coder::abi::AbiRead;
739 match method_id {741 match method_id {
742 ::evm_coder::ERC165Call::INTERFACE_ID => return Ok(::evm_coder::ERC165Call::parse(method_id, reader)?.map(Self::ERC165Call)),
740 #(743 #(
741 #parsers,744 #parsers,
742 )*745 )*
757 #(760 #(
758 #call_variants,761 #call_variants,
759 )*762 )*
763 InternalCall::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}) => {
764 let mut writer = ::evm_coder::abi::AbiWriter::default();
765 writer.bool(&InternalCall::supports_interface(interface_id));
766 return Ok(writer);
767 }
760 _ => {},768 _ => {},
761 }769 }
762 let mut writer = ::evm_coder::abi::AbiWriter::default();770 let mut writer = ::evm_coder::abi::AbiWriter::default();
modifiedcrates/evm-coder/src/lib.rsdiffbeforeafterboth
2#[cfg(not(feature = "std"))]2#[cfg(not(feature = "std"))]
3extern crate alloc;3extern crate alloc;
44
5use abi::{AbiReader, AbiWriter};5use abi::{AbiRead, AbiReader, AbiWriter};
6pub use evm_coder_macros::{event_topic, fn_selector, solidity_interface, solidity, ToLog};6pub use evm_coder_macros::{event_topic, fn_selector, solidity_interface, solidity, ToLog};
7pub mod abi;7pub mod abi;
8pub mod events;8pub mod events;
61 fn call(&mut self, call: types::Msg<C>) -> execution::Result<AbiWriter>;61 fn call(&mut self, call: types::Msg<C>) -> execution::Result<AbiWriter>;
62}62}
63
64/// Implementation is implicitly provided for all interfaces
65///
66/// Note: no Callable implementation is provided
67#[derive(Debug)]
68pub enum ERC165Call {
69 SupportsInterface { interface_id: types::bytes4 },
70}
71
72impl ERC165Call {
73 pub const INTERFACE_ID: types::bytes4 = 0x01ffc9a7;
74}
75
76impl Call for ERC165Call {
77 fn parse(selector: u32, input: &mut AbiReader) -> execution::Result<Option<Self>> {
78 if selector != Self::INTERFACE_ID {
79 return Ok(None);
80 }
81 Ok(Some(Self::SupportsInterface {
82 interface_id: input.abi_read()?,
83 }))
84 }
85}
6386
64#[macro_export]87#[macro_export]
65macro_rules! generate_stubgen {88macro_rules! generate_stubgen {
modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
55
6use cumulus_primitives_core::ParaId;6use cumulus_primitives_core::ParaId;
7use nft_runtime::*;7use nft_runtime::*;
8use nft_data_structs::*;
9use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};8use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};
10use sc_service::ChainType;9use sc_service::ChainType;
11use sp_core::{sr25519, Pair, Public};10use sp_core::{sr25519, Pair, Public};
168 treasury: Default::default(),167 treasury: Default::default(),
169 sudo: SudoConfig { key: root_key },168 sudo: SudoConfig { key: root_key },
170 vesting: VestingConfig { vesting: vec![] },169 vesting: VestingConfig { vesting: vec![] },
171 nft: NftConfig {
172 collection_id: vec![(
173 1,
174 Collection {
175 owner: get_account_id_from_seed::<sr25519::Public>("Alice"),
176 mode: CollectionMode::NFT,
177 access: AccessMode::Normal,
178 decimal_points: 0,
179 name: vec![],
180 description: vec![],
181 token_prefix: vec![],
182 mint_mode: false,
183 offchain_schema: vec![],
184 schema_version: SchemaVersion::default(),
185 sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<
186 sr25519::Public,
187 >("Alice")),
188 const_on_chain_schema: vec![],
189 variable_on_chain_schema: vec![],
190 limits: CollectionLimits::default(),
191 meta_update_permission: MetaUpdatePermission::ItemOwner,
192 transfers_enabled: true,
193 },
194 )],
195 nft_item_id: vec![],
196 fungible_item_id: vec![],
197 refungible_item_id: vec![],
198 },
199 parachain_info: nft_runtime::ParachainInfoConfig { parachain_id: id },170 parachain_info: nft_runtime::ParachainInfoConfig { parachain_id: id },
200 aura: nft_runtime::AuraConfig {171 aura: nft_runtime::AuraConfig {
201 authorities: initial_authorities,172 authorities: initial_authorities,
modifiednode/rpc/Cargo.tomldiffbeforeafterboth
49fc-mapping-sync = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }49fc-mapping-sync = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
5050
51pallet-nft = { path = "../../pallets/nft" }51pallet-nft = { path = "../../pallets/nft" }
52uc-rpc = { path = "../../client/rpc" }
53up-rpc = { path = "../../primitives/rpc" }
52nft-runtime = { path = "../../runtime" }54nft-runtime = { path = "../../runtime" }
5355
54[features]56[features]
modifiednode/rpc/src/lib.rsdiffbeforeafterboth
1use nft_runtime::{Hash, AccountId, Index, opaque::Block, BlockNumber, Balance};1use nft_runtime::{Hash, AccountId, CrossAccountId, Index, opaque::Block, BlockNumber, Balance};
2use fc_rpc::{2use fc_rpc::{
3 EthBlockDataCache, OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override, StorageOverride,3 EthBlockDataCache, OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override, StorageOverride,
4};4};
9 backend::{AuxStore, StorageProvider},9 backend::{AuxStore, StorageProvider},
10 client::BlockchainEvents,10 client::BlockchainEvents,
11};11};
12use pallet_nft::NftApi;
13use sc_finality_grandpa::{12use sc_finality_grandpa::{
14 FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState,13 FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState,
15};14};
101where100where
102 Block: sp_api::BlockT,101 Block: sp_api::BlockT,
103 C: ProvideRuntimeApi<Block>,102 C: ProvideRuntimeApi<Block>,
104 C::Api: pallet_nft::NftApi<Block>,103 C::Api: up_rpc::NftApi<Block, CrossAccountId, AccountId>,
105{104{
106 fn code(&self, block: &sp_api::BlockId<Block>, account: sp_core::H160) -> Option<Vec<u8>> {105 fn code(&self, block: &sp_api::BlockId<Block>, account: sp_core::H160) -> Option<Vec<u8>> {
106 use up_rpc::NftApi;
107 self.client107 self.client
108 .runtime_api()108 .runtime_api()
109 .eth_contract_code(block, account)109 .eth_contract_code(block, account)
127 // C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,127 // C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,
128 C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,128 C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
129 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,129 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,
130 C::Api: pallet_nft::NftApi<Block>,130 C::Api: up_rpc::NftApi<Block, CrossAccountId, AccountId>,
131 B: sc_client_api::Backend<Block> + Send + Sync + 'static,131 B: sc_client_api::Backend<Block> + Send + Sync + 'static,
132 B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,132 B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,
133 SC: SelectChain<Block> + 'static,133 SC: SelectChain<Block> + 'static,
139 EthPubSubApiServer, EthSigner, HexEncodedIdProvider, NetApi, NetApiServer, Web3Api,139 EthPubSubApiServer, EthSigner, HexEncodedIdProvider, NetApi, NetApiServer, Web3Api,
140 Web3ApiServer,140 Web3ApiServer,
141 };141 };
142 use uc_rpc::{NftApi, Nft};
142 // use pallet_contracts_rpc::{Contracts, ContractsApi};143 // use pallet_contracts_rpc::{Contracts, ContractsApi};
143 use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};144 use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};
144 use substrate_frame_rpc_system::{FullSystem, SystemApi};145 use substrate_frame_rpc_system::{FullSystem, SystemApi};
203 max_past_logs,204 max_past_logs,
204 block_data_cache.clone(),205 block_data_cache.clone(),
205 )));206 )));
207 io.extend_with(NftApi::to_delegate(Nft::new(client.clone())));
206208
207 if let Some(filter_pool) = filter_pool {209 if let Some(filter_pool) = filter_pool {
208 io.extend_with(EthFilterApiServer::to_delegate(EthFilterApi::new(210 io.extend_with(EthFilterApiServer::to_delegate(EthFilterApi::new(
addedpallets/common/Cargo.tomldiffbeforeafterboth

no changes

addedpallets/common/src/account.rsdiffbeforeafterboth

no changes

addedpallets/common/src/benchmarking.rsdiffbeforeafterboth

no changes

addedpallets/common/src/erc.rsdiffbeforeafterboth

no changes

addedpallets/common/src/eth.rsdiffbeforeafterboth

no changes

addedpallets/common/src/lib.rsdiffbeforeafterboth

no changes

modifiedpallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth
16 execution::{self, Result},16 execution::{self, Result},
17 types::{Msg, value},17 types::{Msg, value},
18 };18 };
19 use frame_support::ensure;19 use frame_support::{ensure};
20 use pallet_evm::{ExitError, ExitReason, ExitRevert, ExitSucceed, PrecompileOutput};20 use pallet_evm::{ExitError, ExitReason, ExitRevert, ExitSucceed, PrecompileOutput};
21 pub use frame_support::dispatch::DispatchResult;21 pub use frame_support::dispatch::DispatchResult;
22 use pallet_ethereum::EthereumTransactionSender;22 use pallet_ethereum::EthereumTransactionSender;
106 self.logs.borrow_mut().push(log);106 self.logs.borrow_mut().push(log);
107 Ok(())107 Ok(())
108 }108 }
109 /// Doesn't consumes any gas, should be used after consume_log_sub
110 pub fn log_infallible(&self, log: impl ToLog) {
111 self.logs.borrow_mut().push(log.to_log(self.contract));
112 }
109 pub fn retrieve_logs(self) -> Vec<Log> {113 pub fn retrieve_logs(self) -> Vec<Log> {
110 self.logs.into_inner()114 self.logs.into_inner()
111 }115 }
116 pub fn consume_sload_sub(&self) -> DispatchResult {120 pub fn consume_sload_sub(&self) -> DispatchResult {
117 self.consume_gas_sub(G_SLOAD_WORD)121 self.consume_gas_sub(G_SLOAD_WORD)
118 }122 }
123 pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {
124 self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))
125 }
119 pub fn consume_sstore_sub(&self) -> DispatchResult {126 pub fn consume_sstore_sub(&self) -> DispatchResult {
120 self.consume_gas_sub(G_SSTORE_WORD)127 self.consume_gas_sub(G_SSTORE_WORD)
121 }128 }
129 pub fn consume_log_sub(&self, topics: usize, data: usize) -> DispatchResult {
130 self.consume_gas_sub(log_price(data, topics))
131 }
122 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {132 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {
123 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);133 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);
124 let mut gas_limit = self.gas_limit.borrow_mut();134 let mut gas_limit = self.gas_limit.borrow_mut();
modifiedpallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth
9 string stub_error = "this contract is implemented in native";9 string stub_error = "this contract is implemented in native";
10}10}
11
12contract ERC165 is Dummy {
13 function supportsInterface(bytes4 interfaceID)
14 external
15 view
16 returns (bool)
17 {
18 require(false, stub_error);
19 interfaceID;
20 return true;
21 }
22}
1123
12contract ContractHelpers is Dummy {24contract ContractHelpers is Dummy, ERC165 {
13 // Selector: contractOwner(address) 5152b14c25 // Selector: contractOwner(address) 5152b14c
14 function contractOwner(address contractAddress)26 function contractOwner(address contractAddress)
15 public27 public
addedpallets/fungible/Cargo.tomldiffbeforeafterboth

no changes

addedpallets/fungible/src/benchmarking.rsdiffbeforeafterboth

no changes

addedpallets/fungible/src/common.rsdiffbeforeafterboth

no changes

addedpallets/fungible/src/erc.rsdiffbeforeafterboth

no changes

addedpallets/fungible/src/lib.rsdiffbeforeafterboth

no changes

addedpallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterboth

binary blob — no preview

addedpallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth

no changes

addedpallets/fungible/src/weights.rsdiffbeforeafterboth

no changes

modifiedpallets/inflation/src/benchmarking.rsdiffbeforeafterboth
3use super::*;3use super::*;
4use crate::Module as Inflation;4use crate::Module as Inflation;
55
6use sp_std::prelude::*;
7use frame_system::RawOrigin;
8use frame_benchmarking::{benchmarks};6use frame_benchmarking::{benchmarks};
9use frame_support::traits::OnInitialize;7use frame_support::traits::OnInitialize;
108
modifiedpallets/nft/Cargo.tomldiffbeforeafterboth
1616
17[features]17[features]
18default = ['std']18default = ['std']
19runtime-benchmarks = ['frame-benchmarking']19runtime-benchmarks = ['frame-benchmarking', 'pallet-common/runtime-benchmarks']
20std = [20std = [
21 'codec/std',21 'codec/std',
22 'serde/std',22 'serde/std',
27 'pallet-timestamp/std',27 'pallet-timestamp/std',
28 'pallet-randomness-collective-flip/std',28 'pallet-randomness-collective-flip/std',
29 'pallet-transaction-payment/std',29 'pallet-transaction-payment/std',
30 'pallet-common/std',
31 'pallet-fungible/std',
32 'pallet-nonfungible/std',
33 'pallet-refungible/std',
30 'fp-evm/std',34 'fp-evm/std',
31 'nft-data-structs/std',35 'nft-data-structs/std',
32 'up-sponsorship/std',36 'up-sponsorship/std',
145fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }151fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
146hex-literal = "0.3.3"152hex-literal = "0.3.3"
153
154pallet-common = { default-features = false, path = "../common" }
155pallet-fungible = { default-features = false, path = "../fungible" }
156pallet-nonfungible = { default-features = false, path = "../nonfungible" }
157pallet-refungible = { default-features = false, path = "../refungible" }
147158
modifiedpallets/nft/src/benchmarking.rsdiffbeforeafterboth
7use nft_data_structs::*;7use nft_data_structs::*;
8use core::convert::TryInto;8use core::convert::TryInto;
9use sp_runtime::DispatchError;9use sp_runtime::DispatchError;
10use pallet_common::benchmarking::{create_data, create_u16_data};
1011
11const SEED: u32 = 1;12const SEED: u32 = 1;
12
13fn create_data(size: usize) -> Vec<u8> {
14 (0..size).map(|v| (v & 0xff) as u8).collect()
15}
16fn create_u16_data(size: usize) -> Vec<u16> {
17 (0..size).map(|v| (v & 0xffff) as u16).collect()
18}
19
20fn default_nft_data() -> CreateItemData {
21 CreateItemData::NFT(CreateNftData {
22 const_data: create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap(),
23 variable_data: create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap(),
24 })
25}
26
27fn default_fungible_data() -> CreateItemData {
28 CreateItemData::Fungible(CreateFungibleData { value: 1000 })
29}
30
31fn default_re_fungible_data() -> CreateItemData {
32 CreateItemData::ReFungible(CreateReFungibleData {
33 const_data: create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap(),
34 variable_data: create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap(),
35 pieces: 1000,
36 })
37}
3813
39fn create_collection_helper<T: Config>(14fn create_collection_helper<T: Config>(
40 owner: T::AccountId,15 owner: T::AccountId,
55 token_prefix,30 token_prefix,
56 mode,31 mode,
57 )?;32 )?;
58 Ok(CreatedCollectionCount::get())33 Ok(<pallet_common::CreatedCollectionCount<T>>::get())
59}34}
60fn create_nft_collection<T: Config>(owner: T::AccountId) -> Result<CollectionId, DispatchError> {35fn create_nft_collection<T: Config>(owner: T::AccountId) -> Result<CollectionId, DispatchError> {
61 create_collection_helper::<T>(owner, CollectionMode::NFT)36 create_collection_helper::<T>(owner, CollectionMode::NFT)
62}37}
63fn create_fungible_collection<T: Config>(
64 owner: T::AccountId,
65) -> Result<CollectionId, DispatchError> {
66 create_collection_helper::<T>(owner, CollectionMode::Fungible(0))
67}
68fn create_refungible_collection<T: Config>(
69 owner: T::AccountId,
70) -> Result<CollectionId, DispatchError> {
71 create_collection_helper::<T>(owner, CollectionMode::ReFungible)
72}
7338
74benchmarks! {39benchmarks! {
7540
82 T::Currency::deposit_creating(&caller, T::CollectionCreationPrice::get());47 T::Currency::deposit_creating(&caller, T::CollectionCreationPrice::get());
83 }: _(RawOrigin::Signed(caller.clone()), col_name.clone(), col_desc.clone(), token_prefix.clone(), mode)48 }: _(RawOrigin::Signed(caller.clone()), col_name.clone(), col_desc.clone(), token_prefix.clone(), mode)
84 verify {49 verify {
85 assert_eq!(<Pallet<T>>::collection_id(2).unwrap().owner, caller);50 assert_eq!(<pallet_common::CollectionById<T>>::get(CollectionId(1)).unwrap().owner, caller);
86 }51 }
8752
88 destroy_collection {53 destroy_collection {
129 let caller: T::AccountId = account("caller", 0, SEED);94 let caller: T::AccountId = account("caller", 0, SEED);
130 let collection = create_nft_collection::<T>(caller.clone())?;95 let collection = create_nft_collection::<T>(caller.clone())?;
131 let new_admin: T::AccountId = account("admin", 0, SEED);96 let new_admin: T::AccountId = account("admin", 0, SEED);
132 <Pallet<T>>::add_collection_admin(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(new_admin.clone()))?;97 <Pallet<T>>::add_collection_admin(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(new_admin.clone()))?;
133 }: _(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(new_admin))98 }: _(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(new_admin))
13499
135 set_collection_sponsor {100 set_collection_sponsor {
140 confirm_sponsorship {105 confirm_sponsorship {
141 let caller: T::AccountId = account("caller", 0, SEED);106 let caller: T::AccountId = account("caller", 0, SEED);
142 let collection = create_nft_collection::<T>(caller.clone())?;107 let collection = create_nft_collection::<T>(caller.clone())?;
143 <Pallet<T>>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone())?;108 <Pallet<T>>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), collection, caller.clone())?;
144 }: _(RawOrigin::Signed(caller.clone()), collection)109 }: _(RawOrigin::Signed(caller.clone()), collection)
145110
146 remove_collection_sponsor {111 remove_collection_sponsor {
147 let caller: T::AccountId = account("caller", 0, SEED);112 let caller: T::AccountId = account("caller", 0, SEED);
148 let collection = create_nft_collection::<T>(caller.clone())?;113 let collection = create_nft_collection::<T>(caller.clone())?;
149 <Pallet<T>>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone())?;114 <Pallet<T>>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), collection, caller.clone())?;
150 <Pallet<T>>::confirm_sponsorship(RawOrigin::Signed(caller.clone()).into(), 2)?;115 <Pallet<T>>::confirm_sponsorship(RawOrigin::Signed(caller.clone()).into(), collection)?;
151 }: _(RawOrigin::Signed(caller.clone()), collection)116 }: _(RawOrigin::Signed(caller.clone()), collection)
152
153 // nft item
154 create_item_nft {
155 let b in 0..(CUSTOM_DATA_LIMIT * 2);
156
157 let caller: T::AccountId = account("caller", 0, SEED);
158 let collection = create_nft_collection::<T>(caller.clone())?;
159 let data = CreateItemData::NFT(CreateNftData {
160 const_data: create_data(b.min(CUSTOM_DATA_LIMIT) as usize).try_into().unwrap(),
161 variable_data: create_data(b.saturating_sub(CUSTOM_DATA_LIMIT) as usize).try_into().unwrap(),
162 });
163 }: create_item(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
164
165 create_multiple_items_nft {
166 // TODO: Take item data size into account. As create_item_nft bench shows, this parameter has no effect on execution time,
167 // but it may if we increase CUSTOM_DATA_LIMIT
168 let b in 1..1000;
169
170 let caller: T::AccountId = account("caller", 0, SEED);
171 let collection = create_nft_collection::<T>(caller.clone())?;
172 let data = (0..b).map(|_| default_nft_data()).collect();
173 }: create_multiple_items(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
174
175 // fungible item
176 create_item_fungible {
177 let caller: T::AccountId = account("caller", 0, SEED);
178 let collection = create_fungible_collection::<T>(caller.clone())?;
179 let data = CreateItemData::Fungible(CreateFungibleData {
180 value: 1000,
181 });
182 }: create_item(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
183
184 create_multiple_items_fungible {
185 let b in 1..1000;
186
187 let caller: T::AccountId = account("caller", 0, SEED);
188 let collection = create_fungible_collection::<T>(caller.clone())?;
189 let data = (0..b).map(|_| default_fungible_data()).collect();
190 }: create_multiple_items(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
191
192 // refungible item
193 create_item_refungible {
194 let b in 0..(CUSTOM_DATA_LIMIT * 2);
195
196 let caller: T::AccountId = account("caller", 0, SEED);
197 let collection = create_refungible_collection::<T>(caller.clone())?;
198 let data = CreateItemData::ReFungible(CreateReFungibleData {
199 const_data: create_data(b.min(CUSTOM_DATA_LIMIT) as usize).try_into().unwrap(),
200 variable_data: create_data(b.saturating_sub(CUSTOM_DATA_LIMIT) as usize).try_into().unwrap(),
201 pieces: 1000,
202 });
203 }: create_item(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
204
205 create_multiple_items_refungible {
206 // TODO: Take item data size into account. As create_item_nft bench shows, this parameter has no effect on execution time,
207 // but it may if we increase CUSTOM_DATA_LIMIT
208 let b in 1..1000;
209
210 let caller: T::AccountId = account("caller", 0, SEED);
211 let collection = create_refungible_collection::<T>(caller.clone())?;
212 let data = (0..b).map(|_| default_re_fungible_data()).collect();
213 }: create_multiple_items(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
214
215 burn_item_nft {
216 let caller: T::AccountId = account("caller", 0, SEED);
217 let collection = create_nft_collection::<T>(caller.clone())?;
218 let data = default_nft_data();
219 <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(caller.clone()), data)?;
220 }: burn_item(RawOrigin::Signed(caller.clone()), collection, 1, 1)
221
222 transfer_nft {
223 let caller: T::AccountId = account("caller", 0, SEED);
224 let collection = create_nft_collection::<T>(caller.clone())?;
225 let recipient: T::AccountId = account("recipient", 0, SEED);
226 let data = default_nft_data();
227 <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(caller.clone()), data)?;
228 }: transfer(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), collection, 1, 1)
229
230 transfer_fungible {
231 let caller: T::AccountId = account("caller", 0, SEED);
232 let collection = create_fungible_collection::<T>(caller.clone())?;
233 let recipient: T::AccountId = account("recipient", 0, SEED);
234 let data = default_fungible_data();
235 <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(caller.clone()), data)?;
236 }: transfer(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), collection, 1, 1)
237
238 transfer_refungible {
239 let caller: T::AccountId = account("caller", 0, SEED);
240 let collection = create_refungible_collection::<T>(caller.clone())?;
241 let recipient: T::AccountId = account("recipient", 0, SEED);
242 let data = default_re_fungible_data();
243 <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(caller.clone()), data)?;
244 }: transfer(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), collection, 1, 1)
245117
246 set_transfers_enabled_flag {118 set_transfers_enabled_flag {
247 let caller: T::AccountId = account("caller", 0, SEED);119 let caller: T::AccountId = account("caller", 0, SEED);
248 let collection = create_nft_collection::<T>(caller.clone())?;120 let collection = create_nft_collection::<T>(caller.clone())?;
249 }: _(RawOrigin::Signed(caller.clone()), collection, false)121 }: _(RawOrigin::Signed(caller.clone()), collection, false)
250
251 approve_nft {
252 let caller: T::AccountId = account("caller", 0, SEED);
253 let collection = create_nft_collection::<T>(caller.clone())?;
254 let recipient: T::AccountId = account("recipient", 0, SEED);
255 let data = default_nft_data();
256 <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(caller.clone()), data)?;
257 }: approve(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), collection, 1, 1)
258
259 // Nft
260 transfer_from_nft {
261 let caller: T::AccountId = account("caller", 0, SEED);
262 let collection = create_nft_collection::<T>(caller.clone())?;
263 let recipient: T::AccountId = account("recipient", 0, SEED);
264 let data = default_nft_data();
265 <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(caller.clone()), data)?;
266 <Pallet<T>>::approve(RawOrigin::Signed(caller.clone()).into(), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)?;
267 }: transfer_from(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)
268
269 // Fungible
270 transfer_from_fungible {
271 let caller: T::AccountId = account("caller", 0, SEED);
272 let collection = create_fungible_collection::<T>(caller.clone())?;
273 let recipient: T::AccountId = account("recipient", 0, SEED);
274 let data = default_fungible_data();
275 <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(caller.clone()), data)?;
276 <Pallet<T>>::approve(RawOrigin::Signed(caller.clone()).into(), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)?;
277 }: transfer_from(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)
278
279 // ReFungible
280 transfer_from_refungible {
281 let caller: T::AccountId = account("caller", 0, SEED);
282 let collection = create_refungible_collection::<T>(caller.clone())?;
283 let recipient: T::AccountId = account("recipient", 0, SEED);
284 let data = default_re_fungible_data();
285 <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(caller.clone()), data)?;
286 <Pallet<T>>::approve(RawOrigin::Signed(caller.clone()).into(), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)?;
287 }: transfer_from(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)
288122
289 set_offchain_schema {123 set_offchain_schema {
290 let b in 0..OFFCHAIN_SCHEMA_LIMIT;124 let b in 0..OFFCHAIN_SCHEMA_LIMIT;
308 let caller: T::AccountId = account("caller", 0, SEED);142 let caller: T::AccountId = account("caller", 0, SEED);
309 let collection = create_nft_collection::<T>(caller.clone())?;143 let collection = create_nft_collection::<T>(caller.clone())?;
310 let data = create_data(b as usize);144 let data = create_data(b as usize);
311 }: set_variable_on_chain_schema(RawOrigin::Signed(caller.clone()), 2, data)145 }: set_variable_on_chain_schema(RawOrigin::Signed(caller.clone()), collection, data)
312
313 set_variable_meta_data_nft {
314 let b in 0..CUSTOM_DATA_LIMIT;
315
316 let caller: T::AccountId = account("caller", 0, SEED);
317 let collection = create_nft_collection::<T>(caller.clone())?;
318 let data = default_nft_data();
319 <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(caller.clone()), data)?;
320 let data = create_data(b as usize);
321 }: set_variable_meta_data(RawOrigin::Signed(caller.clone()), collection, 1, data)
322146
323 set_schema_version {147 set_schema_version {
324 let caller: T::AccountId = account("caller", 0, SEED);148 let caller: T::AccountId = account("caller", 0, SEED);
325 let collection = create_nft_collection::<T>(caller.clone())?;149 let collection = create_nft_collection::<T>(caller.clone())?;
326 }: set_schema_version(RawOrigin::Signed(caller.clone()), 2, SchemaVersion::Unique)150 }: set_schema_version(RawOrigin::Signed(caller.clone()), collection, SchemaVersion::Unique)
327151
328 set_collection_limits{152 set_collection_limits{
329 let caller: T::AccountId = account("caller", 0, SEED);153 let caller: T::AccountId = account("caller", 0, SEED);
330 let collection = create_nft_collection::<T>(caller.clone())?;154 let collection = create_nft_collection::<T>(caller.clone())?;
331155
332 let cl = CollectionLimits {156 let cl = CollectionLimits {
333 account_token_ownership_limit: 0,157 account_token_ownership_limit: Some(0),
334 sponsored_data_size: 0,158 sponsored_data_size: 0,
335 token_limit: 1,159 token_limit: 1,
336 sponsor_transfer_timeout: 0,160 sponsor_transfer_timeout: 0,
337 owner_can_destroy: true,161 owner_can_destroy: true,
338 owner_can_transfer: true,162 owner_can_transfer: true,
339 sponsored_data_rate_limit: None,163 sponsored_data_rate_limit: None,
340 };164 };
341 }: set_collection_limits(RawOrigin::Signed(caller.clone()), 2, cl)165 }: set_collection_limits(RawOrigin::Signed(caller.clone()), collection, cl)
166
167 set_meta_update_permission_flag {
168 let caller: T::AccountId = account("caller", 0, SEED);
169 let collection = create_nft_collection::<T>(caller.clone())?;
170 }: _(RawOrigin::Signed(caller.clone()), collection, MetaUpdatePermission::Admin)
342}171}
343172
addedpallets/nft/src/common.rsdiffbeforeafterboth

no changes

addedpallets/nft/src/dispatch.rsdiffbeforeafterboth

no changes

deletedpallets/nft/src/eth/account.rsdiffbeforeafterboth

no changes

deletedpallets/nft/src/eth/erc.rsdiffbeforeafterboth

no changes

modifiedpallets/nft/src/eth/mod.rsdiffbeforeafterboth
1pub mod account;1pub mod sponsoring;
2
3use pallet_common::{
4 CollectionById,
2pub mod erc;5 erc::CommonEvmHandler,
6 eth::{map_eth_to_id, map_eth_to_token_id},
7};
3pub mod sponsoring;8use pallet_fungible::FungibleHandle;
4
5use pallet_evm_coder_substrate::call_internal;9use pallet_nonfungible::NonfungibleHandle;
10use pallet_refungible::{RefungibleHandle, erc::RefungibleTokenHandle};
6use sp_std::borrow::ToOwned;11use sp_std::borrow::ToOwned;
7use sp_std::vec::Vec;12use sp_std::vec::Vec;
8use pallet_evm::{PrecompileOutput};13use pallet_evm::{PrecompileOutput};
9use sp_core::{H160, U256};14use sp_core::{H160, U256};
10use frame_support::storage::StorageMap;
11use crate::{Config, CollectionById, CollectionHandle, CollectionId, CollectionMode};15use crate::{CollectionMode, Config, dispatch::Dispatched};
12use erc::{UniqueFungibleCall, UniqueNFTCall};16use pallet_common::CollectionHandle;
1317
14pub struct NftErcSupport<T: Config>(core::marker::PhantomData<T>);18pub struct NftErcSupport<T: Config>(core::marker::PhantomData<T>);
15
16// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection
17// TODO: Unhardcode prefix
18const ETH_ACCOUNT_PREFIX: [u8; 16] = [
19 0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
20];
21
22fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {
23 if eth[0..16] != ETH_ACCOUNT_PREFIX {
24 return None;
25 }
26 let mut id_bytes = [0; 4];
27 id_bytes.copy_from_slice(&eth[16..20]);
28 Some(u32::from_be_bytes(id_bytes))
29}
30pub fn collection_id_to_address(id: u32) -> H160 {
31 let mut out = [0; 20];
32 out[0..16].copy_from_slice(&ETH_ACCOUNT_PREFIX);
33 out[16..20].copy_from_slice(&u32::to_be_bytes(id));
34 H160(out)
35}
36
37/*
38fn call_internal<T: Config>(
39 collection: &mut CollectionHandle<T>,
40 caller: caller,
41 method_id: u32,
42 mut input: AbiReader,
43 value: U256,
44) -> Result<Option<AbiWriter>> {
45 match collection.mode.clone() {
46 CollectionMode::Fungible(_) => {
47 call_internal();
48 let call = match UniqueFungibleCall::parse(method_id, &mut input)? {
49 Some(v) => v,
50 None => {
51 #[cfg(feature = "std")]
52 {
53 println!("Method not found");
54 }
55 return Ok(None);
56 }
57 };
58 Ok(Some(<CollectionHandle<T> as UniqueFungible>::call(
59 collection,
60 Msg {
61 call,
62 caller,
63 value,
64 },
65 )?))
66 }
67 CollectionMode::NFT => {
68 let call = match UniqueNFTCall::parse(method_id, &mut input)? {
69 Some(v) => v,
70 None => return Ok(None),
71 };
72 Ok(Some(<CollectionHandle<T> as UniqueNFT>::call(
73 collection,
74 Msg {
75 call,
76 caller,
77 value,
78 },
79 )?))
80 }
81 _ => Err("erc calls only supported to fungible and nft collections for now".into()),
82 }
83}*/
8419
85impl<T: Config> pallet_evm::OnMethodCall<T> for NftErcSupport<T> {20impl<T: Config> pallet_evm::OnMethodCall<T> for NftErcSupport<T> {
86 fn is_reserved(target: &H160) -> bool {21 fn is_reserved(target: &H160) -> bool {
92 .unwrap_or(false)27 .unwrap_or(false)
93 }28 }
94 fn get_code(target: &H160) -> Option<Vec<u8>> {29 fn get_code(target: &H160) -> Option<Vec<u8>> {
95 map_eth_to_id(target)30 if let Some(collection_id) = map_eth_to_id(target) {
96 .and_then(<CollectionById<T>>::get)31 let collection = <CollectionById<T>>::get(collection_id)?;
97 .map(|collection| {32 Some(
98 match collection.mode {33 match collection.mode {
99 CollectionMode::NFT => include_bytes!("stubs/UniqueNFT.raw") as &[u8],34 CollectionMode::NFT => <NonfungibleHandle<T>>::CODE,
100 CollectionMode::Fungible(_) => {35 CollectionMode::Fungible(_) => <FungibleHandle<T>>::CODE,
101 include_bytes!("stubs/UniqueFungible.raw") as &[u8]
102 }
103 CollectionMode::ReFungible => {36 CollectionMode::ReFungible => <RefungibleHandle<T>>::CODE,
104 include_bytes!("stubs/UniqueRefungible.raw") as &[u8]
105 }
106 }37 }
107 .to_owned()38 .to_owned(),
108 })39 )
40 } else if let Some((collection_id, _token_id)) = map_eth_to_token_id(target) {
41 let collection = <CollectionById<T>>::get(collection_id)?;
42 if collection.mode != CollectionMode::ReFungible {
43 return None;
44 }
45 // TODO: check token existence
46 Some(<RefungibleTokenHandle<T>>::CODE.to_owned())
47 } else {
48 None
49 }
109 }50 }
110 fn call(51 fn call(
111 source: &H160,52 source: &H160,
114 input: &[u8],55 input: &[u8],
115 value: U256,56 value: U256,
116 ) -> Option<PrecompileOutput> {57 ) -> Option<PrecompileOutput> {
58 if let Some(collection_id) = map_eth_to_id(target) {
117 let mut collection = map_eth_to_id(target)59 let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
118 .and_then(|id| <CollectionHandle<T>>::get_with_gas_limit(id, gas_limit))?;
119 let result = match collection.mode {60 let dispatched = Dispatched::dispatch(collection);
61
62 match dispatched {
120 CollectionMode::NFT => {63 Dispatched::Fungible(h) => h.call(source, input, value),
121 call_internal::<UniqueNFTCall, _>(*source, &mut collection, value, input)
122 }
123 CollectionMode::Fungible(_) => {64 Dispatched::Nonfungible(h) => h.call(source, input, value),
124 call_internal::<UniqueFungibleCall, _>(*source, &mut collection, value, input)
125 }
126 _ => return None,65 Dispatched::Refungible(h) => h.call(source, input, value),
127 };66 }
67 } else if let Some((collection_id, token_id)) = map_eth_to_token_id(target) {
68 let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
128 collection.recorder.evm_to_precompile_output(result)69 if collection.mode != CollectionMode::ReFungible {
70 return None;
71 }
72
73 let handle = RefungibleHandle::cast(collection);
74 // TODO: check token existence
75 RefungibleTokenHandle(handle, token_id).call(source, input, value)
76 } else {
77 None
78 }
129 }79 }
130}80}
13181
modifiedpallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth
1//! Implements EVM sponsoring logic via OnChargeEVMTransaction1//! Implements EVM sponsoring logic via OnChargeEVMTransaction
22
3use crate::{3use crate::{Collection, Config, FungibleTransferBasket, NftTransferBasket};
4 Collection, CollectionById, Config, FungibleTransferBasket, NftTransferBasket,
5 eth::{account::EvmBackwardsAddressMapping, map_eth_to_id},
6};
7use evm_coder::{Call, abi::AbiReader};4use evm_coder::{Call, abi::AbiReader};
8use frame_support::{5use frame_support::{
9 storage::{StorageMap, StorageDoubleMap},6 storage::{StorageDoubleMap},
10};7};
8use pallet_common::eth::map_eth_to_id;
11use sp_core::H160;9use sp_core::H160;
12use sp_std::prelude::*;10use sp_std::prelude::*;
13use up_sponsorship::SponsorshipHandler;11use up_sponsorship::SponsorshipHandler;
14use super::{12use core::marker::PhantomData;
15 account::CrossAccountId,
16 erc::{UniqueFungibleCall, UniqueNFTCall, ERC721Call, ERC20Call, ERC721UniqueExtensionsCall},
17};
18use core::convert::TryInto;13use core::convert::TryInto;
14use nft_data_structs::{CollectionId, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT};
15use pallet_common::{
16 CollectionById,
17 account::{CrossAccountId, EvmBackwardsAddressMapping},
18};
19
19use core::marker::PhantomData;20use pallet_nonfungible::erc::{UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721Call};
20use nft_data_structs::{NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT};21use pallet_fungible::erc::{UniqueFungibleCall, ERC20Call};
2122
22struct AnyError;23struct AnyError;
2324
24fn try_sponsor<T: Config>(25fn try_sponsor<T: Config>(
25 caller: &H160,26 caller: &H160,
26 collection_id: u32,27 collection_id: CollectionId,
27 collection: &Collection<T>,28 collection: &Collection<T>,
28 call: &[u8],29 call: &[u8],
29) -> Result<(), AnyError> {30) -> Result<(), AnyError> {
34 .map_err(|_| AnyError)?35 .map_err(|_| AnyError)?
35 .ok_or(AnyError)?;36 .ok_or(AnyError)?;
36 match call {37 match call {
37 UniqueNFTCall::ERC721UniqueExtensions(38 UniqueNFTCall::ERC721UniqueExtensions(ERC721UniqueExtensionsCall::Transfer {
38 ERC721UniqueExtensionsCall::TransferNft { token_id, .. },39 token_id,
40 ..
39 )41 })
40 | UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, .. }) => {42 | UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, .. }) => {
deletedpallets/nft/src/eth/stubs/UniqueFungible.rawdiffbeforeafterboth

binary blob — no preview

deletedpallets/nft/src/eth/stubs/UniqueFungible.soldiffbeforeafterboth

no changes

deletedpallets/nft/src/eth/stubs/UniqueNFT.rawdiffbeforeafterboth

binary blob — no preview

deletedpallets/nft/src/eth/stubs/UniqueNFT.soldiffbeforeafterboth

no changes

deletedpallets/nft/src/eth/stubs/UniqueRefungible.rawdiffbeforeafterboth

no changes

modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
16pub use serde::{Serialize, Deserialize};16pub use serde::{Serialize, Deserialize};
1717
18pub use frame_support::{18pub use frame_support::{
19 construct_runtime, decl_event, decl_module, decl_storage, decl_error,19 construct_runtime, decl_module, decl_storage, decl_error,
20 dispatch::DispatchResult,20 dispatch::DispatchResult,
21 ensure, fail, parameter_types,21 ensure, fail, parameter_types,
22 traits::{22 traits::{
23 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,23 ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced, Randomness,
24 Randomness, IsSubType, WithdrawReasons,24 IsSubType, WithdrawReasons,
25 },25 },
26 weights::{26 weights::{
27 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},27 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
28 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,28 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,
29 WeightToFeePolynomial, DispatchClass,29 WeightToFeePolynomial, DispatchClass,
30 },30 },
31 StorageValue, transactional,31 StorageValue, transactional,
32 pallet_prelude::DispatchResultWithPostInfo,
32};33};
33use scale_info::TypeInfo;34use scale_info::TypeInfo;
34use frame_system::{self as system, ensure_signed};35use frame_system::{self as system, ensure_signed};
35use sp_core::H160;36use sp_runtime::{sp_std::prelude::Vec};
36use sp_std::vec;
37use sp_runtime::{DispatchError, sp_std::prelude::Vec};
38use core::ops::{Deref, DerefMut};
39use nft_data_structs::{37use nft_data_structs::{
40 MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_REFUNGIBLE_PIECES,38 MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, CUSTOM_DATA_LIMIT,
41 CUSTOM_DATA_LIMIT, COLLECTION_NUMBER_LIMIT, ACCOUNT_TOKEN_OWNERSHIP_LIMIT,
42 VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, COLLECTION_ADMINS_LIMIT,39 VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, COLLECTION_ADMINS_LIMIT,
43 OFFCHAIN_SCHEMA_LIMIT, MAX_TOKEN_PREFIX_LENGTH, MAX_COLLECTION_NAME_LENGTH,40 OFFCHAIN_SCHEMA_LIMIT, AccessMode, Collection, CreateItemData, CollectionLimits, CollectionId,
44 MAX_COLLECTION_DESCRIPTION_LENGTH, AccessMode, Collection, CreateItemData, CollectionLimits,
45 CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, Ownership, NftItemType,41 CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
46 MetaUpdatePermission, FungibleItemType, ReFungibleItemType,
47};42};
43use pallet_common::{
44 account::CrossAccountId, CollectionHandle, IsAdmin, Pallet as PalletCommon,
45 Error as CommonError, CommonWeightInfo, Allowlist,
46};
47use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};
48use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
49use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};
4850
49#[cfg(test)]51#[cfg(test)]
50mod mock;52mod mock;
58pub use eth::sponsoring::NftEthSponsorshipHandler;60pub use eth::sponsoring::NftEthSponsorshipHandler;
5961
60pub use eth::NftErcSupport;62pub use eth::NftErcSupport;
61pub use eth::account::*;
62use eth::erc::{ERC20Events, ERC721Events};
6363
64pub mod common;
65use common::CommonWeights;
66pub mod dispatch;
67use dispatch::dispatch_call;
68
64#[cfg(feature = "runtime-benchmarks")]69#[cfg(feature = "runtime-benchmarks")]
65mod benchmarking;70mod benchmarking;
66pub mod weights;71pub mod weights;
69decl_error! {74decl_error! {
70 /// Error for non-fungible-token module.75 /// Error for non-fungible-token module.
71 pub enum Error for Module<T: Config> {76 pub enum Error for Module<T: Config> {
72 /// Total collections bound exceeded.
73 TotalCollectionsLimitExceeded,
74 /// Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.77 /// Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.
75 CollectionDecimalPointLimitExceeded,78 CollectionDecimalPointLimitExceeded,
76 /// Collection name can not be longer than 63 char.
77 CollectionNameLimitExceeded,
78 /// Collection description can not be longer than 255 char.
79 CollectionDescriptionLimitExceeded,
80 /// Token prefix can not be longer than 15 char.
81 CollectionTokenPrefixLimitExceeded,
82 /// This collection does not exist.
83 CollectionNotFound,
84 /// Item not exists.
85 TokenNotFound,
86 /// Admin not found
87 AdminNotFound,
88 /// Arithmetic calculation overflow.
89 NumOverflow,
90 /// Account already has admin role.
91 AlreadyAdmin,
92 /// You do not own this collection.
93 NoPermission,
94 /// This address is not set as sponsor, use setCollectionSponsor first.79 /// This address is not set as sponsor, use setCollectionSponsor first.
95 ConfirmUnsetSponsorFail,80 ConfirmUnsetSponsorFail,
96 /// Collection is not in mint mode.
97 PublicMintingNotAllowed,
98 /// Sender parameter and item owner must be equal.
99 MustBeTokenOwner,
100 /// Item balance not enough.
101 TokenValueTooLow,
102 /// Size of item is too large.
103 NftSizeLimitExceeded,
104 /// No approve found
105 ApproveNotFound,
106 /// Requested value more than approved.
107 TokenValueNotEnough,
108 /// Only approved addresses can call this method.
109 ApproveRequired,
110 /// Address is not in white list.
111 AddresNotInWhiteList,
112 /// Number of collection admins bound exceeded.
113 CollectionAdminsLimitExceeded,
114 /// Owned tokens by a single address bound exceeded.
115 AddressOwnershipLimitExceeded,
116 /// Length of items properties must be greater than 0.81 /// Length of items properties must be greater than 0.
117 EmptyArgument,82 EmptyArgument,
118 /// const_data exceeded data limit.
119 TokenConstDataLimitExceeded,
120 /// variable_data exceeded data limit.
121 TokenVariableDataLimitExceeded,
122 /// Not NFT item data used to mint in NFT collection.
123 NotNftDataUsedToMintNftCollectionToken,
124 /// Not Fungible item data used to mint in Fungible collection.
125 NotFungibleDataUsedToMintFungibleCollectionToken,
126 /// Not Re Fungible item data used to mint in Re Fungible collection.
127 NotReFungibleDataUsedToMintReFungibleCollectionToken,
128 /// Unexpected collection type.
129 UnexpectedCollectionType,
130 /// Can't store metadata in fungible tokens.
131 CantStoreMetadataInFungibleTokens,
132 /// Collection token limit exceeded
133 CollectionTokenLimitExceeded,
134 /// Account token limit exceeded per collection
135 AccountTokenLimitExceeded,
136 /// Collection limit bounds per collection exceeded83 /// Collection limit bounds per collection exceeded
137 CollectionLimitBoundsExceeded,84 CollectionLimitBoundsExceeded,
138 /// Tried to enable permissions which are only permitted to be disabled85 /// Tried to enable permissions which are only permitted to be disabled
139 OwnerPermissionsCantBeReverted,86 OwnerPermissionsCantBeReverted,
140 /// Schema data size limit bound exceeded
141 SchemaDataLimitExceeded,
142 /// Maximum refungibility exceeded
143 WrongRefungiblePieces,
144 /// createRefungible should be called with one owner
145 BadCreateRefungibleCall,
146 /// Gas limit exceeded
147 OutOfGas,
148 /// Metadata update denied by collection settings
149 MetadataUpdateDenied,
150 /// Metadata update flag become unmutable with None option
151 MetadataFlagFrozen,
152 /// Collection settings not allowing items transferring
153 TransferNotAllowed,
154 /// Can't transfer tokens to ethereum zero address
155 AddressIsZero,
156 }87 }
157}88}
158
159#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]
160pub struct CollectionHandle<T: Config> {89pub trait Config:
161 pub id: CollectionId,
162 collection: Collection<T>,90 system::Config
163 recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,
164}
165impl<T: Config> CollectionHandle<T> {
166 pub fn get_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {91 + pallet_evm_coder_substrate::Config
167 <CollectionById<T>>::get(id).map(|collection| Self {
168 id,
169 collection,
170 recorder: pallet_evm_coder_substrate::SubstrateRecorder::new(
171 eth::collection_id_to_address(id),92 + pallet_common::Config
172 gas_limit,
173 ),
174 })
175 }
176 pub fn get(id: CollectionId) -> Option<Self> {
177 Self::get_with_gas_limit(id, u64::MAX)
178 }93 + pallet_nonfungible::Config
179 pub fn log(&self, log: impl evm_coder::ToLog) -> DispatchResult {
180 self.recorder.log_sub(log)94 + pallet_refungible::Config
181 }
182 #[allow(dead_code)]
183 fn consume_gas(&self, gas: u64) -> DispatchResult {
184 self.recorder.consume_gas_sub(gas)
185 }
186 fn consume_sload(&self) -> DispatchResult {
187 self.recorder.consume_sload_sub()
188 }
189 fn consume_sstore(&self) -> DispatchResult {
190 self.recorder.consume_sstore_sub()
191 }
192 pub fn submit_logs(self) -> DispatchResult {
193 self.recorder.submit_logs()
194 }
195 pub fn save(self) -> DispatchResult {
196 self.recorder.submit_logs()?;
197 <CollectionById<T>>::insert(self.id, self.collection);
198 Ok(())
199 }
200}
201impl<T: Config> Deref for CollectionHandle<T> {
202 type Target = Collection<T>;95 + pallet_fungible::Config
203
204 fn deref(&self) -> &Self::Target {
205 &self.collection
206 }
207}
208
209impl<T: Config> DerefMut for CollectionHandle<T> {
210 fn deref_mut(&mut self) -> &mut Self::Target {96 + Sized
211 &mut self.collection
212 }
213}
214
215pub trait Config: system::Config + pallet_evm_coder_substrate::Config + Sized + TypeInfo {
216 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;97 + TypeInfo
21798{
218 /// Weight information for extrinsics in this pallet.99 /// Weight information for extrinsics in this pallet.
219 type WeightInfo: WeightInfo;100 type WeightInfo: WeightInfo;
220
221 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;
222 type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;
223
224 type CrossAccountId: CrossAccountId<Self::AccountId>;
225 type Currency: Currency<Self::AccountId>;
226 type CollectionCreationPrice: Get<
227 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,
228 >;
229 type TreasuryAccountId: Get<Self::AccountId>;
230}101}
231102
232type SelfWeightOf<T> = <T as Config>::WeightInfo;103type SelfWeightOf<T> = <T as Config>::WeightInfo;
233104
234trait WeightInfoHelpers: WeightInfo {
235 fn transfer() -> Weight {
236 Self::transfer_nft()
237 .max(Self::transfer_fungible())
238 .max(Self::transfer_refungible())
239 }
240 fn transfer_from() -> Weight {
241 Self::transfer_from_nft()
242 .max(Self::transfer_from_fungible())
243 .max(Self::transfer_from_refungible())
244 }
245 fn approve() -> Weight {
246 // TODO: refungible, fungible
247 Self::approve_nft()
248 }
249 fn set_variable_meta_data(data: u32) -> Weight {
250 // TODO: refungible
251 Self::set_variable_meta_data_nft(data)
252 }
253 fn create_item(data: u32) -> Weight {
254 Self::create_item_nft(data)
255 .max(Self::create_item_fungible())
256 .max(Self::create_item_refungible(data))
257 }
258 fn create_multiple_items(amount: u32) -> Weight {
259 Self::create_multiple_items_nft(amount)
260 .max(Self::create_multiple_items_fungible(amount))
261 .max(Self::create_multiple_items_refungible(amount))
262 }
263 fn burn_item() -> Weight {
264 // TODO: refungible, fungible
265 Self::burn_item_nft()
266 }
267}
268impl<T: WeightInfo> WeightInfoHelpers for T {}
269
270// # Used definitions105// # Used definitions
271//106//
272// ## User control levels107// ## User control levels
293 trait Store for Module<T: Config> as Nft {128 trait Store for Module<T: Config> as Nft {
294129
295 //#region Private members130 //#region Private members
296 /// Id of next collection
297 CreatedCollectionCount: u32;
298 /// Used for migrations131 /// Used for migrations
299 ChainVersion: u64;132 ChainVersion: u64;
300 /// Id of last collection token
301 /// Collection id (controlled?1)
302 ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;
303 //#endregion133 //#endregion
304134
305 //#region Bound counters
306 /// Amount of collections destroyed, used for total amount tracking with
307 /// CreatedCollectionCount
308 DestroyedCollectionCount: u32;
309 //#endregion
310
311 //#region Basic collections
312 /// Collection info
313 /// Collection id (controlled?1)
314 pub CollectionById get(fn collection_id) config(): map hasher(blake2_128_concat) CollectionId => Option<Collection<T>> = None;
315 /// List of collection admins
316 /// Collection id (controlled?2)
317 pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::CrossAccountId>;
318 /// Whitelisted collection users
319 /// Collection id (controlled?2), user id (controlled?3)
320 pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;
321 //#endregion
322
323 /// How many of collection items user have
324 /// Collection id (controlled?2), account id (real)
325 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;
326
327 /// Amount of items which spender can transfer out of owners account (via transferFrom)
328 /// Collection id (controlled?2), (token id (controlled ?2) + owner account id (real) + spender account id (controlled?3))
329 /// TODO: Off chain worker should remove from this map when token gets removed
330 pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;
331
332 //#region Item collections
333 /// Collection id (controlled?2), token id (controlled?1)
334 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<NftItemType<T::CrossAccountId>>;
335 /// Collection id (controlled?2), owner (controlled?2)
336 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;
337 /// Collection id (controlled?2), token id (controlled?1)
338 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<ReFungibleItemType<T::CrossAccountId>>;
339 //#endregion
340
341 //#region Index list
342 /// Collection id (controlled?2), tokens owner (controlled?2)
343 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;
344 //#endregion
345
346 //#region Tokens transfer rate limit baskets135 //#region Tokens transfer rate limit baskets
347 /// (Collection id (controlled?2), who created (real))136 /// (Collection id (controlled?2), who created (real))
348 /// TODO: Off chain worker should remove from this map when collection gets removed137 /// TODO: Off chain worker should remove from this map when collection gets removed
359 /// Collection id (controlled?2), token id (controlled?2)148 /// Collection id (controlled?2), token id (controlled?2)
360 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;149 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;
361 }150 }
362 add_extra_genesis {
363 build(|config: &GenesisConfig<T>| {
364 // Modification of storage
365 for (_num, _c) in &config.collection_id {
366 <Module<T>>::init_collection(_c);
367 }
368
369 for (_num, _c, _i) in &config.nft_item_id {
370 <Module<T>>::init_nft_token(*_c, _i);
371 }
372
373 for (collection_id, account_id, fungible_item) in &config.fungible_item_id {
374 <Module<T>>::init_fungible_token(*collection_id, &T::CrossAccountId::from_sub(account_id.clone()), fungible_item);
375 }
376
377 for (_num, _c, _i) in &config.refungible_item_id {
378 <Module<T>>::init_refungible_token(*_c, _i);
379 }
380 })
381 }
382}151}
383152
384decl_event!(
385 pub enum Event<T>
386 where
387 AccountId = <T as frame_system::Config>::AccountId,
388 CrossAccountId = <T as Config>::CrossAccountId,
389 {
390 /// New collection was created
391 ///
392 /// # Arguments
393 ///
394 /// * collection_id: Globally unique identifier of newly created collection.
395 ///
396 /// * mode: [CollectionMode] converted into u8.
397 ///
398 /// * account_id: Collection owner.
399 CollectionCreated(CollectionId, u8, AccountId),
400
401 /// New item was created.
402 ///
403 /// # Arguments
404 ///
405 /// * collection_id: Id of the collection where item was created.
406 ///
407 /// * item_id: Id of an item. Unique within the collection.
408 ///
409 /// * recipient: Owner of newly created item
410 ItemCreated(CollectionId, TokenId, CrossAccountId),
411
412 /// Collection item was burned.
413 ///
414 /// # Arguments
415 ///
416 /// collection_id.
417 ///
418 /// item_id: Identifier of burned NFT.
419 ItemDestroyed(CollectionId, TokenId),
420
421 /// Item was transferred
422 ///
423 /// * collection_id: Id of collection to which item is belong
424 ///
425 /// * item_id: Id of an item
426 ///
427 /// * sender: Original owner of item
428 ///
429 /// * recipient: New owner of item
430 ///
431 /// * amount: Always 1 for NFT
432 Transfer(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),
433
434 /// * collection_id
435 ///
436 /// * item_id
437 ///
438 /// * sender
439 ///
440 /// * spender
441 ///
442 /// * amount
443 Approved(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),
444 }
445);
446
447decl_module! {153decl_module! {
448 pub struct Module<T: Config> for enum Call154 pub struct Module<T: Config> for enum Call
449 where155 where
450 origin: T::Origin156 origin: T::Origin
451 {157 {
452 fn deposit_event() = default;
453 const CollectionAdminsLimit: u64 = COLLECTION_ADMINS_LIMIT;158 const CollectionAdminsLimit: u64 = COLLECTION_ADMINS_LIMIT;
454 type Error = Error<T>;159 type Error = Error<T>;
455160
484 // Anyone can create a collection189 // Anyone can create a collection
485 let who = ensure_signed(origin)?;190 let who = ensure_signed(origin)?;
486191
487 // Take a (non-refundable) deposit of collection creation192 let limits = CollectionLimits::<T::BlockNumber> {
488 let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();
489 imbalance.subsume(<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(
490 &T::TreasuryAccountId::get(),
491 T::CollectionCreationPrice::get(),
492 ));
493 <T as Config>::Currency::settle(
494 &who,
495 imbalance,
496 WithdrawReasons::TRANSFER,
497 ExistenceRequirement::KeepAlive,
498 ).map_err(|_| Error::<T>::NoPermission)?;
499
500 let decimal_points = match mode {
501 CollectionMode::Fungible(points) => points,
502 _ => 0
503 };
504
505 let created_count = CreatedCollectionCount::get();
506 let destroyed_count = DestroyedCollectionCount::get();
507
508 // bound Total number of collections
509 ensure!(created_count - destroyed_count < COLLECTION_NUMBER_LIMIT, Error::<T>::TotalCollectionsLimitExceeded);
510
511 // check params
512 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
513 ensure!(collection_name.len() <= MAX_COLLECTION_NAME_LENGTH, Error::<T>::CollectionNameLimitExceeded);
514 ensure!(collection_description.len() <= MAX_COLLECTION_DESCRIPTION_LENGTH, Error::<T>::CollectionDescriptionLimitExceeded);
515 ensure!(token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH, Error::<T>::CollectionTokenPrefixLimitExceeded);
516
517 // Generate next collection ID
518 let next_id = created_count
519 .checked_add(1)
520 .ok_or(Error::<T>::NumOverflow)?;
521
522 CreatedCollectionCount::put(next_id);
523
524 let limits = CollectionLimits {
525 sponsored_data_size: CUSTOM_DATA_LIMIT,193 sponsored_data_size: CUSTOM_DATA_LIMIT,
526 ..Default::default()194 ..Default::default()
527 };195 };
528196
529 // Create new collection197 // Create new collection
530 let new_collection = Collection {198 let new_collection = Collection::<T> {
531 owner: who.clone(),199 owner: who.clone(),
532 name: collection_name,200 name: collection_name,
533 mode: mode.clone(),201 mode: mode.clone(),
534 mint_mode: false,202 mint_mode: false,
535 access: AccessMode::Normal,203 access: AccessMode::Normal,
536 description: collection_description,204 description: collection_description,
537 decimal_points,
538 token_prefix,205 token_prefix,
539 offchain_schema: Vec::new(),206 offchain_schema: Vec::new(),
540 schema_version: SchemaVersion::ImageURL,207 schema_version: SchemaVersion::ImageURL,
541 sponsorship: SponsorshipState::Disabled,208 sponsorship: SponsorshipState::Disabled,
542 variable_on_chain_schema: Vec::new(),209 variable_on_chain_schema: Vec::new(),
543 const_on_chain_schema: Vec::new(),210 const_on_chain_schema: Vec::new(),
544 limits,211 limits,
545 meta_update_permission: MetaUpdatePermission::default(),
546 transfers_enabled: true,212 transfers_enabled: true,
213 meta_update_permission: Default::default(),
547 };214 };
548215
549 // Add new collection to map216 let _id = match mode {
550 <CollectionById<T>>::insert(next_id, new_collection);217 CollectionMode::NFT => {PalletNonfungible::init_collection(new_collection)?},
218 CollectionMode::Fungible(decimal_points) => {
219 // check params
220 ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
221 PalletFungible::init_collection(new_collection)?
222 }
223 CollectionMode::ReFungible => {
224 PalletRefungible::init_collection(new_collection)?
225 }
226 };
551227
552 // call event
553 Self::deposit_event(RawEvent::CollectionCreated(next_id, mode.id(), who));
554
555 Ok(())228 Ok(())
556 }229 }
557230
567 #[weight = <SelfWeightOf<T>>::destroy_collection()]240 #[weight = <SelfWeightOf<T>>::destroy_collection()]
568 #[transactional]241 #[transactional]
569 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {242 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {
243 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
570244
571 let sender = ensure_signed(origin)?;245 let collection = <CollectionHandle<T>>::try_get(collection_id)?;
572 let collection = Self::get_collection(collection_id)?;
573 Self::check_owner_permissions(&collection, &sender)?;246 collection.check_is_owner(&sender)?;
574 if !collection.limits.owner_can_destroy {
575 fail!(Error::<T>::NoPermission);
576 }
577247
578 <AddressTokens<T>>::remove_prefix(collection_id, None);248 // =========
579 <Allowances<T>>::remove_prefix(collection_id, None);
580 <Balance<T>>::remove_prefix(collection_id, None);
581 <ItemListIndex>::remove(collection_id);
582 <AdminList<T>>::remove(collection_id);
583 <CollectionById<T>>::remove(collection_id);
584 <WhiteList<T>>::remove_prefix(collection_id, None);
585249
586 <NftItemList<T>>::remove_prefix(collection_id, None);250 match collection.mode {
251 CollectionMode::ReFungible => PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?,
587 <FungibleItemList<T>>::remove_prefix(collection_id, None);252 CollectionMode::Fungible(_) => PalletFungible::destroy_collection(FungibleHandle::cast(collection), &sender)?,
588 <ReFungibleItemList<T>>::remove_prefix(collection_id, None);253 CollectionMode::NFT => PalletNonfungible::destroy_collection(NonfungibleHandle::cast(collection), &sender)?,
254 }
589255
590 <NftTransferBasket<T>>::remove_prefix(collection_id, None);256 <NftTransferBasket<T>>::remove_prefix(collection_id, None);
591 <FungibleTransferBasket<T>>::remove_prefix(collection_id, None);257 <FungibleTransferBasket<T>>::remove_prefix(collection_id, None);
592 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id, None);258 <ReFungibleTransferBasket<T>>::remove_prefix(collection_id, None);
593259
594 <VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);260 <VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);
595261
596 DestroyedCollectionCount::put(DestroyedCollectionCount::get()
597 .checked_add(1)
598 .ok_or(Error::<T>::NumOverflow)?);
599
600 Ok(())262 Ok(())
601 }263 }
602264
617 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{279 pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{
618280
619 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);281 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
620 let collection = Self::get_collection(collection_id)?;282 let collection = <CollectionHandle<T>>::try_get(collection_id)?;
621283
622 Self::toggle_white_list_internal(284 <PalletCommon<T>>::toggle_allowlist(
623 &sender,
624 &collection,285 &collection,
286 &sender,
625 &address,287 &address,
626 true,288 true,
627 )?;289 )?;
646 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{308 pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{
647309
648 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);310 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
649 let collection = Self::get_collection(collection_id)?;311 let collection = <CollectionHandle<T>>::try_get(collection_id)?;
650312
651 Self::toggle_white_list_internal(313 <PalletCommon<T>>::toggle_allowlist(
652 &sender,
653 &collection,314 &collection,
315 &sender,
654 &address,316 &address,
655 false,317 false,
656 )?;318 )?;
673 #[transactional]335 #[transactional]
674 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult336 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult
675 {337 {
676 let sender = ensure_signed(origin)?;338 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
677339
678 let mut target_collection = Self::get_collection(collection_id)?;340 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
679 Self::check_owner_permissions(&target_collection, &sender)?;341 target_collection.check_is_owner(&sender)?;
342
680 target_collection.access = mode;343 target_collection.access = mode;
681 target_collection.save()344 target_collection.save()
698 #[transactional]361 #[transactional]
699 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult362 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult
700 {363 {
701 let sender = ensure_signed(origin)?;364 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
702365
703 let mut target_collection = Self::get_collection(collection_id)?;366 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
704 Self::check_owner_permissions(&target_collection, &sender)?;367 target_collection.check_is_owner(&sender)?;
368
705 target_collection.mint_mode = mint_permission;369 target_collection.mint_mode = mint_permission;
706 target_collection.save()370 target_collection.save()
721 #[transactional]385 #[transactional]
722 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {386 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {
723387
724 let sender = ensure_signed(origin)?;388 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
389
725 let mut target_collection = Self::get_collection(collection_id)?;390 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
726 Self::check_owner_permissions(&target_collection, &sender)?;391 target_collection.check_is_owner(&sender)?;
392
727 target_collection.owner = new_owner;393 target_collection.owner = new_owner;
728 target_collection.save()394 target_collection.save()
745 #[transactional]411 #[transactional]
746 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {412 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {
747 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);413 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
748 let collection = Self::get_collection(collection_id)?;
749 Self::check_owner_or_admin_permissions(&collection, &sender)?;
750 let mut admin_arr = <AdminList<T>>::get(collection_id);
751414
752 match admin_arr.binary_search(&new_admin_id) {415 let collection = <CollectionHandle<T>>::try_get(collection_id)?;
753 Ok(_) => {},
754 Err(idx) => {
755 ensure!(admin_arr.len() < COLLECTION_ADMINS_LIMIT as usize, Error::<T>::CollectionAdminsLimitExceeded);
756 admin_arr.insert(idx, new_admin_id);416 collection.check_is_owner_or_admin(&sender)?;
417
757 <AdminList<T>>::insert(collection_id, admin_arr);418 <IsAdmin<T>>::insert((collection_id, new_admin_id.as_sub()), true);
758 }
759 }
760 Ok(())419 Ok(())
761 }420 }
762421
776 #[transactional]435 #[transactional]
777 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {436 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {
778 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);437 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
779 let collection = Self::get_collection(collection_id)?;
780 Self::check_owner_or_admin_permissions(&collection, &sender)?;
781 let mut admin_arr = <AdminList<T>>::get(collection_id);
782438
783 if let Ok(idx) = admin_arr.binary_search(&account_id) {439 let collection = <CollectionHandle<T>>::try_get(collection_id)?;
784 admin_arr.remove(idx);440 collection.check_is_owner_or_admin(&sender)?;
441
785 <AdminList<T>>::insert(collection_id, admin_arr);442 <IsAdmin<T>>::remove((collection_id, account_id.as_sub()));
786 }
787 Ok(())443 Ok(())
788 }444 }
789445
799 #[weight = <SelfWeightOf<T>>::set_collection_sponsor()]455 #[weight = <SelfWeightOf<T>>::set_collection_sponsor()]
800 #[transactional]456 #[transactional]
801 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {457 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {
802 let sender = ensure_signed(origin)?;458 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
803 let mut target_collection = Self::get_collection(collection_id)?;
804 Self::check_owner_permissions(&target_collection, &sender)?;
805459
460 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
461 target_collection.check_is_owner_or_admin(&sender)?;
462
806 target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);463 target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);
807 target_collection.save()464 target_collection.save()
808 }465 }
819 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {476 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {
820 let sender = ensure_signed(origin)?;477 let sender = ensure_signed(origin)?;
821478
822 let mut target_collection = Self::get_collection(collection_id)?;479 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
823 ensure!(480 ensure!(
824 target_collection.sponsorship.pending_sponsor() == Some(&sender),481 target_collection.sponsorship.pending_sponsor() == Some(&sender),
825 Error::<T>::ConfirmUnsetSponsorFail482 Error::<T>::ConfirmUnsetSponsorFail
841 #[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]498 #[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]
842 #[transactional]499 #[transactional]
843 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {500 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {
844 let sender = ensure_signed(origin)?;501 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
845502
846 let mut target_collection = Self::get_collection(collection_id)?;503 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
847 Self::check_owner_permissions(&target_collection, &sender)?;504 target_collection.check_is_owner(&sender)?;
848505
849 target_collection.sponsorship = SponsorshipState::Disabled;506 target_collection.sponsorship = SponsorshipState::Disabled;
850 target_collection.save()507 target_collection.save()
868 /// * owner: Address, initial owner of the NFT.525 /// * owner: Address, initial owner of the NFT.
869 ///526 ///
870 /// * data: Token data to store on chain.527 /// * data: Token data to store on chain.
871 // #[weight =528 #[weight = <CommonWeights<T>>::create_item()]
872 // (130_000_000 as Weight)
873 // .saturating_add((2135 as Weight).saturating_mul((properties.len() as u64) as Weight))
874 // .saturating_add(RocksDbWeight::get().reads(10 as Weight))
875 // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]
876
877 #[weight = <SelfWeightOf<T>>::create_item(data.data_size() as u32)]
878 #[transactional]529 #[transactional]
879 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResult {530 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {
880 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);531 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
881 let collection = Self::get_collection(collection_id)?;
882532
883 Self::create_item_internal(&sender, &collection, &owner, data)?;533 dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data))
884
885 collection.submit_logs()
886 }534 }
887535
888 /// This method creates multiple items in a collection created with CreateCollection method.536 /// This method creates multiple items in a collection created with CreateCollection method.
903 /// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].551 /// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].
904 ///552 ///
905 /// * owner: Address, initial owner of the NFT.553 /// * owner: Address, initial owner of the NFT.
906 #[weight = <SelfWeightOf<T>>::create_multiple_items(items_data.len() as u32)]554 #[weight = <CommonWeights<T>>::create_multiple_items(items_data.len() as u32)]
907 #[transactional]555 #[transactional]
908 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResult {556 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {
909
910 ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);557 ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);
911 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);558 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
912 let collection = Self::get_collection(collection_id)?;
913559
914 Self::create_multiple_items_internal(&sender, &collection, &owner, items_data)?;560 dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data))
915
916 collection.submit_logs()
917 }561 }
918562
919 // TODO! transaction weight563 // TODO! transaction weight
932 #[weight = <SelfWeightOf<T>>::set_transfers_enabled_flag()]576 #[weight = <SelfWeightOf<T>>::set_transfers_enabled_flag()]
933 #[transactional]577 #[transactional]
934 pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {578 pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {
579 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
580 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
581 target_collection.check_is_owner(&sender)?;
935582
936 let sender = ensure_signed(origin)?;583 // =========
937 let mut target_collection = Self::get_collection(collection_id)?;
938584
939 Self::check_owner_permissions(&target_collection, &sender)?;
940
941 target_collection.transfers_enabled = value;585 target_collection.transfers_enabled = value;
942 target_collection.save()586 target_collection.save()
943 }587 }
944588
945 // TODO! transaction weight
946 /// Set meta_update_permission value for particular collection
947 ///
948 /// # Permissions
949 ///
950 /// * Collection Owner.
951 ///
952 /// # Arguments
953 ///
954 /// * collection_id: ID of the collection.
955 ///
956 /// * value: New flag value.
957 #[weight = <T as Config>::WeightInfo::burn_item()]
958 #[transactional]
959 pub fn set_meta_update_permission_flag(origin, collection_id: CollectionId, value: MetaUpdatePermission) -> DispatchResult {
960
961 let sender = ensure_signed(origin)?;
962 let mut target_collection = Self::get_collection(collection_id)?;
963
964 ensure!(
965 target_collection.meta_update_permission != MetaUpdatePermission::None,
966 Error::<T>::MetadataFlagFrozen
967 );
968 Self::check_owner_permissions(&target_collection, &sender)?;
969
970 target_collection.meta_update_permission = value;
971
972 target_collection.save()
973 }
974
975 /// Destroys a concrete instance of NFT.589 /// Destroys a concrete instance of NFT.
976 ///590 ///
977 /// # Permissions591 /// # Permissions
985 /// * collection_id: ID of the collection.599 /// * collection_id: ID of the collection.
986 ///600 ///
987 /// * item_id: ID of NFT to burn.601 /// * item_id: ID of NFT to burn.
988 #[weight = <SelfWeightOf<T>>::burn_item()]602 #[weight = <CommonWeights<T>>::burn_item()]
989 #[transactional]603 #[transactional]
990 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {604 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
991
992 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);605 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
993 let target_collection = Self::get_collection(collection_id)?;
994606
995 Self::burn_item_internal(&sender, &target_collection, item_id, value, true)?;607 dispatch_call::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))
996
997 target_collection.submit_logs()
998 }608 }
999609
1000 /// Destroys a concrete instance of NFT on behalf of the owner610 /// Destroys a concrete instance of NFT on behalf of the owner
1013 /// * item_id: ID of NFT to burn.623 /// * item_id: ID of NFT to burn.
1014 ///624 ///
1015 /// * from: owner of item625 /// * from: owner of item
1016 #[weight = <SelfWeightOf<T>>::burn_item()]626 #[weight = <CommonWeights<T>>::burn_from()]
1017 #[transactional]627 #[transactional]
1018 pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResult {628 pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
1019
1020 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);629 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1021 let target_collection = Self::get_collection(collection_id)?;
1022630
1023 Self::burn_from_internal(&sender, &target_collection, &from, item_id, value)?;631 dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value))
1024
1025 target_collection.submit_logs()
1026 }632 }
1027633
1028 /// Change ownership of the token.634 /// Change ownership of the token.
1048 /// * Non-Fungible Mode: Ignored654 /// * Non-Fungible Mode: Ignored
1049 /// * Fungible Mode: Must specify transferred amount655 /// * Fungible Mode: Must specify transferred amount
1050 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)656 /// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)
1051 #[weight = <SelfWeightOf<T>>::transfer()]657 #[weight = <CommonWeights<T>>::transfer()]
1052 #[transactional]658 #[transactional]
1053 pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {659 pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
1054 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);660 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1055 let collection = Self::get_collection(collection_id)?;
1056661
1057 Self::transfer_internal(&sender, &recipient, &collection, item_id, value)?;662 dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value))
1058
1059 collection.submit_logs()
1060 }663 }
1061664
1062 /// Set, change, or remove approved address to transfer the ownership of the NFT.665 /// Set, change, or remove approved address to transfer the ownership of the NFT.
1074 /// * collection_id.677 /// * collection_id.
1075 ///678 ///
1076 /// * item_id: ID of the item.679 /// * item_id: ID of the item.
1077 #[weight = <SelfWeightOf<T>>::approve()]680 #[weight = <CommonWeights<T>>::approve()]
1078 #[transactional]681 #[transactional]
1079 pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {682 pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {
1080 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);683 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1081 let collection = Self::get_collection(collection_id)?;
1082684
1083 Self::approve_internal(&sender, &spender, &collection, item_id, amount)?;685 dispatch_call::<T, _>(collection_id, |d| d.approve(sender, spender, item_id, amount))
1084
1085 collection.submit_logs()
1086 }686 }
1087687
1088 /// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.688 /// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.
1104 /// * item_id: ID of the item.704 /// * item_id: ID of the item.
1105 ///705 ///
1106 /// * value: Amount to transfer.706 /// * value: Amount to transfer.
1107 #[weight = <SelfWeightOf<T>>::transfer_from()]707 #[weight = <CommonWeights<T>>::transfer_from()]
1108 #[transactional]708 #[transactional]
1109 pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {709 pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {
1110 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);710 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1111 let collection = Self::get_collection(collection_id)?;
1112711
1113 Self::transfer_from_internal(&sender, &from, &recipient, &collection, item_id, value)?;712 dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value))
1114
1115 collection.submit_logs()
1116 }713 }
1117 // #[weight = 0]
1118 // // let no_perm_mes = "You do not have permissions to modify this collection";
1119 // // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);
1120 // // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));
1121 // // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);
1122714
1123 // // // on_nft_received call
1124
1125 // // Self::transfer(origin, collection_id, item_id, new_owner)?;
1126
1127 // Ok(())
1128 // }
1129
1130 /// Set off-chain data schema.715 /// Set off-chain data schema.
1131 ///716 ///
1132 /// # Permissions717 /// # Permissions
1139 /// * collection_id.724 /// * collection_id.
1140 ///725 ///
1141 /// * schema: String representing the offchain data schema.726 /// * schema: String representing the offchain data schema.
1142 #[weight = <SelfWeightOf<T>>::set_variable_meta_data(data.len() as u32)]727 #[weight = <CommonWeights<T>>::set_variable_metadata(data.len() as u32)]
1143 #[transactional]728 #[transactional]
1144 pub fn set_variable_meta_data (729 pub fn set_variable_meta_data (
1145 origin,730 origin,
1146 collection_id: CollectionId,731 collection_id: CollectionId,
1147 item_id: TokenId,732 item_id: TokenId,
1148 data: Vec<u8>733 data: Vec<u8>
1149 ) -> DispatchResult {734 ) -> DispatchResultWithPostInfo {
1150 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);735 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1151736
1152 let collection = Self::get_collection(collection_id)?;737 dispatch_call::<T, _>(collection_id, |d| d.set_variable_metadata(sender, item_id, data))
1153 Self::meta_update_check(&sender, &collection, item_id)?;738 }
1154739
1155 Self::set_variable_meta_data_internal(&sender, &collection, item_id, data)?;740 /// Set meta_update_permission value for particular collection
741 ///
742 /// # Permissions
743 ///
744 /// * Collection Owner.
745 ///
746 /// # Arguments
747 ///
748 /// * collection_id: ID of the collection.
749 ///
750 /// * value: New flag value.
751 #[weight = <SelfWeightOf<T>>::set_meta_update_permission_flag()]
752 #[transactional]
753 pub fn set_meta_update_permission_flag(origin, collection_id: CollectionId, value: MetaUpdatePermission) -> DispatchResult {
754 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
755 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
1156756
1157 Ok(())757 ensure!(
758 target_collection.meta_update_permission != MetaUpdatePermission::None,
759 <CommonError<T>>::MetadataFlagFrozen,
760 );
761 target_collection.check_is_owner(&sender)?;
762
763 target_collection.meta_update_permission = value;
764
765 target_collection.save()
1158 }766 }
1159767
1160 /// Set schema standard768 /// Set schema standard
1179 version: SchemaVersion787 version: SchemaVersion
1180 ) -> DispatchResult {788 ) -> DispatchResult {
1181 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);789 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1182 let mut target_collection = Self::get_collection(collection_id)?;790 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
1183 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;791 target_collection.check_is_owner_or_admin(&sender)?;
1184 target_collection.schema_version = version;792 target_collection.schema_version = version;
1185 target_collection.save()793 target_collection.save()
1186 }794 }
1205 schema: Vec<u8>813 schema: Vec<u8>
1206 ) -> DispatchResult {814 ) -> DispatchResult {
1207 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);815 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1208 let mut target_collection = Self::get_collection(collection_id)?;816 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
1209 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;817 target_collection.check_is_owner_or_admin(&sender)?;
1210818
1211 // check schema limit819 // check schema limit
1212 ensure!(schema.len() as u32 <= OFFCHAIN_SCHEMA_LIMIT, "");820 ensure!(schema.len() as u32 <= OFFCHAIN_SCHEMA_LIMIT, "");
1235 schema: Vec<u8>843 schema: Vec<u8>
1236 ) -> DispatchResult {844 ) -> DispatchResult {
1237 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);845 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1238 let mut target_collection = Self::get_collection(collection_id)?;846 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
1239 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;847 target_collection.check_is_owner_or_admin(&sender)?;
1240848
1241 // check schema limit849 // check schema limit
1242 ensure!(schema.len() as u32 <= CONST_ON_CHAIN_SCHEMA_LIMIT, "");850 ensure!(schema.len() as u32 <= CONST_ON_CHAIN_SCHEMA_LIMIT, "");
1265 schema: Vec<u8>873 schema: Vec<u8>
1266 ) -> DispatchResult {874 ) -> DispatchResult {
1267 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);875 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1268 let mut target_collection = Self::get_collection(collection_id)?;876 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
1269 Self::check_owner_or_admin_permissions(&target_collection, &sender)?;877 target_collection.check_is_owner_or_admin(&sender)?;
1270878
1271 // check schema limit879 // check schema limit
1272 ensure!(schema.len() as u32 <= VARIABLE_ON_CHAIN_SCHEMA_LIMIT, "");880 ensure!(schema.len() as u32 <= VARIABLE_ON_CHAIN_SCHEMA_LIMIT, "");
1279 #[transactional]887 #[transactional]
1280 pub fn set_collection_limits(888 pub fn set_collection_limits(
1281 origin,889 origin,
1282 collection_id: u32,890 collection_id: CollectionId,
1283 new_limits: CollectionLimits<T::BlockNumber>,891 new_limits: CollectionLimits<T::BlockNumber>,
1284 ) -> DispatchResult {892 ) -> DispatchResult {
1285 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);893 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1286 let mut target_collection = Self::get_collection(collection_id)?;894 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
1287 Self::check_owner_permissions(&target_collection, sender.as_sub())?;895 target_collection.check_is_owner(&sender)?;
1288 let old_limits = &target_collection.limits;896 let old_limits = &target_collection.limits;
1289897
1290 // collection bounds898 // collection bounds
1291 ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&899 ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&
1292 new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP &&900 new_limits.account_token_ownership_limit.unwrap_or(0) <= MAX_TOKEN_OWNERSHIP &&
1293 new_limits.sponsored_data_size <= CUSTOM_DATA_LIMIT,901 new_limits.sponsored_data_size <= CUSTOM_DATA_LIMIT,
1294 Error::<T>::CollectionLimitBoundsExceeded);902 Error::<T>::CollectionLimitBoundsExceeded);
1295903
1296 // token_limit check prev904 // token_limit check prev
1297 ensure!(old_limits.token_limit >= new_limits.token_limit, Error::<T>::CollectionTokenLimitExceeded);905 ensure!(old_limits.token_limit >= new_limits.token_limit, <CommonError<T>>::CollectionTokenLimitExceeded);
1298 ensure!(new_limits.token_limit > 0, Error::<T>::CollectionTokenLimitExceeded);906 ensure!(new_limits.token_limit > 0, <CommonError<T>>::CollectionTokenLimitExceeded);
1299907
1300 ensure!(908 ensure!(
1301 (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&909 (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&
1310 }918 }
1311}919}
1312920
921// TODO: limit returned entries?
1313impl<T: Config> Module<T> {922impl<T: Config> Pallet<T> {
1314 pub fn create_item_internal(923 pub fn adminlist(collection: CollectionId) -> Vec<T::AccountId> {
1315 sender: &T::CrossAccountId,
1316 collection: &CollectionHandle<T>,
1317 owner: &T::CrossAccountId,
1318 data: CreateItemData,
1319 ) -> DispatchResult {
1320 ensure!(
1321 owner != &T::CrossAccountId::from_eth(H160([0; 20])),
1322 Error::<T>::AddressIsZero924 <IsAdmin<T>>::iter_prefix((collection,))
1323 );
1324
1325 Self::can_create_items_in_collection(collection, sender, owner, 1)?;
1326 Self::validate_create_item_args(collection, &data)?;925 .map(|(a, _)| a)
1327 Self::create_item_no_validation(collection, owner, data)?;
1328
1329 Ok(())926 .collect()
1330 }927 }
1331928 pub fn allowlist(collection: CollectionId) -> Vec<T::AccountId> {
1332 pub fn transfer_internal(929 <Allowlist<T>>::iter_prefix((collection,))
1333 sender: &T::CrossAccountId,930 .map(|(a, _)| a)
1334 recipient: &T::CrossAccountId,931 .collect()
1335 target_collection: &CollectionHandle<T>,
1336 item_id: TokenId,
1337 value: u128,
1338 ) -> DispatchResult {
1339 ensure!(
1340 recipient != &T::CrossAccountId::from_eth(H160([0; 20])),
1341 Error::<T>::AddressIsZero
1342 );
1343
1344 // Limits check
1345 Self::is_correct_transfer(target_collection, recipient)?;
1346
1347 // Transfer permissions check
1348 ensure!(
1349 Self::is_item_owner(sender, target_collection, item_id)?
1350 || Self::is_owner_or_admin_permissions(target_collection, sender)?,
1351 Error::<T>::NoPermission
1352 );
1353
1354 if target_collection.access == AccessMode::WhiteList {
1355 Self::check_white_list(target_collection, sender)?;
1356 Self::check_white_list(target_collection, recipient)?;
1357 }
1358
1359 match target_collection.mode {
1360 CollectionMode::NFT => Self::transfer_nft(
1361 target_collection,
1362 item_id,
1363 sender.clone(),
1364 recipient.clone(),
1365 )?,
1366 CollectionMode::Fungible(_) => {
1367 Self::transfer_fungible(target_collection, value, sender, recipient)?
1368 }
1369 CollectionMode::ReFungible => Self::transfer_refungible(
1370 target_collection,
1371 item_id,
1372 value,
1373 sender.clone(),
1374 recipient.clone(),
1375 )?,
1376 };
1377
1378 Self::deposit_event(RawEvent::Transfer(
1379 target_collection.id,
1380 item_id,
1381 sender.clone(),
1382 recipient.clone(),
1383 value,
1384 ));
1385
1386 Ok(())
1387 }
1388
1389 pub fn approve_internal(
1390 sender: &T::CrossAccountId,
1391 spender: &T::CrossAccountId,
1392 collection: &CollectionHandle<T>,
1393 item_id: TokenId,
1394 amount: u128,
1395 ) -> DispatchResult {
1396 Self::token_exists(collection, item_id)?;
1397
1398 // Transfer permissions check
1399 let bypasses_limits = collection.limits.owner_can_transfer
1400 && Self::is_owner_or_admin_permissions(collection, sender)?;
1401
1402 let allowance_limit = if bypasses_limits {
1403 None
1404 } else if let Some(amount) = Self::owned_amount(sender, collection, item_id)? {
1405 Some(amount)
1406 } else {
1407 fail!(Error::<T>::NoPermission);
1408 };
1409
1410 if collection.access == AccessMode::WhiteList {
1411 Self::check_white_list(collection, sender)?;
1412 Self::check_white_list(collection, spender)?;
1413 }
1414
1415 collection.consume_sload()?;
1416 let allowance: u128 = amount
1417 .checked_add(<Allowances<T>>::get(
1418 collection.id,
1419 (item_id, sender.as_sub(), spender.as_sub()),
1420 ))
1421 .ok_or(Error::<T>::NumOverflow)?;
1422 if let Some(limit) = allowance_limit {
1423 ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);
1424 }
1425 collection.consume_sstore()?;
1426 <Allowances<T>>::insert(
1427 collection.id,
1428 (item_id, sender.as_sub(), spender.as_sub()),
1429 allowance,
1430 );
1431
1432 if matches!(collection.mode, CollectionMode::NFT) {
1433 // TODO: NFT: only one owner may exist for token in ERC721
1434 collection.log(ERC721Events::Approval {
1435 owner: *sender.as_eth(),
1436 approved: *spender.as_eth(),
1437 token_id: item_id.into(),
1438 })?;
1439 }
1440
1441 if matches!(collection.mode, CollectionMode::Fungible(_)) {
1442 // TODO: NFT: only one owner may exist for token in ERC20
1443 collection.log(ERC20Events::Approval {
1444 owner: *sender.as_eth(),
1445 spender: *spender.as_eth(),
1446 value: allowance.into(),
1447 })?;
1448 }
1449
1450 Self::deposit_event(RawEvent::Approved(
1451 collection.id,
1452 item_id,
1453 sender.clone(),
1454 spender.clone(),
1455 allowance,
1456 ));
1457 Ok(())
1458 }
1459
1460 pub fn transfer_from_internal(
1461 sender: &T::CrossAccountId,
1462 from: &T::CrossAccountId,
1463 recipient: &T::CrossAccountId,
1464 collection: &CollectionHandle<T>,
1465 item_id: TokenId,
1466 amount: u128,
1467 ) -> DispatchResult {
1468 if sender == from {
1469 // Transfer by `from`, because it is either equal to sender, or derived from him
1470 return Self::transfer_internal(from, recipient, collection, item_id, amount);
1471 }
1472
1473 // Check approval
1474 collection.consume_sload()?;
1475 let approval: u128 =
1476 <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));
1477
1478 // Limits check
1479 Self::is_correct_transfer(collection, recipient)?;
1480
1481 // Transfer permissions check
1482 ensure!(
1483 approval >= amount
1484 || (collection.limits.owner_can_transfer
1485 && Self::is_owner_or_admin_permissions(collection, sender)?),
1486 Error::<T>::NoPermission
1487 );
1488
1489 if collection.access == AccessMode::WhiteList {
1490 Self::check_white_list(collection, sender)?;
1491 Self::check_white_list(collection, recipient)?;
1492 }
1493
1494 // Reduce approval by transferred amount or remove if remaining approval drops to 0
1495 let allowance = approval.saturating_sub(amount);
1496 collection.consume_sstore()?;
1497 if allowance > 0 {
1498 <Allowances<T>>::insert(
1499 collection.id,
1500 (item_id, from.as_sub(), sender.as_sub()),
1501 allowance,
1502 );
1503 } else {
1504 <Allowances<T>>::remove(collection.id, (item_id, from.as_sub(), sender.as_sub()));
1505 }
1506
1507 match collection.mode {
1508 CollectionMode::NFT => {
1509 Self::transfer_nft(collection, item_id, from.clone(), recipient.clone())?
1510 }
1511 CollectionMode::Fungible(_) => {
1512 Self::transfer_fungible(collection, amount, from, recipient)?
1513 }
1514 CollectionMode::ReFungible => Self::transfer_refungible(
1515 collection,
1516 item_id,
1517 amount,
1518 from.clone(),
1519 recipient.clone(),
1520 )?,
1521 };
1522
1523 if matches!(collection.mode, CollectionMode::Fungible(_)) {
1524 collection.log(ERC20Events::Approval {
1525 owner: *from.as_eth(),
1526 spender: *sender.as_eth(),
1527 value: allowance.into(),
1528 })?;
1529 }
1530
1531 Ok(())
1532 }
1533
1534 pub fn set_variable_meta_data_internal(
1535 sender: &T::CrossAccountId,
1536 collection: &CollectionHandle<T>,
1537 item_id: TokenId,
1538 data: Vec<u8>,
1539 ) -> DispatchResult {
1540 Self::token_exists(collection, item_id)?;
1541
1542 ensure!(
1543 CUSTOM_DATA_LIMIT >= data.len() as u32,
1544 Error::<T>::TokenVariableDataLimitExceeded
1545 );
1546
1547 ensure!(
1548 (Self::is_item_owner(sender, collection, item_id)?
1549 && collection.meta_update_permission == MetaUpdatePermission::ItemOwner)
1550 || (Self::is_owner_or_admin_permissions(collection, sender)?
1551 && collection.meta_update_permission == MetaUpdatePermission::Admin),
1552 Error::<T>::NoPermission
1553 );
1554
1555 match collection.mode {
1556 CollectionMode::NFT => Self::set_nft_variable_data(collection, item_id, data)?,
1557 CollectionMode::ReFungible => {
1558 Self::set_re_fungible_variable_data(collection, item_id, data)?
1559 }
1560 CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),
1561 };
1562
1563 Ok(())
1564 }
1565
1566 pub fn meta_update_check(
1567 sender: &T::CrossAccountId,
1568 collection: &CollectionHandle<T>,
1569 item_id: TokenId,
1570 ) -> DispatchResult {
1571 match collection.meta_update_permission {
1572 MetaUpdatePermission::ItemOwner => ensure!(
1573 Self::is_item_owner(sender, collection, item_id)?,
1574 Error::<T>::NoPermission
1575 ),
1576 MetaUpdatePermission::Admin => ensure!(
1577 Self::is_owner_or_admin_permissions(collection, sender)?,
1578 Error::<T>::NoPermission
1579 ),
1580 MetaUpdatePermission::None => fail!(Error::<T>::MetadataUpdateDenied),
1581 }
1582
1583 Ok(())
1584 }
1585
1586 pub fn get_variable_metadata(
1587 collection: &CollectionHandle<T>,
1588 item_id: TokenId,
1589 ) -> Result<Vec<u8>, DispatchError> {
1590 Ok(match collection.mode {
1591 CollectionMode::NFT => {
1592 <NftItemList<T>>::get(collection.id, item_id)
1593 .ok_or(Error::<T>::TokenNotFound)?
1594 .variable_data
1595 }
1596 CollectionMode::ReFungible => {
1597 <ReFungibleItemList<T>>::get(collection.id, item_id)
1598 .ok_or(Error::<T>::TokenNotFound)?
1599 .variable_data
1600 }
1601 _ => fail!(Error::<T>::UnexpectedCollectionType),
1602 })
1603 }
1604
1605 pub fn create_multiple_items_internal(
1606 sender: &T::CrossAccountId,
1607 collection: &CollectionHandle<T>,
1608 owner: &T::CrossAccountId,
1609 items_data: Vec<CreateItemData>,
1610 ) -> DispatchResult {
1611 Self::can_create_items_in_collection(collection, sender, owner, items_data.len() as u32)?;
1612
1613 for data in &items_data {
1614 Self::validate_create_item_args(collection, data)?;
1615 }
1616 for data in &items_data {
1617 Self::create_item_no_validation(collection, owner, data.clone())?;
1618 }
1619
1620 Ok(())
1621 }
1622
1623 pub fn burn_item_internal(
1624 owner: &T::CrossAccountId,
1625 collection: &CollectionHandle<T>,
1626 item_id: TokenId,
1627 value: u128,
1628 allow_escalation: bool,
1629 ) -> DispatchResult {
1630 ensure!(
1631 Self::is_item_owner(owner, collection, item_id)?
1632 || (allow_escalation
1633 && collection.limits.owner_can_transfer
1634 && Self::is_owner_or_admin_permissions(collection, owner)?),
1635 Error::<T>::NoPermission
1636 );
1637
1638 if collection.access == AccessMode::WhiteList {
1639 Self::check_white_list(collection, owner)?;
1640 }
1641
1642 match collection.mode {
1643 CollectionMode::NFT => match value {
1644 1 => Self::burn_nft_item(collection, item_id)?,
1645 0 => (),
1646 _ => fail!(<Error<T>>::TokenValueTooLow),
1647 },
1648 CollectionMode::Fungible(_) => Self::burn_fungible_item(collection, owner, value)?,
1649 CollectionMode::ReFungible => {
1650 Self::burn_refungible_item(collection, item_id, owner, value)?
1651 }
1652 _ => (),
1653 };
1654
1655 Ok(())
1656 }
1657
1658 pub fn burn_from_internal(
1659 sender: &T::CrossAccountId,
1660 collection: &CollectionHandle<T>,
1661 from: &T::CrossAccountId,
1662 item_id: TokenId,
1663 amount: u128,
1664 ) -> DispatchResult {
1665 if sender == from {
1666 // Transfer by `from`, because it is either equal to sender, or derived from him
1667 return Self::burn_item_internal(from, collection, item_id, amount, true);
1668 }
1669
1670 // Check approval
1671 collection.consume_sload()?;
1672 let approval: u128 =
1673 <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));
1674
1675 // Transfer permissions check
1676 ensure!(
1677 approval >= amount
1678 || (collection.limits.owner_can_transfer
1679 && Self::is_owner_or_admin_permissions(collection, sender)?),
1680 Error::<T>::NoPermission
1681 );
1682
1683 if collection.access == AccessMode::WhiteList {
1684 Self::check_white_list(collection, sender)?;
1685 }
1686
1687 // Reduce approval by transferred amount or remove if remaining approval drops to 0
1688 let allowance = approval.saturating_sub(amount);
1689 collection.consume_sstore()?;
1690 if allowance > 0 {
1691 <Allowances<T>>::insert(
1692 collection.id,
1693 (item_id, from.as_sub(), sender.as_sub()),
1694 allowance,
1695 );
1696 } else {
1697 <Allowances<T>>::remove(collection.id, (item_id, from.as_sub(), sender.as_sub()));
1698 }
1699
1700 // Escalation is disallowed here, because we need to be sure that passed owner is real
1701 Self::burn_item_internal(from, collection, item_id, amount, false)?;
1702
1703 if matches!(collection.mode, CollectionMode::Fungible(_)) {
1704 collection.log(ERC20Events::Approval {
1705 owner: *from.as_eth(),
1706 spender: *sender.as_eth(),
1707 value: allowance.into(),
1708 })?;
1709 }
1710
1711 Ok(())
1712 }
1713
1714 pub fn toggle_white_list_internal(
1715 sender: &T::CrossAccountId,
1716 collection: &CollectionHandle<T>,
1717 address: &T::CrossAccountId,
1718 whitelisted: bool,
1719 ) -> DispatchResult {
1720 Self::check_owner_or_admin_permissions(collection, sender)?;
1721
1722 if whitelisted {
1723 <WhiteList<T>>::insert(collection.id, address.as_sub(), true);
1724 } else {
1725 <WhiteList<T>>::remove(collection.id, address.as_sub());
1726 }
1727
1728 Ok(())
1729 }
1730
1731 fn is_correct_transfer(
1732 collection: &CollectionHandle<T>,
1733 recipient: &T::CrossAccountId,
1734 ) -> DispatchResult {
1735 let collection_id = collection.id;
1736
1737 // check token limit and account token limit
1738 collection.consume_sload()?;
1739 let account_items: u32 =
1740 <AddressTokens<T>>::get(collection_id, recipient.as_sub()).len() as u32;
1741
1742 // zero limit means collection limit is disabled
1743 // otherwise get lower value
1744 let limit = if collection.limits.account_token_ownership_limit == 0
1745 || collection.limits.account_token_ownership_limit > ACCOUNT_TOKEN_OWNERSHIP_LIMIT
1746 {
1747 ACCOUNT_TOKEN_OWNERSHIP_LIMIT
1748 } else {
1749 collection.limits.account_token_ownership_limit
1750 };
1751
1752 ensure!(limit > account_items, Error::<T>::AccountTokenLimitExceeded);
1753
1754 // preliminary transfer check
1755 ensure!(collection.transfers_enabled, Error::<T>::TransferNotAllowed);
1756
1757 Ok(())
1758 }
1759
1760 fn can_create_items_in_collection(
1761 collection: &CollectionHandle<T>,
1762 sender: &T::CrossAccountId,
1763 owner: &T::CrossAccountId,
1764 amount: u32,
1765 ) -> DispatchResult {
1766 let collection_id = collection.id;
1767
1768 // check token limit and account token limit
1769 let total_items: u32 = ItemListIndex::get(collection_id)
1770 .checked_add(amount)
1771 .ok_or(Error::<T>::CollectionTokenLimitExceeded)?;
1772 let account_items: u32 = (<AddressTokens<T>>::get(collection_id, owner.as_sub()).len()
1773 as u32)
1774 .checked_add(amount)
1775 .ok_or(Error::<T>::AccountTokenLimitExceeded)?;
1776
1777 // zero limit means collection limit is disabled
1778 // otherwise get lower value
1779 let account_token_limit = if collection.limits.account_token_ownership_limit == 0
1780 || collection.limits.account_token_ownership_limit > ACCOUNT_TOKEN_OWNERSHIP_LIMIT
1781 {
1782 ACCOUNT_TOKEN_OWNERSHIP_LIMIT
1783 } else {
1784 collection.limits.account_token_ownership_limit
1785 };
1786
1787 ensure!(
1788 collection.limits.token_limit >= total_items,
1789 Error::<T>::CollectionTokenLimitExceeded
1790 );
1791 ensure!(
1792 account_token_limit >= account_items,
1793 Error::<T>::AccountTokenLimitExceeded
1794 );
1795
1796 if !Self::is_owner_or_admin_permissions(collection, sender)? {
1797 ensure!(collection.mint_mode, Error::<T>::PublicMintingNotAllowed);
1798 Self::check_white_list(collection, owner)?;
1799 Self::check_white_list(collection, sender)?;
1800 }
1801
1802 Ok(())
1803 }
1804
1805 fn validate_create_item_args(
1806 target_collection: &CollectionHandle<T>,
1807 data: &CreateItemData,
1808 ) -> DispatchResult {
1809 match target_collection.mode {
1810 CollectionMode::NFT => {
1811 if !matches!(data, CreateItemData::NFT(_)) {
1812 fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);
1813 }
1814 }
1815 CollectionMode::Fungible(_) => {
1816 if !matches!(data, CreateItemData::Fungible(_)) {
1817 fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);
1818 }
1819 }
1820 CollectionMode::ReFungible => {
1821 if let CreateItemData::ReFungible(data) = data {
1822 // Check refungibility limits
1823 ensure!(
1824 data.pieces <= MAX_REFUNGIBLE_PIECES,
1825 Error::<T>::WrongRefungiblePieces
1826 );
1827 ensure!(data.pieces > 0, Error::<T>::WrongRefungiblePieces);
1828 } else {
1829 fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);
1830 }
1831 }
1832 };
1833
1834 Ok(())
1835 }
1836
1837 fn create_item_no_validation(
1838 collection: &CollectionHandle<T>,
1839 owner: &T::CrossAccountId,
1840 data: CreateItemData,
1841 ) -> DispatchResult {
1842 match data {
1843 CreateItemData::NFT(data) => {
1844 let item = NftItemType {
1845 owner: owner.clone(),
1846 const_data: data.const_data.into_inner(),
1847 variable_data: data.variable_data.into_inner(),
1848 };
1849
1850 Self::add_nft_item(collection, item)?;
1851 }
1852 CreateItemData::Fungible(data) => {
1853 Self::add_fungible_item(collection, owner, data.value)?;
1854 }
1855 CreateItemData::ReFungible(data) => {
1856 let owner_list = vec![Ownership {
1857 owner: owner.clone(),
1858 fraction: data.pieces,
1859 }];
1860
1861 let item = ReFungibleItemType {
1862 owner: owner_list,
1863 const_data: data.const_data.into_inner(),
1864 variable_data: data.variable_data.into_inner(),
1865 };
1866
1867 Self::add_refungible_item(collection, item)?;
1868 }
1869 };
1870
1871 Ok(())
1872 }
1873
1874 fn add_fungible_item(
1875 collection: &CollectionHandle<T>,
1876 owner: &T::CrossAccountId,
1877 value: u128,
1878 ) -> DispatchResult {
1879 let collection_id = collection.id;
1880
1881 // Does new owner already have an account?
1882 collection.consume_sload()?;
1883 let balance: u128 = <FungibleItemList<T>>::get(collection_id, owner.as_sub()).value;
1884
1885 // Mint
1886 let item = FungibleItemType {
1887 value: balance.checked_add(value).ok_or(Error::<T>::NumOverflow)?,
1888 };
1889 collection.consume_sstore()?;
1890 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), item);
1891
1892 // Update balance
1893 collection.consume_sload()?;
1894 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())
1895 .checked_add(value)
1896 .ok_or(Error::<T>::NumOverflow)?;
1897 collection.consume_sstore()?;
1898 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);
1899
1900 collection.log(ERC20Events::Transfer {
1901 from: H160::default(),
1902 to: *owner.as_eth(),
1903 value: value.into(),
1904 })?;
1905 Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));
1906 Ok(())
1907 }
1908
1909 fn add_refungible_item(
1910 collection: &CollectionHandle<T>,
1911 item: ReFungibleItemType<T::CrossAccountId>,
1912 ) -> DispatchResult {
1913 let collection_id = collection.id;
1914
1915 let current_index = <ItemListIndex>::get(collection_id)
1916 .checked_add(1)
1917 .ok_or(Error::<T>::NumOverflow)?;
1918 let itemcopy = item.clone();
1919
1920 ensure!(item.owner.len() == 1, Error::<T>::BadCreateRefungibleCall,);
1921 let item_owner = item.owner.first().expect("only one owner is defined");
1922
1923 let value = item_owner.fraction;
1924 let owner = item_owner.owner.clone();
1925
1926 Self::add_token_index(collection, current_index, &owner)?;
1927
1928 <ItemListIndex>::insert(collection_id, current_index);
1929 <ReFungibleItemList<T>>::insert(collection_id, current_index, itemcopy);
1930
1931 // Update balance
1932 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())
1933 .checked_add(value)
1934 .ok_or(Error::<T>::NumOverflow)?;
1935 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);
1936
1937 Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));
1938 Ok(())
1939 }
1940
1941 fn add_nft_item(
1942 collection: &CollectionHandle<T>,
1943 item: NftItemType<T::CrossAccountId>,
1944 ) -> DispatchResult {
1945 let collection_id = collection.id;
1946
1947 let current_index = <ItemListIndex>::get(collection_id)
1948 .checked_add(1)
1949 .ok_or(Error::<T>::NumOverflow)?;
1950
1951 let item_owner = item.owner.clone();
1952 Self::add_token_index(collection, current_index, &item.owner)?;
1953
1954 <ItemListIndex>::insert(collection_id, current_index);
1955 <NftItemList<T>>::insert(collection_id, current_index, item);
1956
1957 // Update balance
1958 let new_balance = <Balance<T>>::get(collection_id, item_owner.as_sub())
1959 .checked_add(1)
1960 .ok_or(Error::<T>::NumOverflow)?;
1961 <Balance<T>>::insert(collection_id, item_owner.as_sub(), new_balance);
1962
1963 collection.log(ERC721Events::Transfer {
1964 from: H160::default(),
1965 to: *item_owner.as_eth(),
1966 token_id: current_index.into(),
1967 })?;
1968 Self::deposit_event(RawEvent::ItemCreated(
1969 collection_id,
1970 current_index,
1971 item_owner,
1972 ));
1973 Ok(())
1974 }
1975
1976 fn burn_refungible_item(
1977 collection: &CollectionHandle<T>,
1978 item_id: TokenId,
1979 owner: &T::CrossAccountId,
1980 value: u128,
1981 ) -> DispatchResult {
1982 let collection_id = collection.id;
1983
1984 let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id)
1985 .ok_or(Error::<T>::TokenNotFound)?;
1986 let mut rft_balance = token
1987 .owner
1988 .iter()
1989 .find(|&i| i.owner == *owner)
1990 .ok_or(Error::<T>::TokenNotFound)?
1991 .clone();
1992 Self::remove_token_index(collection, item_id, owner)?;
1993
1994 // update balance
1995 let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.as_sub())
1996 .checked_sub(value)
1997 .ok_or(Error::<T>::NumOverflow)?;
1998 <Balance<T>>::insert(collection_id, rft_balance.owner.as_sub(), new_balance);
1999
2000 rft_balance.fraction = (rft_balance.fraction)
2001 .checked_sub(value)
2002 .ok_or(Error::<T>::NumOverflow)?;
2003
2004 let index = token
2005 .owner
2006 .iter()
2007 .position(|i| i.owner == *owner)
2008 .expect("owned item is exists");
2009 if rft_balance.fraction == 0 {
2010 // Re-create owners list with sender removed
2011 token.owner.remove(index);
2012 } else {
2013 token.owner[index] = rft_balance;
2014 }
2015
2016 let owner_count = token.owner.len();
2017
2018 // Burn the token completely if this was the last (only) owner
2019 if owner_count == 0 {
2020 <ReFungibleItemList<T>>::remove(collection_id, item_id);
2021 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);
2022 } else {
2023 <ReFungibleItemList<T>>::insert(collection_id, item_id, token);
2024 }
2025
2026 Ok(())
2027 }
2028
2029 fn burn_nft_item(collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {
2030 let collection_id = collection.id;
2031
2032 let item =
2033 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;
2034 Self::remove_token_index(collection, item_id, &item.owner)?;
2035
2036 // update balance
2037 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())
2038 .checked_sub(1)
2039 .ok_or(Error::<T>::NumOverflow)?;
2040 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);
2041 <NftItemList<T>>::remove(collection_id, item_id);
2042 <VariableMetaDataBasket<T>>::remove(collection_id, item_id);
2043
2044 collection.log(ERC721Events::Transfer {
2045 from: *item.owner.as_eth(),
2046 to: H160::default(),
2047 token_id: item_id.into(),
2048 })?;
2049 Self::deposit_event(RawEvent::ItemDestroyed(collection.id, item_id));
2050 Ok(())
2051 }
2052
2053 fn burn_fungible_item(
2054 collection: &CollectionHandle<T>,
2055 owner: &T::CrossAccountId,
2056 value: u128,
2057 ) -> DispatchResult {
2058 let collection_id = collection.id;
2059
2060 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());
2061 ensure!(balance.value >= value, Error::<T>::TokenValueNotEnough);
2062
2063 // update balance
2064 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())
2065 .checked_sub(value)
2066 .ok_or(Error::<T>::NumOverflow)?;
2067 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);
2068
2069 if balance.value - value > 0 {
2070 balance.value -= value;
2071 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);
2072 } else {
2073 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());
2074 }
2075
2076 collection.log(ERC20Events::Transfer {
2077 from: *owner.as_eth(),
2078 to: H160::default(),
2079 value: value.into(),
2080 })?;
2081 Ok(())
2082 }
2083
2084 pub fn get_collection(
2085 collection_id: CollectionId,
2086 ) -> Result<CollectionHandle<T>, sp_runtime::DispatchError> {
2087 Ok(<CollectionHandle<T>>::get(collection_id).ok_or(Error::<T>::CollectionNotFound)?)
2088 }
2089
2090 fn check_owner_permissions(
2091 target_collection: &CollectionHandle<T>,
2092 subject: &T::AccountId,
2093 ) -> DispatchResult {
2094 ensure!(
2095 *subject == target_collection.owner,
2096 Error::<T>::NoPermission
2097 );
2098
2099 Ok(())
2100 }
2101
2102 fn is_owner_or_admin_permissions(
2103 collection: &CollectionHandle<T>,
2104 subject: &T::CrossAccountId,
2105 ) -> Result<bool, DispatchError> {
2106 collection.consume_sload()?;
2107 Ok(*subject.as_sub() == collection.owner
2108 || <AdminList<T>>::get(collection.id).contains(subject))
2109 }
2110
2111 fn check_owner_or_admin_permissions(
2112 collection: &CollectionHandle<T>,
2113 subject: &T::CrossAccountId,
2114 ) -> DispatchResult {
2115 ensure!(
2116 Self::is_owner_or_admin_permissions(collection, subject)?,
2117 Error::<T>::NoPermission
2118 );
2119
2120 Ok(())
2121 }
2122
2123 fn owned_amount(
2124 subject: &T::CrossAccountId,
2125 collection: &CollectionHandle<T>,
2126 item_id: TokenId,
2127 ) -> Result<Option<u128>, DispatchError> {
2128 collection.consume_sload()?;
2129 Ok(Self::owned_amount_unchecked(subject, collection, item_id))
2130 }
2131
2132 fn owned_amount_unchecked(
2133 subject: &T::CrossAccountId,
2134 target_collection: &CollectionHandle<T>,
2135 item_id: TokenId,
2136 ) -> Option<u128> {
2137 let collection_id = target_collection.id;
2138
2139 match target_collection.mode {
2140 CollectionMode::NFT => {
2141 (<NftItemList<T>>::get(collection_id, item_id)?.owner == *subject).then(|| 1)
2142 }
2143 CollectionMode::Fungible(_) => {
2144 Some(<FungibleItemList<T>>::get(collection_id, &subject.as_sub()).value)
2145 }
2146 CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)?
2147 .owner
2148 .iter()
2149 .find(|i| i.owner == *subject)
2150 .map(|i| i.fraction),
2151 }
2152 }
2153
2154 fn is_item_owner(
2155 subject: &T::CrossAccountId,
2156 target_collection: &CollectionHandle<T>,
2157 item_id: TokenId,
2158 ) -> Result<bool, DispatchError> {
2159 Ok(match target_collection.mode {
2160 CollectionMode::Fungible(_) => true,
2161 _ => Self::owned_amount(subject, target_collection, item_id)?.is_some(),
2162 })
2163 }
2164
2165 fn check_white_list(
2166 collection: &CollectionHandle<T>,
2167 address: &T::CrossAccountId,
2168 ) -> DispatchResult {
2169 collection.consume_sload()?;
2170 ensure!(
2171 <WhiteList<T>>::contains_key(collection.id, address.as_sub()),
2172 Error::<T>::AddresNotInWhiteList,
2173 );
2174 Ok(())
2175 }
2176
2177 /// Check if token exists. In case of Fungible, check if there is an entry for
2178 /// the owner in fungible balances double map
2179 fn token_exists(target_collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {
2180 let collection_id = target_collection.id;
2181 let exists = match target_collection.mode {
2182 CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),
2183 CollectionMode::Fungible(_) => true,
2184 CollectionMode::ReFungible => {
2185 <ReFungibleItemList<T>>::contains_key(collection_id, item_id)
2186 }
2187 };
2188
2189 ensure!(exists, Error::<T>::TokenNotFound);
2190 Ok(())
2191 }
2192
2193 fn transfer_fungible(
2194 collection: &CollectionHandle<T>,
2195 value: u128,
2196 owner: &T::CrossAccountId,
2197 recipient: &T::CrossAccountId,
2198 ) -> DispatchResult {
2199 let collection_id = collection.id;
2200
2201 collection.consume_sload()?;
2202 collection.consume_sload()?;
2203 let mut recipient_balance = <FungibleItemList<T>>::get(collection_id, recipient.as_sub());
2204 let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());
2205
2206 recipient_balance.value = recipient_balance
2207 .value
2208 .checked_add(value)
2209 .ok_or(Error::<T>::NumOverflow)?;
2210 balance.value = balance
2211 .value
2212 .checked_sub(value)
2213 .ok_or(Error::<T>::TokenValueTooLow)?;
2214
2215 // update balanceOf
2216 collection.consume_sstore()?;
2217 collection.consume_sstore()?;
2218 if balance.value != 0 {
2219 <Balance<T>>::insert(collection_id, owner.as_sub(), balance.value);
2220 } else {
2221 <Balance<T>>::remove(collection_id, owner.as_sub());
2222 }
2223 <Balance<T>>::insert(collection_id, recipient.as_sub(), recipient_balance.value);
2224
2225 // Reduce or remove sender
2226 collection.consume_sstore()?;
2227 collection.consume_sstore()?;
2228 if balance.value != 0 {
2229 <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);
2230 } else {
2231 <FungibleItemList<T>>::remove(collection_id, owner.as_sub());
2232 }
2233 <FungibleItemList<T>>::insert(collection_id, recipient.as_sub(), recipient_balance);
2234
2235 collection.log(ERC20Events::Transfer {
2236 from: *owner.as_eth(),
2237 to: *recipient.as_eth(),
2238 value: value.into(),
2239 })?;
2240 Self::deposit_event(RawEvent::Transfer(
2241 collection.id,
2242 1,
2243 owner.clone(),
2244 recipient.clone(),
2245 value,
2246 ));
2247
2248 Ok(())
2249 }
2250
2251 fn transfer_refungible(
2252 collection: &CollectionHandle<T>,
2253 item_id: TokenId,
2254 value: u128,
2255 owner: T::CrossAccountId,
2256 new_owner: T::CrossAccountId,
2257 ) -> DispatchResult {
2258 let collection_id = collection.id;
2259 collection.consume_sload()?;
2260 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id)
2261 .ok_or(Error::<T>::TokenNotFound)?;
2262
2263 let item = full_item
2264 .owner
2265 .iter()
2266 .find(|i| i.owner == owner)
2267 .ok_or(Error::<T>::TokenNotFound)?;
2268 let amount = item.fraction;
2269
2270 ensure!(amount >= value, Error::<T>::TokenValueTooLow);
2271
2272 collection.consume_sload()?;
2273 // update balance
2274 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())
2275 .checked_sub(value)
2276 .ok_or(Error::<T>::NumOverflow)?;
2277 collection.consume_sstore()?;
2278 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);
2279
2280 collection.consume_sload()?;
2281 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())
2282 .checked_add(value)
2283 .ok_or(Error::<T>::NumOverflow)?;
2284 collection.consume_sstore()?;
2285 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);
2286
2287 let old_owner = item.owner.clone();
2288 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);
2289
2290 let mut new_full_item = full_item.clone();
2291 // transfer
2292 if amount == value && !new_owner_has_account {
2293 // change owner
2294 // new owner do not have account
2295 new_full_item
2296 .owner
2297 .iter_mut()
2298 .find(|i| i.owner == owner)
2299 .expect("old owner does present in refungible")
2300 .owner = new_owner.clone();
2301 collection.consume_sstore()?;
2302 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);
2303
2304 // update index collection
2305 Self::move_token_index(collection, item_id, &old_owner, &new_owner)?;
2306 } else {
2307 new_full_item
2308 .owner
2309 .iter_mut()
2310 .find(|i| i.owner == owner)
2311 .expect("old owner does present in refungible")
2312 .fraction -= value;
2313
2314 // separate amount
2315 if new_owner_has_account {
2316 // new owner has account
2317 new_full_item
2318 .owner
2319 .iter_mut()
2320 .find(|i| i.owner == new_owner)
2321 .expect("new owner has account")
2322 .fraction += value;
2323 } else {
2324 // new owner do not have account
2325 new_full_item.owner.push(Ownership {
2326 owner: new_owner.clone(),
2327 fraction: value,
2328 });
2329 Self::add_token_index(collection, item_id, &new_owner)?;
2330 }
2331
2332 collection.consume_sstore()?;
2333 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);
2334 }
2335
2336 Self::deposit_event(RawEvent::Transfer(
2337 collection.id,
2338 item_id,
2339 owner,
2340 new_owner,
2341 amount,
2342 ));
2343
2344 Ok(())
2345 }
2346
2347 fn transfer_nft(
2348 collection: &CollectionHandle<T>,
2349 item_id: TokenId,
2350 sender: T::CrossAccountId,
2351 new_owner: T::CrossAccountId,
2352 ) -> DispatchResult {
2353 let collection_id = collection.id;
2354 collection.consume_sload()?;
2355 let mut item =
2356 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;
2357
2358 ensure!(sender == item.owner, Error::<T>::MustBeTokenOwner);
2359
2360 collection.consume_sload()?;
2361 // update balance
2362 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())
2363 .checked_sub(1)
2364 .ok_or(Error::<T>::NumOverflow)?;
2365 collection.consume_sstore()?;
2366 <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);
2367
2368 collection.consume_sload()?;
2369 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())
2370 .checked_add(1)
2371 .ok_or(Error::<T>::NumOverflow)?;
2372 collection.consume_sstore()?;
2373 <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);
2374
2375 // change owner
2376 let old_owner = item.owner.clone();
2377 item.owner = new_owner.clone();
2378 collection.consume_sstore()?;
2379 <NftItemList<T>>::insert(collection_id, item_id, item);
2380
2381 // update index collection
2382 Self::move_token_index(collection, item_id, &old_owner, &new_owner)?;
2383
2384 collection.log(ERC721Events::Transfer {
2385 from: *sender.as_eth(),
2386 to: *new_owner.as_eth(),
2387 token_id: item_id.into(),
2388 })?;
2389 Self::deposit_event(RawEvent::Transfer(
2390 collection.id,
2391 item_id,
2392 sender,
2393 new_owner,
2394 1,
2395 ));
2396
2397 Ok(())
2398 }
2399
2400 fn set_re_fungible_variable_data(
2401 collection: &CollectionHandle<T>,
2402 item_id: TokenId,
2403 data: Vec<u8>,
2404 ) -> DispatchResult {
2405 let collection_id = collection.id;
2406 let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id)
2407 .ok_or(Error::<T>::TokenNotFound)?;
2408
2409 item.variable_data = data;
2410
2411 <ReFungibleItemList<T>>::insert(collection_id, item_id, item);
2412
2413 Ok(())
2414 }
2415
2416 fn set_nft_variable_data(
2417 collection: &CollectionHandle<T>,
2418 item_id: TokenId,
2419 data: Vec<u8>,
2420 ) -> DispatchResult {
2421 let collection_id = collection.id;
2422 let mut item =
2423 <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;
2424
2425 item.variable_data = data;
2426
2427 <NftItemList<T>>::insert(collection_id, item_id, item);
2428
2429 Ok(())
2430 }
2431
2432 #[allow(dead_code)]
2433 fn init_collection(item: &Collection<T>) {
2434 // check params
2435 assert!(
2436 item.decimal_points <= MAX_DECIMAL_POINTS,
2437 "decimal_points parameter must be lower than MAX_DECIMAL_POINTS"
2438 );
2439 assert!(
2440 item.name.len() <= 64,
2441 "Collection name can not be longer than 63 char"
2442 );
2443 assert!(
2444 item.name.len() <= 256,
2445 "Collection description can not be longer than 255 char"
2446 );
2447 assert!(
2448 item.token_prefix.len() <= 16,
2449 "Token prefix can not be longer than 15 char"
2450 );
2451
2452 // Generate next collection ID
2453 let next_id = CreatedCollectionCount::get().checked_add(1).unwrap();
2454
2455 CreatedCollectionCount::put(next_id);
2456 }
2457
2458 #[allow(dead_code)]
2459 fn init_nft_token(collection_id: CollectionId, item: &NftItemType<T::CrossAccountId>) {
2460 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();
2461
2462 Self::add_token_index(
2463 &CollectionHandle::get(collection_id).unwrap(),
2464 current_index,
2465 &item.owner,
2466 )
2467 .unwrap();
2468
2469 <ItemListIndex>::insert(collection_id, current_index);
2470
2471 // Update balance
2472 let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())
2473 .checked_add(1)
2474 .unwrap();
2475 <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);
2476 }
2477
2478 #[allow(dead_code)]
2479 fn init_fungible_token(
2480 collection_id: CollectionId,
2481 owner: &T::CrossAccountId,
2482 item: &FungibleItemType,
2483 ) {
2484 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();
2485
2486 Self::add_token_index(
2487 &CollectionHandle::get(collection_id).unwrap(),
2488 current_index,
2489 owner,
2490 )
2491 .unwrap();
2492
2493 <ItemListIndex>::insert(collection_id, current_index);
2494
2495 // Update balance
2496 let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())
2497 .checked_add(item.value)
2498 .unwrap();
2499 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);
2500 }
2501
2502 #[allow(dead_code)]
2503 fn init_refungible_token(
2504 collection_id: CollectionId,
2505 item: &ReFungibleItemType<T::CrossAccountId>,
2506 ) {
2507 let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();
2508
2509 let value = item.owner.first().unwrap().fraction;
2510 let owner = item.owner.first().unwrap().owner.clone();
2511
2512 Self::add_token_index(
2513 &CollectionHandle::get(collection_id).unwrap(),
2514 current_index,
2515 &owner,
2516 )
2517 .unwrap();
2518
2519 <ItemListIndex>::insert(collection_id, current_index);
2520
2521 // Update balance
2522 let new_balance = <Balance<T>>::get(collection_id, &owner.as_sub())
2523 .checked_add(value)
2524 .unwrap();
2525 <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);
2526 }
2527
2528 fn add_token_index(
2529 collection: &CollectionHandle<T>,
2530 item_index: TokenId,
2531 owner: &T::CrossAccountId,
2532 ) -> DispatchResult {
2533 collection.consume_sload()?;
2534 let list_exists = <AddressTokens<T>>::contains_key(collection.id, owner.as_sub());
2535 if list_exists {
2536 collection.consume_sload()?;
2537 let mut list = <AddressTokens<T>>::get(collection.id, owner.as_sub());
2538
2539 // bound Owned tokens by a single address in collection
2540 let account_items: u32 = list.len() as u32;
2541 ensure!(
2542 account_items < ACCOUNT_TOKEN_OWNERSHIP_LIMIT,
2543 Error::<T>::AddressOwnershipLimitExceeded
2544 );
2545
2546 let item_contains = list.contains(&item_index.clone());
2547
2548 if !item_contains {
2549 list.push(item_index);
2550 }
2551
2552 collection.consume_sstore()?;
2553 <AddressTokens<T>>::insert(collection.id, owner.as_sub(), list);
2554 } else {
2555 let itm = vec![item_index];
2556 collection.consume_sstore()?;
2557 <AddressTokens<T>>::insert(collection.id, owner.as_sub(), itm);
2558 }
2559
2560 Ok(())
2561 }
2562
2563 fn remove_token_index(
2564 collection: &CollectionHandle<T>,
2565 item_index: TokenId,
2566 owner: &T::CrossAccountId,
2567 ) -> DispatchResult {
2568 collection.consume_sload()?;
2569 let list_exists = <AddressTokens<T>>::contains_key(collection.id, owner.as_sub());
2570 if list_exists {
2571 collection.consume_sload()?;
2572 let mut list = <AddressTokens<T>>::get(collection.id, owner.as_sub());
2573 let item_contains = list.contains(&item_index.clone());
2574
2575 if item_contains {
2576 list.retain(|&item| item != item_index);
2577 collection.consume_sstore()?;
2578 <AddressTokens<T>>::insert(collection.id, owner.as_sub(), list);
2579 }
2580 }
2581
2582 Ok(())
2583 }
2584
2585 fn move_token_index(
2586 collection: &CollectionHandle<T>,
2587 item_index: TokenId,
2588 old_owner: &T::CrossAccountId,
2589 new_owner: &T::CrossAccountId,
2590 ) -> DispatchResult {
2591 Self::remove_token_index(collection, item_index, old_owner)?;
2592 Self::add_token_index(collection, item_index, new_owner)?;
2593
2594 Ok(())
2595 }
2596}
2597
2598sp_api::decl_runtime_apis! {
2599 pub trait NftApi {
2600 /// Used for ethereum integration
2601 fn eth_contract_code(account: H160) -> Option<Vec<u8>>;
2602 }932 }
2603}933}
2604934
modifiedpallets/nft/src/sponsorship.rsdiffbeforeafterboth
1use crate::{1use crate::{
2 Config, Call, CollectionById, CreateItemBasket, VariableMetaDataBasket,2 Config, Call, CreateItemBasket, VariableMetaDataBasket, ReFungibleTransferBasket,
3 ReFungibleTransferBasket, FungibleTransferBasket, NftTransferBasket, CreateItemData,3 FungibleTransferBasket, NftTransferBasket, CreateItemData, CollectionMode,
4 CollectionMode,
5};4};
13 TokenId, CollectionId, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,12 TokenId, CollectionId, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
14 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,13 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
15};14};
15use pallet_common::{CollectionById};
1616
17pub struct NftSponsorshipHandler<T>(PhantomData<T>);17pub struct NftSponsorshipHandler<T>(PhantomData<T>);
18impl<T: Config> NftSponsorshipHandler<T> {18impl<T: Config> NftSponsorshipHandler<T> {
61 sponsor_transfer = match collection_mode {61 sponsor_transfer = match collection_mode {
62 CollectionMode::NFT => {62 CollectionMode::NFT => {
63 // get correct limit63 // get correct limit
64 let limit: u32 = if collection_limits.sponsor_transfer_timeout != 0 {64 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
65 if collection_limits.sponsor_transfer_timeout > NFT_SPONSOR_TRANSFER_TIMEOUT
66 {
67 collection_limits.sponsor_transfer_timeout65 collection_limits.sponsor_transfer_timeout
68 } else {66 } else {
69 NFT_SPONSOR_TRANSFER_TIMEOUT67 NFT_SPONSOR_TRANSFER_TIMEOUT
70 }68 };
71 } else {
72 0
73 };
7469
75 let mut sponsored = true;70 let mut sponsored = true;
76 if NftTransferBasket::<T>::contains_key(collection_id, item_id) {71 if NftTransferBasket::<T>::contains_key(collection_id, item_id) {
88 }83 }
89 CollectionMode::Fungible(_) => {84 CollectionMode::Fungible(_) => {
90 // get correct limit85 // get correct limit
91 let limit: u32 = if collection_limits.sponsor_transfer_timeout != 0 {86 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
92 if collection_limits.sponsor_transfer_timeout
93 > FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
94 {
95 collection_limits.sponsor_transfer_timeout87 collection_limits.sponsor_transfer_timeout
96 } else {88 } else {
97 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT89 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
98 }90 };
99 } else {91
100 092 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
101 };
102
103 let mut sponsored = true;93 let mut sponsored = true;
104 if FungibleTransferBasket::<T>::contains_key(collection_id, who) {94 if FungibleTransferBasket::<T>::contains_key(collection_id, who) {
116 }106 }
117 CollectionMode::ReFungible => {107 CollectionMode::ReFungible => {
118 // get correct limit108 // get correct limit
119 let limit: u32 = if collection_limits.sponsor_transfer_timeout != 0 {109 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
120 if collection_limits.sponsor_transfer_timeout
121 > REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
122 {
123 collection_limits.sponsor_transfer_timeout110 collection_limits.sponsor_transfer_timeout
124 } else {111 } else {
125 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT112 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
126 }113 };
127 } else {
128 0
129 };
130114
131 let mut sponsored = true;115 let mut sponsored = true;
132 if ReFungibleTransferBasket::<T>::contains_key(collection_id, item_id) {116 if ReFungibleTransferBasket::<T>::contains_key(collection_id, item_id) {
modifiedpallets/nft/src/weights.rsdiffbeforeafterboth
22
3//! Autogenerated weights for pallet_nft3//! Autogenerated weights for pallet_nft
4//!4//!
5//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.05//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
6//! DATE: 2021-08-31, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`6//! DATE: 2021-10-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
7//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1287//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 128
88
9// Executed Command:9// Executed Command:
43 fn set_collection_sponsor() -> Weight;43 fn set_collection_sponsor() -> Weight;
44 fn confirm_sponsorship() -> Weight;44 fn confirm_sponsorship() -> Weight;
45 fn remove_collection_sponsor() -> Weight;45 fn remove_collection_sponsor() -> Weight;
46 fn create_item_nft(b: u32, ) -> Weight;
47 fn create_multiple_items_nft(b: u32, ) -> Weight;
48 fn create_item_fungible() -> Weight;
49 fn create_multiple_items_fungible(b: u32, ) -> Weight;
50 fn create_item_refungible(b: u32, ) -> Weight;
51 fn create_multiple_items_refungible(b: u32, ) -> Weight;
52 fn burn_item_nft() -> Weight;
53 fn transfer_nft() -> Weight;
54 fn transfer_fungible() -> Weight;
55 fn transfer_refungible() -> Weight;
56 fn set_transfers_enabled_flag() -> Weight;46 fn set_transfers_enabled_flag() -> Weight;
57 fn approve_nft() -> Weight;
58 fn transfer_from_nft() -> Weight;
59 fn transfer_from_fungible() -> Weight;
60 fn transfer_from_refungible() -> Weight;
61 fn set_offchain_schema(b: u32, ) -> Weight;47 fn set_offchain_schema(b: u32, ) -> Weight;
62 fn set_const_on_chain_schema(b: u32, ) -> Weight;48 fn set_const_on_chain_schema(b: u32, ) -> Weight;
63 fn set_variable_on_chain_schema(b: u32, ) -> Weight;49 fn set_variable_on_chain_schema(b: u32, ) -> Weight;
64 fn set_variable_meta_data_nft(b: u32, ) -> Weight;
65 fn set_schema_version() -> Weight;50 fn set_schema_version() -> Weight;
66 fn set_collection_limits() -> Weight;51 fn set_collection_limits() -> Weight;
52 fn set_meta_update_permission_flag() -> Weight;
67}53}
6854
69/// Weights for pallet_nft using the Substrate node and recommended hardware.55/// Weights for pallet_nft using the Substrate node and recommended hardware.
70pub struct SubstrateWeight<T>(PhantomData<T>);56pub struct SubstrateWeight<T>(PhantomData<T>);
71impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {57impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
58 // Storage: Common CreatedCollectionCount (r:1 w:1)
59 // Storage: Common DestroyedCollectionCount (r:1 w:0)
60 // Storage: System Account (r:2 w:2)
61 // Storage: Common CollectionById (r:0 w:1)
72 fn create_collection() -> Weight {62 fn create_collection() -> Weight {
73 (25_851_000 as Weight)63 (23_803_000 as Weight)
74 .saturating_add(T::DbWeight::get().reads(8 as Weight))64 .saturating_add(T::DbWeight::get().reads(4 as Weight))
75 .saturating_add(T::DbWeight::get().writes(6 as Weight))65 .saturating_add(T::DbWeight::get().writes(4 as Weight))
76 }66 }
67 // Storage: Common CollectionById (r:1 w:1)
68 // Storage: Common DestroyedCollectionCount (r:1 w:1)
69 // Storage: Nonfungible TokensMinted (r:0 w:1)
70 // Storage: Nonfungible TokensBurnt (r:0 w:1)
77 fn destroy_collection() -> Weight {71 fn destroy_collection() -> Weight {
78 (28_737_000 as Weight)72 (27_831_000 as Weight)
79 .saturating_add(T::DbWeight::get().reads(2 as Weight))73 .saturating_add(T::DbWeight::get().reads(2 as Weight))
80 .saturating_add(T::DbWeight::get().writes(4 as Weight))74 .saturating_add(T::DbWeight::get().writes(4 as Weight))
81 }75 }
76 // Storage: Common CollectionById (r:1 w:0)
77 // Storage: Common Allowlist (r:0 w:1)
82 fn add_to_white_list() -> Weight {78 fn add_to_white_list() -> Weight {
83 (6_237_000 as Weight)79 (6_629_000 as Weight)
84 .saturating_add(T::DbWeight::get().reads(1 as Weight))80 .saturating_add(T::DbWeight::get().reads(1 as Weight))
85 .saturating_add(T::DbWeight::get().writes(1 as Weight))81 .saturating_add(T::DbWeight::get().writes(1 as Weight))
86 }82 }
83 // Storage: Common CollectionById (r:1 w:0)
84 // Storage: Common Allowlist (r:0 w:1)
87 fn remove_from_white_list() -> Weight {85 fn remove_from_white_list() -> Weight {
88 (6_252_000 as Weight)86 (6_596_000 as Weight)
89 .saturating_add(T::DbWeight::get().reads(1 as Weight))87 .saturating_add(T::DbWeight::get().reads(1 as Weight))
90 .saturating_add(T::DbWeight::get().writes(1 as Weight))88 .saturating_add(T::DbWeight::get().writes(1 as Weight))
91 }89 }
90 // Storage: Common CollectionById (r:1 w:1)
92 fn set_public_access_mode() -> Weight {91 fn set_public_access_mode() -> Weight {
93 (6_691_000 as Weight)92 (6_338_000 as Weight)
94 .saturating_add(T::DbWeight::get().reads(1 as Weight))93 .saturating_add(T::DbWeight::get().reads(1 as Weight))
95 .saturating_add(T::DbWeight::get().writes(1 as Weight))94 .saturating_add(T::DbWeight::get().writes(1 as Weight))
96 }95 }
96 // Storage: Common CollectionById (r:1 w:1)
97 fn set_mint_permission() -> Weight {97 fn set_mint_permission() -> Weight {
98 (6_630_000 as Weight)98 (6_383_000 as Weight)
99 .saturating_add(T::DbWeight::get().reads(1 as Weight))99 .saturating_add(T::DbWeight::get().reads(1 as Weight))
100 .saturating_add(T::DbWeight::get().writes(1 as Weight))100 .saturating_add(T::DbWeight::get().writes(1 as Weight))
101 }101 }
102 // Storage: Common CollectionById (r:1 w:1)
102 fn change_collection_owner() -> Weight {103 fn change_collection_owner() -> Weight {
103 (6_521_000 as Weight)104 (6_493_000 as Weight)
104 .saturating_add(T::DbWeight::get().reads(1 as Weight))105 .saturating_add(T::DbWeight::get().reads(1 as Weight))
105 .saturating_add(T::DbWeight::get().writes(1 as Weight))106 .saturating_add(T::DbWeight::get().writes(1 as Weight))
106 }107 }
108 // Storage: Common CollectionById (r:1 w:0)
109 // Storage: Common IsAdmin (r:0 w:1)
107 fn add_collection_admin() -> Weight {110 fn add_collection_admin() -> Weight {
108 (8_057_000 as Weight)111 (6_850_000 as Weight)
109 .saturating_add(T::DbWeight::get().reads(2 as Weight))112 .saturating_add(T::DbWeight::get().reads(1 as Weight))
110 .saturating_add(T::DbWeight::get().writes(1 as Weight))113 .saturating_add(T::DbWeight::get().writes(1 as Weight))
111 }114 }
115 // Storage: Common CollectionById (r:1 w:0)
116 // Storage: Common IsAdmin (r:0 w:1)
112 fn remove_collection_admin() -> Weight {117 fn remove_collection_admin() -> Weight {
113 (8_307_000 as Weight)118 (6_615_000 as Weight)
114 .saturating_add(T::DbWeight::get().reads(2 as Weight))119 .saturating_add(T::DbWeight::get().reads(1 as Weight))
115 .saturating_add(T::DbWeight::get().writes(1 as Weight))120 .saturating_add(T::DbWeight::get().writes(1 as Weight))
116 }121 }
122 // Storage: Common CollectionById (r:1 w:1)
117 fn set_collection_sponsor() -> Weight {123 fn set_collection_sponsor() -> Weight {
118 (6_484_000 as Weight)124 (6_430_000 as Weight)
119 .saturating_add(T::DbWeight::get().reads(1 as Weight))125 .saturating_add(T::DbWeight::get().reads(1 as Weight))
120 .saturating_add(T::DbWeight::get().writes(1 as Weight))126 .saturating_add(T::DbWeight::get().writes(1 as Weight))
121 }127 }
128 // Storage: Common CollectionById (r:1 w:1)
122 fn confirm_sponsorship() -> Weight {129 fn confirm_sponsorship() -> Weight {
123 (6_530_000 as Weight)130 (6_125_000 as Weight)
124 .saturating_add(T::DbWeight::get().reads(1 as Weight))131 .saturating_add(T::DbWeight::get().reads(1 as Weight))
125 .saturating_add(T::DbWeight::get().writes(1 as Weight))132 .saturating_add(T::DbWeight::get().writes(1 as Weight))
126 }133 }
134 // Storage: Common CollectionById (r:1 w:1)
127 fn remove_collection_sponsor() -> Weight {135 fn remove_collection_sponsor() -> Weight {
128 (6_733_000 as Weight)136 (6_236_000 as Weight)
129 .saturating_add(T::DbWeight::get().reads(1 as Weight))137 .saturating_add(T::DbWeight::get().reads(1 as Weight))
130 .saturating_add(T::DbWeight::get().writes(1 as Weight))138 .saturating_add(T::DbWeight::get().writes(1 as Weight))
131 }139 }
132 fn create_item_nft(_b: u32, ) -> Weight {140 // Storage: Common CollectionById (r:1 w:1)
133 (167_909_000 as Weight)
134 .saturating_add(T::DbWeight::get().reads(11 as Weight))
135 .saturating_add(T::DbWeight::get().writes(8 as Weight))
136 }
137 fn create_multiple_items_nft(b: u32, ) -> Weight {
138 (336_830_000 as Weight)
139 // Standard Error: 42_000
140 .saturating_add((11_627_000 as Weight).saturating_mul(b as Weight))
141 .saturating_add(T::DbWeight::get().reads(11 as Weight))
142 .saturating_add(T::DbWeight::get().writes(7 as Weight))
143 .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(b as Weight)))
144 }
145 fn create_item_fungible() -> Weight {
146 (24_123_000 as Weight)
147 .saturating_add(T::DbWeight::get().reads(9 as Weight))
148 .saturating_add(T::DbWeight::get().writes(4 as Weight))
149 }
150 fn create_multiple_items_fungible(b: u32, ) -> Weight {
151 (48_227_000 as Weight)
152 // Standard Error: 13_000
153 .saturating_add((2_918_000 as Weight).saturating_mul(b as Weight))
154 .saturating_add(T::DbWeight::get().reads(9 as Weight))
155 .saturating_add(T::DbWeight::get().writes(4 as Weight))
156 }
157 fn create_item_refungible(_b: u32, ) -> Weight {
158 (26_293_000 as Weight)
159 .saturating_add(T::DbWeight::get().reads(9 as Weight))
160 .saturating_add(T::DbWeight::get().writes(7 as Weight))
161 }
162 fn create_multiple_items_refungible(b: u32, ) -> Weight {
163 (0 as Weight)
164 // Standard Error: 16_000
165 .saturating_add((8_374_000 as Weight).saturating_mul(b as Weight))
166 .saturating_add(T::DbWeight::get().reads(9 as Weight))
167 .saturating_add(T::DbWeight::get().writes(6 as Weight))
168 .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(b as Weight)))
169 }
170 fn burn_item_nft() -> Weight {
171 (32_237_000 as Weight)
172 .saturating_add(T::DbWeight::get().reads(9 as Weight))
173 .saturating_add(T::DbWeight::get().writes(7 as Weight))
174 }
175 fn transfer_nft() -> Weight {
176 (192_578_000 as Weight)
177 .saturating_add(T::DbWeight::get().reads(14 as Weight))
178 .saturating_add(T::DbWeight::get().writes(10 as Weight))
179 }
180 fn transfer_fungible() -> Weight {
181 (170_749_000 as Weight)
182 .saturating_add(T::DbWeight::get().reads(11 as Weight))
183 .saturating_add(T::DbWeight::get().writes(7 as Weight))
184 }
185 fn transfer_refungible() -> Weight {
186 (35_949_000 as Weight)
187 .saturating_add(T::DbWeight::get().reads(10 as Weight))
188 .saturating_add(T::DbWeight::get().writes(7 as Weight))
189 }
190 fn set_transfers_enabled_flag() -> Weight {141 fn set_transfers_enabled_flag() -> Weight {
191 (6_376_000 as Weight)142 (6_500_000 as Weight)
192 .saturating_add(T::DbWeight::get().reads(1 as Weight))143 .saturating_add(T::DbWeight::get().reads(1 as Weight))
193 .saturating_add(T::DbWeight::get().writes(1 as Weight))144 .saturating_add(T::DbWeight::get().writes(1 as Weight))
194 }145 }
195 fn approve_nft() -> Weight {146 // Storage: Common CollectionById (r:1 w:1)
196 (169_825_000 as Weight)
197 .saturating_add(T::DbWeight::get().reads(9 as Weight))
198 .saturating_add(T::DbWeight::get().writes(4 as Weight))
199 }
200 fn transfer_from_nft() -> Weight {
201 (197_912_000 as Weight)
202 .saturating_add(T::DbWeight::get().reads(15 as Weight))
203 .saturating_add(T::DbWeight::get().writes(11 as Weight))
204 }
205 fn transfer_from_fungible() -> Weight {
206 (183_789_000 as Weight)
207 .saturating_add(T::DbWeight::get().reads(12 as Weight))
208 .saturating_add(T::DbWeight::get().writes(8 as Weight))
209 }
210 fn transfer_from_refungible() -> Weight {
211 (37_149_000 as Weight)
212 .saturating_add(T::DbWeight::get().reads(11 as Weight))
213 .saturating_add(T::DbWeight::get().writes(8 as Weight))
214 }
215 fn set_offchain_schema(_b: u32, ) -> Weight {147 fn set_offchain_schema(_b: u32, ) -> Weight {
216 (6_435_000 as Weight)148 (6_538_000 as Weight)
217 .saturating_add(T::DbWeight::get().reads(1 as Weight))149 .saturating_add(T::DbWeight::get().reads(1 as Weight))
218 .saturating_add(T::DbWeight::get().writes(1 as Weight))150 .saturating_add(T::DbWeight::get().writes(1 as Weight))
219 }151 }
152 // Storage: Common CollectionById (r:1 w:1)
220 fn set_const_on_chain_schema(_b: u32, ) -> Weight {153 fn set_const_on_chain_schema(_b: u32, ) -> Weight {
221 (6_646_000 as Weight)154 (6_542_000 as Weight)
222 .saturating_add(T::DbWeight::get().reads(1 as Weight))155 .saturating_add(T::DbWeight::get().reads(1 as Weight))
223 .saturating_add(T::DbWeight::get().writes(1 as Weight))156 .saturating_add(T::DbWeight::get().writes(1 as Weight))
224 }157 }
225 fn set_variable_on_chain_schema(_b: u32, ) -> Weight {158 // Storage: Common CollectionById (r:1 w:1)
159 fn set_variable_on_chain_schema(b: u32, ) -> Weight {
226 (6_542_000 as Weight)160 (6_092_000 as Weight)
161 // Standard Error: 0
162 .saturating_add((2_000 as Weight).saturating_mul(b as Weight))
227 .saturating_add(T::DbWeight::get().reads(1 as Weight))163 .saturating_add(T::DbWeight::get().reads(1 as Weight))
228 .saturating_add(T::DbWeight::get().writes(1 as Weight))164 .saturating_add(T::DbWeight::get().writes(1 as Weight))
229 }165 }
230 fn set_variable_meta_data_nft(_b: u32, ) -> Weight {166 // Storage: Common CollectionById (r:1 w:1)
231 (14_697_000 as Weight)
232 .saturating_add(T::DbWeight::get().reads(2 as Weight))
233 .saturating_add(T::DbWeight::get().writes(1 as Weight))
234 }
235 fn set_schema_version() -> Weight {167 fn set_schema_version() -> Weight {
236 (6_566_000 as Weight)168 (6_470_000 as Weight)
237 .saturating_add(T::DbWeight::get().reads(1 as Weight))169 .saturating_add(T::DbWeight::get().reads(1 as Weight))
238 .saturating_add(T::DbWeight::get().writes(1 as Weight))170 .saturating_add(T::DbWeight::get().writes(1 as Weight))
239 }171 }
172 // Storage: Common CollectionById (r:1 w:1)
240 fn set_collection_limits() -> Weight {173 fn set_collection_limits() -> Weight {
241 (6_349_000 as Weight)174 (6_841_000 as Weight)
242 .saturating_add(T::DbWeight::get().reads(1 as Weight))175 .saturating_add(T::DbWeight::get().reads(1 as Weight))
243 .saturating_add(T::DbWeight::get().writes(1 as Weight))176 .saturating_add(T::DbWeight::get().writes(1 as Weight))
244 }177 }
178 // Storage: Common CollectionById (r:1 w:1)
179 fn set_meta_update_permission_flag() -> Weight {
180 (6_278_000 as Weight)
181 .saturating_add(T::DbWeight::get().reads(1 as Weight))
182 .saturating_add(T::DbWeight::get().writes(1 as Weight))
183 }
245}184}
246185
247// For backwards compatibility and tests186// For backwards compatibility and tests
248impl WeightInfo for () {187impl WeightInfo for () {
188 // Storage: Common CreatedCollectionCount (r:1 w:1)
189 // Storage: Common DestroyedCollectionCount (r:1 w:0)
190 // Storage: System Account (r:2 w:2)
191 // Storage: Common CollectionById (r:0 w:1)
249 fn create_collection() -> Weight {192 fn create_collection() -> Weight {
250 (25_851_000 as Weight)193 (23_803_000 as Weight)
251 .saturating_add(RocksDbWeight::get().reads(8 as Weight))194 .saturating_add(RocksDbWeight::get().reads(4 as Weight))
252 .saturating_add(RocksDbWeight::get().writes(6 as Weight))195 .saturating_add(RocksDbWeight::get().writes(4 as Weight))
253 }196 }
197 // Storage: Common CollectionById (r:1 w:1)
198 // Storage: Common DestroyedCollectionCount (r:1 w:1)
199 // Storage: Nonfungible TokensMinted (r:0 w:1)
200 // Storage: Nonfungible TokensBurnt (r:0 w:1)
254 fn destroy_collection() -> Weight {201 fn destroy_collection() -> Weight {
255 (28_737_000 as Weight)202 (27_831_000 as Weight)
256 .saturating_add(RocksDbWeight::get().reads(2 as Weight))203 .saturating_add(RocksDbWeight::get().reads(2 as Weight))
257 .saturating_add(RocksDbWeight::get().writes(4 as Weight))204 .saturating_add(RocksDbWeight::get().writes(4 as Weight))
258 }205 }
206 // Storage: Common CollectionById (r:1 w:0)
207 // Storage: Common Allowlist (r:0 w:1)
259 fn add_to_white_list() -> Weight {208 fn add_to_white_list() -> Weight {
260 (6_237_000 as Weight)209 (6_629_000 as Weight)
261 .saturating_add(RocksDbWeight::get().reads(1 as Weight))210 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
262 .saturating_add(RocksDbWeight::get().writes(1 as Weight))211 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
263 }212 }
213 // Storage: Common CollectionById (r:1 w:0)
214 // Storage: Common Allowlist (r:0 w:1)
264 fn remove_from_white_list() -> Weight {215 fn remove_from_white_list() -> Weight {
265 (6_252_000 as Weight)216 (6_596_000 as Weight)
266 .saturating_add(RocksDbWeight::get().reads(1 as Weight))217 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
267 .saturating_add(RocksDbWeight::get().writes(1 as Weight))218 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
268 }219 }
220 // Storage: Common CollectionById (r:1 w:1)
269 fn set_public_access_mode() -> Weight {221 fn set_public_access_mode() -> Weight {
270 (6_691_000 as Weight)222 (6_338_000 as Weight)
271 .saturating_add(RocksDbWeight::get().reads(1 as Weight))223 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
272 .saturating_add(RocksDbWeight::get().writes(1 as Weight))224 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
273 }225 }
226 // Storage: Common CollectionById (r:1 w:1)
274 fn set_mint_permission() -> Weight {227 fn set_mint_permission() -> Weight {
275 (6_630_000 as Weight)228 (6_383_000 as Weight)
276 .saturating_add(RocksDbWeight::get().reads(1 as Weight))229 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
277 .saturating_add(RocksDbWeight::get().writes(1 as Weight))230 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
278 }231 }
232 // Storage: Common CollectionById (r:1 w:1)
279 fn change_collection_owner() -> Weight {233 fn change_collection_owner() -> Weight {
280 (6_521_000 as Weight)234 (6_493_000 as Weight)
281 .saturating_add(RocksDbWeight::get().reads(1 as Weight))235 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
282 .saturating_add(RocksDbWeight::get().writes(1 as Weight))236 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
283 }237 }
238 // Storage: Common CollectionById (r:1 w:0)
239 // Storage: Common IsAdmin (r:0 w:1)
284 fn add_collection_admin() -> Weight {240 fn add_collection_admin() -> Weight {
285 (8_057_000 as Weight)241 (6_850_000 as Weight)
286 .saturating_add(RocksDbWeight::get().reads(2 as Weight))242 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
287 .saturating_add(RocksDbWeight::get().writes(1 as Weight))243 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
288 }244 }
245 // Storage: Common CollectionById (r:1 w:0)
246 // Storage: Common IsAdmin (r:0 w:1)
289 fn remove_collection_admin() -> Weight {247 fn remove_collection_admin() -> Weight {
290 (8_307_000 as Weight)248 (6_615_000 as Weight)
291 .saturating_add(RocksDbWeight::get().reads(2 as Weight))249 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
292 .saturating_add(RocksDbWeight::get().writes(1 as Weight))250 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
293 }251 }
252 // Storage: Common CollectionById (r:1 w:1)
294 fn set_collection_sponsor() -> Weight {253 fn set_collection_sponsor() -> Weight {
295 (6_484_000 as Weight)254 (6_430_000 as Weight)
296 .saturating_add(RocksDbWeight::get().reads(1 as Weight))255 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
297 .saturating_add(RocksDbWeight::get().writes(1 as Weight))256 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
298 }257 }
258 // Storage: Common CollectionById (r:1 w:1)
299 fn confirm_sponsorship() -> Weight {259 fn confirm_sponsorship() -> Weight {
300 (6_530_000 as Weight)260 (6_125_000 as Weight)
301 .saturating_add(RocksDbWeight::get().reads(1 as Weight))261 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
302 .saturating_add(RocksDbWeight::get().writes(1 as Weight))262 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
303 }263 }
264 // Storage: Common CollectionById (r:1 w:1)
304 fn remove_collection_sponsor() -> Weight {265 fn remove_collection_sponsor() -> Weight {
305 (6_733_000 as Weight)266 (6_236_000 as Weight)
306 .saturating_add(RocksDbWeight::get().reads(1 as Weight))267 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
307 .saturating_add(RocksDbWeight::get().writes(1 as Weight))268 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
308 }269 }
309 fn create_item_nft(b: u32, ) -> Weight {270 // Storage: Common CollectionById (r:1 w:1)
310 (167_180_000 as Weight)
311 // Standard Error: 1_000
312 .saturating_add((10_000 as Weight).saturating_mul(b as Weight))
313 .saturating_add(RocksDbWeight::get().reads(11 as Weight))
314 .saturating_add(RocksDbWeight::get().writes(8 as Weight))
315 }
316 fn create_multiple_items_nft(b: u32, ) -> Weight {
317 (336_830_000 as Weight)
318 // Standard Error: 42_000
319 .saturating_add((11_627_000 as Weight).saturating_mul(b as Weight))
320 .saturating_add(RocksDbWeight::get().reads(11 as Weight))
321 .saturating_add(RocksDbWeight::get().writes(7 as Weight))
322 .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(b as Weight)))
323 }
324 fn create_item_fungible() -> Weight {
325 (24_123_000 as Weight)
326 .saturating_add(RocksDbWeight::get().reads(9 as Weight))
327 .saturating_add(RocksDbWeight::get().writes(4 as Weight))
328 }
329 fn create_multiple_items_fungible(b: u32, ) -> Weight {
330 (13_217_000 as Weight)
331 // Standard Error: 4_000
332 .saturating_add((2_971_000 as Weight).saturating_mul(b as Weight))
333 .saturating_add(RocksDbWeight::get().reads(9 as Weight))
334 .saturating_add(RocksDbWeight::get().writes(4 as Weight))
335 }
336 fn create_item_refungible(_b: u32, ) -> Weight {
337 (26_293_000 as Weight)
338 .saturating_add(RocksDbWeight::get().reads(9 as Weight))
339 .saturating_add(RocksDbWeight::get().writes(7 as Weight))
340 }
341 fn create_multiple_items_refungible(b: u32, ) -> Weight {
342 (0 as Weight)
343 // Standard Error: 16_000
344 .saturating_add((8_374_000 as Weight).saturating_mul(b as Weight))
345 .saturating_add(RocksDbWeight::get().reads(9 as Weight))
346 .saturating_add(RocksDbWeight::get().writes(6 as Weight))
347 .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(b as Weight)))
348 }
349 fn burn_item_nft() -> Weight {
350 (32_237_000 as Weight)
351 .saturating_add(RocksDbWeight::get().reads(9 as Weight))
352 .saturating_add(RocksDbWeight::get().writes(7 as Weight))
353 }
354 fn transfer_nft() -> Weight {
355 (192_578_000 as Weight)
356 .saturating_add(RocksDbWeight::get().reads(14 as Weight))
357 .saturating_add(RocksDbWeight::get().writes(10 as Weight))
358 }
359 fn transfer_fungible() -> Weight {
360 (170_749_000 as Weight)
361 .saturating_add(RocksDbWeight::get().reads(11 as Weight))
362 .saturating_add(RocksDbWeight::get().writes(7 as Weight))
363 }
364 fn transfer_refungible() -> Weight {
365 (35_949_000 as Weight)
366 .saturating_add(RocksDbWeight::get().reads(10 as Weight))
367 .saturating_add(RocksDbWeight::get().writes(7 as Weight))
368 }
369 fn set_transfers_enabled_flag() -> Weight {271 fn set_transfers_enabled_flag() -> Weight {
370 (6_376_000 as Weight)272 (6_500_000 as Weight)
371 .saturating_add(RocksDbWeight::get().reads(1 as Weight))273 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
372 .saturating_add(RocksDbWeight::get().writes(1 as Weight))274 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
373 }275 }
374 fn approve_nft() -> Weight {276 // Storage: Common CollectionById (r:1 w:1)
375 (169_825_000 as Weight)
376 .saturating_add(RocksDbWeight::get().reads(9 as Weight))
377 .saturating_add(RocksDbWeight::get().writes(4 as Weight))
378 }
379 fn transfer_from_nft() -> Weight {
380 (197_912_000 as Weight)
381 .saturating_add(RocksDbWeight::get().reads(15 as Weight))
382 .saturating_add(RocksDbWeight::get().writes(11 as Weight))
383 }
384 fn transfer_from_fungible() -> Weight {
385 (183_789_000 as Weight)
386 .saturating_add(RocksDbWeight::get().reads(12 as Weight))
387 .saturating_add(RocksDbWeight::get().writes(8 as Weight))
388 }
389 fn transfer_from_refungible() -> Weight {
390 (37_149_000 as Weight)
391 .saturating_add(RocksDbWeight::get().reads(11 as Weight))
392 .saturating_add(RocksDbWeight::get().writes(8 as Weight))
393 }
394 fn set_offchain_schema(_b: u32, ) -> Weight {277 fn set_offchain_schema(_b: u32, ) -> Weight {
395 (6_435_000 as Weight)278 (6_538_000 as Weight)
396 .saturating_add(RocksDbWeight::get().reads(1 as Weight))279 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
397 .saturating_add(RocksDbWeight::get().writes(1 as Weight))280 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
398 }281 }
282 // Storage: Common CollectionById (r:1 w:1)
399 fn set_const_on_chain_schema(_b: u32, ) -> Weight {283 fn set_const_on_chain_schema(_b: u32, ) -> Weight {
400 (6_646_000 as Weight)284 (6_542_000 as Weight)
401 .saturating_add(RocksDbWeight::get().reads(1 as Weight))285 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
402 .saturating_add(RocksDbWeight::get().writes(1 as Weight))286 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
403 }287 }
404 fn set_variable_on_chain_schema(_b: u32, ) -> Weight {288 // Storage: Common CollectionById (r:1 w:1)
289 fn set_variable_on_chain_schema(b: u32, ) -> Weight {
405 (6_542_000 as Weight)290 (6_092_000 as Weight)
291 // Standard Error: 0
292 .saturating_add((2_000 as Weight).saturating_mul(b as Weight))
406 .saturating_add(RocksDbWeight::get().reads(1 as Weight))293 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
407 .saturating_add(RocksDbWeight::get().writes(1 as Weight))294 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
408 }295 }
409 fn set_variable_meta_data_nft(_b: u32, ) -> Weight {296 // Storage: Common CollectionById (r:1 w:1)
410 (14_697_000 as Weight)
411 .saturating_add(RocksDbWeight::get().reads(2 as Weight))
412 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
413 }
414 fn set_schema_version() -> Weight {297 fn set_schema_version() -> Weight {
415 (6_566_000 as Weight)298 (6_470_000 as Weight)
416 .saturating_add(RocksDbWeight::get().reads(1 as Weight))299 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
417 .saturating_add(RocksDbWeight::get().writes(1 as Weight))300 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
418 }301 }
302 // Storage: Common CollectionById (r:1 w:1)
419 fn set_collection_limits() -> Weight {303 fn set_collection_limits() -> Weight {
420 (6_349_000 as Weight)304 (6_841_000 as Weight)
305 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
306 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
307 }
308 // Storage: Common CollectionById (r:1 w:1)
309 fn set_meta_update_permission_flag() -> Weight {
310 (6_278_000 as Weight)
421 .saturating_add(RocksDbWeight::get().reads(1 as Weight))311 .saturating_add(RocksDbWeight::get().reads(1 as Weight))
422 .saturating_add(RocksDbWeight::get().writes(1 as Weight))312 .saturating_add(RocksDbWeight::get().writes(1 as Weight))
423 }313 }
addedpallets/nonfungible/Cargo.tomldiffbeforeafterboth

no changes

addedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth

no changes

addedpallets/nonfungible/src/common.rsdiffbeforeafterboth

no changes

addedpallets/nonfungible/src/erc.rsdiffbeforeafterboth

no changes

addedpallets/nonfungible/src/lib.rsdiffbeforeafterboth

no changes

addedpallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterboth

binary blob — no preview

addedpallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth

no changes

addedpallets/nonfungible/src/weights.rsdiffbeforeafterboth

no changes

addedpallets/refungible/Cargo.tomldiffbeforeafterboth

no changes

addedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth

no changes

addedpallets/refungible/src/common.rsdiffbeforeafterboth

no changes

addedpallets/refungible/src/erc.rsdiffbeforeafterboth

no changes

addedpallets/refungible/src/lib.rsdiffbeforeafterboth

no changes

addedpallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterboth

no changes

addedpallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterboth

no changes

addedpallets/refungible/src/weights.rsdiffbeforeafterboth

no changes

modifiedprimitives/nft/src/lib.rsdiffbeforeafterboth
1#![cfg_attr(not(feature = "std"), no_std)]1#![cfg_attr(not(feature = "std"), no_std)]
2
3use core::convert::{TryFrom, TryInto};
24
3#[cfg(feature = "serde")]5#[cfg(feature = "serde")]
4pub use serde::{Serialize, Deserialize};6pub use serde::{Serialize, Deserialize};
57
8use sp_core::U256;
6use sp_runtime::sp_std::prelude::Vec;9use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};
7use codec::{Decode, Encode, MaxEncodedLen};10use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
8pub use frame_support::{11pub use frame_support::{
9 BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,12 BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,
10 dispatch::DispatchResult,13 dispatch::DispatchResult,
67 pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;70 pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;
68}71}
6972
73#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]
74#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
70pub type CollectionId = u32;75pub struct CollectionId(pub u32);
76impl EncodeLike<u32> for CollectionId {}
77impl EncodeLike<CollectionId> for u32 {}
78
79#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]
80#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
71pub type TokenId = u32;81pub struct TokenId(pub u32);
82impl EncodeLike<u32> for TokenId {}
83impl EncodeLike<TokenId> for u32 {}
84
85impl TokenId {
86 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {
87 self.0
88 .checked_add(1)
89 .ok_or(ArithmeticError::Overflow)
90 .map(Self)
91 }
92}
93
94impl From<TokenId> for U256 {
95 fn from(t: TokenId) -> Self {
96 t.0.into()
97 }
98}
99
100impl TryFrom<U256> for TokenId {
101 type Error = &'static str;
102
103 fn try_from(value: U256) -> Result<Self, Self::Error> {
104 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))
105 }
106}
107
108pub struct OverflowError;
109impl From<OverflowError> for &'static str {
110 fn from(_: OverflowError) -> Self {
111 "overflow occured"
112 }
113}
114
72pub type DecimalPoints = u8;115pub type DecimalPoints = u8;
73116
167 pub owner: T::AccountId,210 pub owner: T::AccountId,
168 pub mode: CollectionMode,211 pub mode: CollectionMode,
169 pub access: AccessMode,212 pub access: AccessMode,
170 pub decimal_points: DecimalPoints,
171 pub name: Vec<u16>, // 64 include null escape char213 pub name: Vec<u16>, // 64 include null escape char
172 pub description: Vec<u16>, // 256 include null escape char214 pub description: Vec<u16>, // 256 include null escape char
173 pub token_prefix: Vec<u8>, // 16 include null escape char215 pub token_prefix: Vec<u8>, // 16 include null escape char
207#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]249#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
208#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]250#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
209pub struct CollectionLimits<BlockNumber: Encode + Decode> {251pub struct CollectionLimits<BlockNumber: Encode + Decode> {
210 pub account_token_ownership_limit: u32,252 pub account_token_ownership_limit: Option<u32>,
211 pub sponsored_data_size: u32,253 pub sponsored_data_size: u32,
212 /// None - setVariableMetadata is not sponsored254 /// None - setVariableMetadata is not sponsored
213 /// Some(v) - setVariableMetadata is sponsored255 /// Some(v) - setVariableMetadata is sponsored
221 pub owner_can_destroy: bool,263 pub owner_can_destroy: bool,
222}264}
265
266impl<BlockNumber: Encode + Decode> CollectionLimits<BlockNumber> {
267 pub fn account_token_ownership_limit(&self) -> u32 {
268 self.account_token_ownership_limit
269 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)
270 .min(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)
271 }
272}
223273
224impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {274impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {
225 fn default() -> Self {275 fn default() -> Self {
226 Self {276 Self {
227 account_token_ownership_limit: 10_000_000,277 account_token_ownership_limit: Some(10_000_000),
228 token_limit: u32::max_value(),278 token_limit: u32::max_value(),
229 sponsored_data_size: u32::MAX,279 sponsored_data_size: u32::MAX,
230 sponsored_data_rate_limit: None,280 sponsored_data_rate_limit: None,
addedprimitives/rpc/Cargo.tomldiffbeforeafterboth

no changes

addedprimitives/rpc/src/lib.rsdiffbeforeafterboth

no changes

modifiedruntime/Cargo.tomldiffbeforeafterboth
26 'pallet-evm-migration/runtime-benchmarks',26 'pallet-evm-migration/runtime-benchmarks',
27 'pallet-balances/runtime-benchmarks',27 'pallet-balances/runtime-benchmarks',
28 'pallet-timestamp/runtime-benchmarks',28 'pallet-timestamp/runtime-benchmarks',
29 'pallet-common/runtime-benchmarks',
30 'pallet-fungible/runtime-benchmarks',
31 'pallet-refungible/runtime-benchmarks',
32 'pallet-nonfungible/runtime-benchmarks',
29 'pallet-nft/runtime-benchmarks',33 'pallet-nft/runtime-benchmarks',
30 'pallet-inflation/runtime-benchmarks',34 'pallet-inflation/runtime-benchmarks',
31 'pallet-xcm/runtime-benchmarks',35 'pallet-xcm/runtime-benchmarks',
64 'pallet-evm-coder-substrate/std',68 'pallet-evm-coder-substrate/std',
65 'pallet-ethereum/std',69 'pallet-ethereum/std',
66 'fp-rpc/std',70 'fp-rpc/std',
71 'up-rpc/std',
67 'fp-self-contained/std',72 'fp-self-contained/std',
68 'parachain-info/std',73 'parachain-info/std',
69 'serde',74 'serde',
70 'pallet-inflation/std',75 'pallet-inflation/std',
76 'pallet-common/std',
77 'pallet-fungible/std',
78 'pallet-refungible/std',
79 'pallet-nonfungible/std',
71 'pallet-nft/std',80 'pallet-nft/std',
72 'pallet-unq-scheduler/std',81 'pallet-unq-scheduler/std',
73 'pallet-nft-charge-transaction/std',82 'pallet-nft-charge-transaction/std',
156# [dependencies.pallet-contracts]165# [dependencies.pallet-contracts]
157# git = 'https://github.com/paritytech/substrate.git'166# git = 'https://github.com/paritytech/substrate.git'
158# default-features = false167# default-features = false
159# branch = 'polkadot-v0.9.9'168# branch = 'polkadot-v0.9.12'
160# version = '4.0.0-dev'169# version = '4.0.0-dev'
161170
162# [dependencies.pallet-contracts-primitives]171# [dependencies.pallet-contracts-primitives]
163# git = 'https://github.com/paritytech/substrate.git'172# git = 'https://github.com/paritytech/substrate.git'
164# default-features = false173# default-features = false
165# branch = 'polkadot-v0.9.9'174# branch = 'polkadot-v0.9.12'
166# version = '4.0.0-dev'175# version = '4.0.0-dev'
167176
168# [dependencies.pallet-contracts-rpc-runtime-api]177# [dependencies.pallet-contracts-rpc-runtime-api]
169# git = 'https://github.com/paritytech/substrate.git'178# git = 'https://github.com/paritytech/substrate.git'
170# default-features = false179# default-features = false
171# branch = 'polkadot-v0.9.9'180# branch = 'polkadot-v0.9.12'
172# version = '4.0.0-dev'181# version = '4.0.0-dev'
173182
174[dependencies.pallet-randomness-collective-flip]183[dependencies.pallet-randomness-collective-flip]
369] }
359derivative = "2.2.0"370derivative = "2.2.0"
360pallet-nft = { path = '../pallets/nft', default-features = false, version = '3.0.0' }371pallet-nft = { path = '../pallets/nft', default-features = false, version = '3.0.0' }
372up-rpc = { path = "../primitives/rpc", default-features = false }
361pallet-inflation = { path = '../pallets/inflation', default-features = false, version = '3.0.0' }373pallet-inflation = { path = '../pallets/inflation', default-features = false, version = '3.0.0' }
362nft-data-structs = { path = '../primitives/nft', default-features = false, version = '0.9.0' }374nft-data-structs = { path = '../primitives/nft', default-features = false, version = '0.9.0' }
375pallet-common = { default-features = false, path = "../pallets/common" }
376pallet-fungible = { default-features = false, path = "../pallets/fungible" }
377pallet-refungible = { default-features = false, path = "../pallets/refungible" }
378pallet-nonfungible = { default-features = false, path = "../pallets/nonfungible" }
363pallet-unq-scheduler = { path = '../pallets/scheduler', default-features = false, version = '3.0.0' }379pallet-unq-scheduler = { path = '../pallets/scheduler', default-features = false, version = '3.0.0' }
364# pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }380# pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
365pallet-nft-transaction-payment = { path = '../pallets/nft-transaction-payment', default-features = false, version = '3.0.0' }381pallet-nft-transaction-payment = { path = '../pallets/nft-transaction-payment', default-features = false, version = '3.0.0' }
modifiedruntime/src/lib.rsdiffbeforeafterboth
103/// to the public key of our transaction signing scheme.103/// to the public key of our transaction signing scheme.
104pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;104pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
105
106pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;
105107
106/// The type for looking up accounts. We don't expect more than 4 billion of them, but you108/// The type for looking up accounts. We don't expect more than 4 billion of them, but you
107/// never know...109/// never know...
717 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;719 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;
718}720}
719721
720/// Used for the pallet nft in `./nft.rs`
721impl pallet_nft::Config for Runtime {722impl pallet_common::Config for Runtime {
722 type Event = Event;723 type Event = Event;
723 type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;
724
725 type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;724 type EvmBackwardsAddressMapping = pallet_common::account::MapBackwardsAddressTruncated;
726 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;725 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;
727 type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;726 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;
728727
729 type Currency = Balances;728 type Currency = Balances;
730 type CollectionCreationPrice = CollectionCreationPrice;729 type CollectionCreationPrice = CollectionCreationPrice;
731 type TreasuryAccountId = TreasuryAccountId;730 type TreasuryAccountId = TreasuryAccountId;
732}731}
732
733impl pallet_fungible::Config for Runtime {
734 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;
735}
736impl pallet_refungible::Config for Runtime {
737 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;
738}
739impl pallet_nonfungible::Config for Runtime {
740 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;
741}
742
743/// Used for the pallet nft in `./nft.rs`
744impl pallet_nft::Config for Runtime {
745 type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;
746}
733747
734parameter_types! {748parameter_types! {
735 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied749 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied
836850
837 // Unique Pallets851 // Unique Pallets
838 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,852 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
839 Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>} = 61,853 Nft: pallet_nft::{Pallet, Call, Storage} = 61,
840 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,854 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
841 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,855 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,
842 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,856 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,
843 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,857 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
858 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,
859 Fungible: pallet_fungible::{Pallet, Storage} = 67,
860 Refungible: pallet_refungible::{Pallet, Storage} = 68,
861 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,
844862
845 // Frontier863 // Frontier
846 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,864 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,
965 }983 }
966}984}
967985
986macro_rules! dispatch_nft_runtime {
987 ($collection:ident.$method:ident($($name:ident),*)) => {{
988 use pallet_nft::dispatch::Dispatched;
989
990 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());
991 let dispatch = collection.as_dyn();
992
993 dispatch.$method($($name),*)
994 }};
995}
968impl_runtime_apis! {996impl_runtime_apis! {
969 impl pallet_nft::NftApi<Block>997 impl up_rpc::NftApi<Block, CrossAccountId, AccountId>
970 for Runtime998 for Runtime
971 {999 {
1000 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {
1001 dispatch_nft_runtime!(collection.account_tokens(account))
1002 }
1003 fn token_exists(collection: CollectionId, token: TokenId) -> bool {
1004 dispatch_nft_runtime!(collection.token_exists(token))
1005 }
1006
1007 fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {
1008 dispatch_nft_runtime!(collection.token_owner(token))
1009 }
1010 fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {
1011 dispatch_nft_runtime!(collection.const_metadata(token))
1012 }
1013 fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {
1014 dispatch_nft_runtime!(collection.variable_metadata(token))
1015 }
1016
1017 fn collection_tokens(collection: CollectionId) -> u32 {
1018 dispatch_nft_runtime!(collection.collection_tokens())
1019 }
1020 fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {
1021 dispatch_nft_runtime!(collection.account_balance(account))
1022 }
1023 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {
1024 dispatch_nft_runtime!(collection.balance(account, token))
1025 }
1026 fn allowance(
1027 collection: CollectionId,
1028 sender: CrossAccountId,
1029 spender: CrossAccountId,
1030 token: TokenId,
1031 ) -> u128 {
1032 dispatch_nft_runtime!(collection.allowance(sender, spender, token))
1033 }
1034
972 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1035 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {
973 <pallet_nft::NftErcSupport<Runtime>>::get_code(&account).or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account)).or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1036 <pallet_nft::NftErcSupport<Runtime>>::get_code(&account).or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account)).or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))
974 }1037 }
1038 fn adminlist(collection: CollectionId) -> Vec<AccountId> {
1039 <pallet_nft::Pallet<Runtime>>::adminlist(collection)
1040 }
1041 fn allowlist(collection: CollectionId) -> Vec<AccountId> {
1042 <pallet_nft::Pallet<Runtime>>::allowlist(collection)
1043 }
1044 fn last_token_id(collection: CollectionId) -> TokenId {
1045 dispatch_nft_runtime!(collection.last_token_id())
1046 }
975 }1047 }
9761048
977 impl sp_api::Core<Block> for Runtime {1049 impl sp_api::Core<Block> for Runtime {
12381310
1239 #[cfg(feature = "runtime-benchmarks")]1311 #[cfg(feature = "runtime-benchmarks")]
1240 impl frame_benchmarking::Benchmark<Block> for Runtime {1312 impl frame_benchmarking::Benchmark<Block> for Runtime {
1313 fn benchmark_metadata(extra: bool) -> (
1314 Vec<frame_benchmarking::BenchmarkList>,
1315 Vec<frame_support::traits::StorageInfo>,
1316 ) {
1317 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};
1318 use frame_support::traits::StorageInfoTrait;
1319
1320 let mut list = Vec::<BenchmarkList>::new();
1321
1322 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);
1323 list_benchmark!(list, extra, pallet_nft, Nft);
1324 list_benchmark!(list, extra, pallet_inflation, Inflation);
1325 list_benchmark!(list, extra, pallet_fungible, Fungible);
1326 list_benchmark!(list, extra, pallet_refungible, Refungible);
1327 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);
1328
1329 let storage_info = AllPalletsWithSystem::storage_info();
1330
1331 return (list, storage_info)
1332 }
1333
1241 fn dispatch_benchmark(1334 fn dispatch_benchmark(
1242 config: frame_benchmarking::BenchmarkConfig1335 config: frame_benchmarking::BenchmarkConfig
1243 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1336 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
1244 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};1337 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};
12451338
1246 let whitelist: Vec<TrackedStorageKey> = vec![1339 let whitelist: Vec<TrackedStorageKey> = vec![
1247 // Alice account1340 // Block Number
1248 hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),1341 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
1249 // // Total Issuance1342 // Total Issuance
1250 // hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1343 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),
1251 // // Execution Phase1344 // Execution Phase
1252 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1345 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),
1253 // // Event Count1346 // Event Count
1254 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1347 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),
1255 // // System Events1348 // System Events
1256 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1349 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
1257 ];1350 ];
12581351
1259 let mut batches = Vec::<BenchmarkBatch>::new();1352 let mut batches = Vec::<BenchmarkBatch>::new();
1262 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1355 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);
1263 add_benchmark!(params, batches, pallet_nft, Nft);1356 add_benchmark!(params, batches, pallet_nft, Nft);
1264 add_benchmark!(params, batches, pallet_inflation, Inflation);1357 add_benchmark!(params, batches, pallet_inflation, Inflation);
1358 add_benchmark!(params, batches, pallet_fungible, Fungible);
1359 add_benchmark!(params, batches, pallet_refungible, Refungible);
1360 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);
12651361
1266 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1362 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1267 Ok(batches)1363 Ok(batches)
modifiedtests/src/eth/api/ContractHelpers.soldiffbeforeafterboth
88
9}9}
10
11interface ERC165 is Dummy {
12 function supportsInterface(bytes4 interfaceID) external view returns (bool);
13}
1014
11interface ContractHelpers is Dummy {15interface ContractHelpers is Dummy, ERC165 {
12 // Selector: contractOwner(address) 5152b14c16 // Selector: contractOwner(address) 5152b14c
13 function contractOwner(address contractAddress)17 function contractOwner(address contractAddress)
14 external18 external
modifiedtests/src/eth/api/UniqueFungible.soldiffbeforeafterboth
88
9}9}
10
11interface ERC165 is Dummy {
12 function supportsInterface(bytes4 interfaceID) external view returns (bool);
13}
1014
11// Inline15// Inline
12interface ERC20Events {16interface ERC20Events {
18 );22 );
19}23}
20
21// Inline
22interface InlineNameSymbol is Dummy {
23 // Selector: name() 06fdde03
24 function name() external view returns (string memory);
25
26 // Selector: symbol() 95d89b41
27 function symbol() external view returns (string memory);
28}
29
30// Inline
31interface InlineTotalSupply is Dummy {
32 // Selector: totalSupply() 18160ddd
33 function totalSupply() external view returns (uint256);
34}
35
36interface ERC165 is Dummy {
37 // Selector: supportsInterface(bytes4) 01ffc9a7
38 function supportsInterface(uint32 interfaceId) external view returns (bool);
39}
4024
41interface ERC20 is Dummy, InlineNameSymbol, InlineTotalSupply, ERC20Events {25interface ERC20 is Dummy, ERC165, ERC20Events {
26 // Selector: name() 06fdde03
27 function name() external view returns (string memory);
28
29 // Selector: symbol() 95d89b41
30 function symbol() external view returns (string memory);
31
32 // Selector: totalSupply() 18160ddd
33 function totalSupply() external view returns (uint256);
34
42 // Selector: decimals() 313ce56735 // Selector: decimals() 313ce567
43 function decimals() external view returns (uint8);36 function decimals() external view returns (uint8);
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
1414
15}15}
16
17interface ERC165 is Dummy {
18 function supportsInterface(bytes4 interfaceID) external view returns (bool);
19}
1620
17// Inline21// Inline
18interface ERC721Events {22interface ERC721Events {
38 event MintingFinished();42 event MintingFinished();
39}43}
40
41// Inline
42interface InlineNameSymbol is Dummy {
43 // Selector: name() 06fdde03
44 function name() external view returns (string memory);
45
46 // Selector: symbol() 95d89b41
47 function symbol() external view returns (string memory);
48}
49
50// Inline
51interface InlineTotalSupply is Dummy {
52 // Selector: totalSupply() 18160ddd
53 function totalSupply() external view returns (uint256);
54}
55
56interface ERC165 is Dummy {
57 // Selector: supportsInterface(bytes4) 01ffc9a7
58 function supportsInterface(uint32 interfaceId) external view returns (bool);
59}
6044
61interface ERC721 is Dummy, ERC165, ERC721Events {45interface ERC721 is Dummy, ERC165, ERC721Events {
62 // Selector: balanceOf(address) 70a0823146 // Selector: balanceOf(address) 70a08231
103 returns (address);87 returns (address);
104}88}
10589
106interface ERC721Burnable is Dummy {90interface ERC721Burnable is Dummy, ERC165 {
107 // Selector: burn(uint256) 42966c6891 // Selector: burn(uint256) 42966c68
108 function burn(uint256 tokenId) external;92 function burn(uint256 tokenId) external;
109}93}
11094
111interface ERC721Enumerable is Dummy, InlineTotalSupply {95interface ERC721Enumerable is Dummy, ERC165 {
112 // Selector: tokenByIndex(uint256) 4f6ccce796 // Selector: tokenByIndex(uint256) 4f6ccce7
113 function tokenByIndex(uint256 index) external view returns (uint256);97 function tokenByIndex(uint256 index) external view returns (uint256);
11498
118 view102 view
119 returns (uint256);103 returns (uint256);
104
105 // Selector: totalSupply() 18160ddd
106 function totalSupply() external view returns (uint256);
120}107}
121108
122interface ERC721Metadata is Dummy, InlineNameSymbol {109interface ERC721Metadata is Dummy, ERC165 {
110 // Selector: name() 06fdde03
111 function name() external view returns (string memory);
112
113 // Selector: symbol() 95d89b41
114 function symbol() external view returns (string memory);
115
123 // Selector: tokenURI(uint256) c87b56dd116 // Selector: tokenURI(uint256) c87b56dd
124 function tokenURI(uint256 tokenId) external view returns (string memory);117 function tokenURI(uint256 tokenId) external view returns (string memory);
125}118}
126119
127interface ERC721Mintable is Dummy, ERC721MintableEvents {120interface ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
128 // Selector: mintingFinished() 05d2035b121 // Selector: mintingFinished() 05d2035b
129 function mintingFinished() external view returns (bool);122 function mintingFinished() external view returns (bool);
130123
142 function finishMinting() external returns (bool);135 function finishMinting() external returns (bool);
143}136}
144137
145interface ERC721UniqueExtensions is Dummy {138interface ERC721UniqueExtensions is Dummy, ERC165 {
146 // Selector: transfer(address,uint256) a9059cbb139 // Selector: transfer(address,uint256) a9059cbb
147 function transfer(address to, uint256 tokenId) external;140 function transfer(address to, uint256 tokenId) external;
141
142 // Selector: burnFrom(address,uint256) 79cc6790
143 function burnFrom(address from, uint256 tokenId) external;
148144
149 // Selector: nextTokenId() 75794a3c145 // Selector: nextTokenId() 75794a3c
150 function nextTokenId() external view returns (uint256);146 function nextTokenId() external view returns (uint256);
addedtests/src/substrate/rpc_defs.jsondiffbeforeafterboth

no changes