difftreelog
Merge pull request #208 from UniqueNetwork/feature/split-collection-pallets
in: master
Split collection pallets
71 files changed
.maintain/frame-weight-template.hbsdiffbeforeafterboth--- a/.maintain/frame-weight-template.hbs
+++ b/.maintain/frame-weight-template.hbs
@@ -92,4 +92,4 @@
{{~/each}}
}
{{~/each}}
-}
\ No newline at end of file
+}
.maintain/scripts/compile_stub.shdiffbeforeafterboth--- a/.maintain/scripts/compile_stub.sh
+++ b/.maintain/scripts/compile_stub.sh
@@ -6,9 +6,9 @@
tmp=$(mktemp -d)
cd $tmp
cp $dir/$INPUT input.sol
-solcjs --optimize --bin input.sol
+solcjs --optimize --bin input.sol -o $PWD
mv input_sol_$(basename $OUTPUT .raw).bin out.bin
xxd -r -p out.bin out.raw
-mv out.raw $dir/$OUTPUT
\ No newline at end of file
+mv out.raw $dir/$OUTPUT
.maintain/scripts/generate_api.shdiffbeforeafterboth--- a/.maintain/scripts/generate_api.sh
+++ b/.maintain/scripts/generate_api.sh
@@ -9,4 +9,4 @@
prettier --use-tabs $raw > $formatted
solhint --fix $formatted
-mv $formatted $OUTPUT
\ No newline at end of file
+mv $formatted $OUTPUT
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,6 +3,7 @@
members = [
'node/*',
'pallets/*',
+ 'client/*',
'primitives/*',
'runtime',
'crates/*',
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -8,25 +8,26 @@
.PHONY: regenerate_solidity
regenerate_solidity:
- PACKAGE=pallet-nft NAME=eth::erc::fungible_iface OUTPUT=./tests/src/eth/api/UniqueFungible.sol ./.maintain/scripts/generate_api.sh
- PACKAGE=pallet-nft NAME=eth::erc::nft_iface OUTPUT=./tests/src/eth/api/UniqueNFT.sol ./.maintain/scripts/generate_api.sh
+ PACKAGE=pallet-fungible NAME=erc::gen_iface OUTPUT=./tests/src/eth/api/UniqueFungible.sol ./.maintain/scripts/generate_api.sh
+ PACKAGE=pallet-nonfungible NAME=erc::gen_iface OUTPUT=./tests/src/eth/api/UniqueNFT.sol ./.maintain/scripts/generate_api.sh
PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_iface OUTPUT=./tests/src/eth/api/ContractHelpers.sol ./.maintain/scripts/generate_api.sh
- PACKAGE=pallet-nft NAME=eth::erc::fungible_impl OUTPUT=./pallets/nft/src/eth/stubs/UniqueFungible.sol ./.maintain/scripts/generate_api.sh
- PACKAGE=pallet-nft NAME=eth::erc::nft_impl OUTPUT=./pallets/nft/src/eth/stubs/UniqueNFT.sol ./.maintain/scripts/generate_api.sh
+ PACKAGE=pallet-fungible NAME=erc::gen_impl OUTPUT=./pallets/fungible/src/stubs/UniqueFungible.sol ./.maintain/scripts/generate_api.sh
+ PACKAGE=pallet-nonfungible NAME=erc::gen_impl OUTPUT=./pallets/nonfungible/src/stubs/UniqueNFT.sol ./.maintain/scripts/generate_api.sh
PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_impl OUTPUT=./pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol ./.maintain/scripts/generate_api.sh
-NFT_EVM_STUBS=./pallets/nft/src/eth/stubs
+FUNGIBLE_EVM_STUBS=./pallets/fungible/src/stubs
+NONFUNGIBLE_EVM_STUBS=./pallets/nonfungible/src/stubs
CONTRACT_HELPERS_STUBS=./pallets/evm-contract-helpers/src/stubs/
-$(NFT_EVM_STUBS)/UniqueFungible.raw: $(NFT_EVM_STUBS)/UniqueFungible.sol
+$(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw: $(FUNGIBLE_EVM_STUBS)/UniqueFungible.sol
INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh
-$(NFT_EVM_STUBS)/UniqueNFT.raw: $(NFT_EVM_STUBS)/UniqueNFT.sol
+$(NONFUNGIBLE_EVM_STUBS)/UniqueNFT.raw: $(NONFUNGIBLE_EVM_STUBS)/UniqueNFT.sol
INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh
$(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw: $(CONTRACT_HELPERS_STUBS)/ContractHelpers.sol
INPUT=$< OUTPUT=$@ ./.maintain/scripts/compile_stub.sh
-evm_stubs: $(NFT_EVM_STUBS)/UniqueFungible.raw $(NFT_EVM_STUBS)/UniqueNFT.raw $(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw
+evm_stubs: $(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw $(NONFUNGIBLE_EVM_STUBS)/UniqueNFT.raw $(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw
.PHONY: _bench
_bench:
@@ -44,5 +45,17 @@
bench-nft:
make _bench PALLET=nft
+.PHONY: bench-fungible
+bench-fungible:
+ make _bench PALLET=fungible
+
+.PHONY: bench-refungible
+bench-refungible:
+ make _bench PALLET=refungible
+
+.PHONY: bench-nonfungible
+bench-nonfungible:
+ make _bench PALLET=nonfungible
+
.PHONY: bench
-bench: bench-evm-migration bench-nft
+bench: bench-evm-migration bench-nft bench-fungible bench-refungible bench-nonfungible
client/rpc/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/client/rpc/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "uc-rpc"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+pallet-common = { default-features = false, path = '../../pallets/common' }
+nft-data-structs = { default-features = false, path = '../../primitives/nft' }
+up-rpc = { path = "../../primitives/rpc" }
+codec = { package = "parity-scale-codec", version = "2.0.0" }
+jsonrpc-core = "18.0.0"
+jsonrpc-core-client = "18.0.0"
+jsonrpc-derive = "18.0.0"
+
+sp-api = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.12" }
+sp-blockchain = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.12" }
+sp-core = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.12" }
+sp-rpc = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.12" }
+sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.12" }
client/rpc/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/client/rpc/src/lib.rs
@@ -0,0 +1,156 @@
+use std::sync::Arc;
+
+use codec::Decode;
+use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
+use jsonrpc_derive::rpc;
+use nft_data_structs::{CollectionId, TokenId};
+use sp_api::{BlockId, BlockT, ProvideRuntimeApi};
+use sp_blockchain::HeaderBackend;
+use up_rpc::NftApi as NftRuntimeApi;
+
+#[rpc]
+pub trait NftApi<BlockHash, CrossAccountId, AccountId> {
+ #[rpc(name = "nft_accountTokens")]
+ fn account_tokens(
+ &self,
+ collection: CollectionId,
+ account: CrossAccountId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<TokenId>>;
+ #[rpc(name = "nft_tokenExists")]
+ fn token_exists(
+ &self,
+ collection: CollectionId,
+ token: TokenId,
+ at: Option<BlockHash>,
+ ) -> Result<bool>;
+
+ #[rpc(name = "nft_tokenOwner")]
+ fn token_owner(
+ &self,
+ collection: CollectionId,
+ token: TokenId,
+ at: Option<BlockHash>,
+ ) -> Result<CrossAccountId>;
+ #[rpc(name = "nft_constMetadata")]
+ fn const_metadata(
+ &self,
+ collection: CollectionId,
+ token: TokenId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<u8>>;
+ #[rpc(name = "nft_variableMetadata")]
+ fn variable_metadata(
+ &self,
+ collection: CollectionId,
+ token: TokenId,
+ at: Option<BlockHash>,
+ ) -> Result<Vec<u8>>;
+
+ #[rpc(name = "nft_collectionTokens")]
+ fn collection_tokens(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<u32>;
+ #[rpc(name = "nft_accountBalance")]
+ fn account_balance(
+ &self,
+ collection: CollectionId,
+ account: CrossAccountId,
+ at: Option<BlockHash>,
+ ) -> Result<u32>;
+ #[rpc(name = "nft_balance")]
+ fn balance(
+ &self,
+ collection: CollectionId,
+ account: CrossAccountId,
+ token: TokenId,
+ at: Option<BlockHash>,
+ ) -> Result<String>;
+ #[rpc(name = "nft_allowance")]
+ fn allowance(
+ &self,
+ collection: CollectionId,
+ sender: CrossAccountId,
+ spender: CrossAccountId,
+ token: TokenId,
+ at: Option<BlockHash>,
+ ) -> Result<String>;
+
+ #[rpc(name = "nft_adminlist")]
+ fn adminlist(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<Vec<AccountId>>;
+ #[rpc(name = "nft_allowlist")]
+ fn allowlist(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<Vec<AccountId>>;
+ #[rpc(name = "nft_lastTokenId")]
+ fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;
+}
+
+pub struct Nft<C, P> {
+ client: Arc<C>,
+ _marker: std::marker::PhantomData<P>,
+}
+
+impl<C, P> Nft<C, P> {
+ pub fn new(client: Arc<C>) -> Self {
+ Self {
+ client,
+ _marker: Default::default(),
+ }
+ }
+}
+
+pub enum Error {
+ RuntimeError,
+}
+
+impl From<Error> for i64 {
+ fn from(e: Error) -> i64 {
+ match e {
+ Error::RuntimeError => 1,
+ }
+ }
+}
+
+macro_rules! pass_method {
+ ($method_name:ident($($name:ident: $ty:ty),* $(,)?) -> $result:ty $(=> $mapper:expr)?) => {
+ fn $method_name(
+ &self,
+ $(
+ $name: $ty,
+ )*
+ at: Option<<Block as BlockT>::Hash>,
+ ) -> Result<$result> {
+ let api = self.client.runtime_api();
+ let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));
+
+ api.$method_name(&at, $($name),*).map_err(|e| RpcError {
+ code: ErrorCode::ServerError(Error::RuntimeError.into()),
+ message: "Unable to query".into(),
+ data: Some(format!("{:?}", e).into()),
+ }) $(
+ .map($mapper)
+ )?
+ }
+ };
+}
+
+impl<C, Block, CrossAccountId, AccountId> NftApi<<Block as BlockT>::Hash, CrossAccountId, AccountId>
+ for Nft<C, Block>
+where
+ Block: BlockT,
+ AccountId: Decode,
+ C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
+ C::Api: NftRuntimeApi<Block, CrossAccountId, AccountId>,
+ CrossAccountId: pallet_common::account::CrossAccountId<AccountId>,
+{
+ pass_method!(account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>);
+ pass_method!(token_exists(collection: CollectionId, token: TokenId) -> bool);
+ pass_method!(token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId);
+ pass_method!(const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);
+ pass_method!(variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);
+ pass_method!(collection_tokens(collection: CollectionId) -> u32);
+ pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32);
+ pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string());
+ pass_method!(allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string());
+
+ pass_method!(adminlist(collection: CollectionId) -> Vec<AccountId>);
+ pass_method!(allowlist(collection: CollectionId) -> Vec<AccountId>);
+ pass_method!(last_token_id(collection: CollectionId) -> TokenId);
+}
crates/evm-coder-macros/src/solidity_interface.rsdiffbeforeafterboth--- a/crates/evm-coder-macros/src/solidity_interface.rs
+++ b/crates/evm-coder-macros/src/solidity_interface.rs
@@ -672,6 +672,7 @@
quote! {
#[derive(Debug)]
pub enum #call_name {
+ ERC165Call(::evm_coder::ERC165Call),
#(
#calls,
)*
@@ -691,6 +692,7 @@
}
pub fn supports_interface(interface_id: u32) -> bool {
interface_id != 0xffffff && (
+ interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||
interface_id == Self::interface_id()
#(
|| #supports_interface
@@ -702,7 +704,7 @@
use core::fmt::Write;
let interface = SolidityInterface {
name: #solidity_name,
- is: &["Dummy", #(
+ is: &["Dummy", "ERC165", #(
#solidity_is,
)* #(
#solidity_events_is,
@@ -712,9 +714,9 @@
)*),
};
if is_impl {
- tc.collect("// Common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\n".into());
+ 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());
} else {
- tc.collect("// Common stubs holder\ninterface Dummy {\n}\n".into());
+ tc.collect("// Common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());
}
#(
#solidity_generators
@@ -737,6 +739,7 @@
fn parse(method_id: u32, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {
use ::evm_coder::abi::AbiRead;
match method_id {
+ ::evm_coder::ERC165Call::INTERFACE_ID => return Ok(::evm_coder::ERC165Call::parse(method_id, reader)?.map(Self::ERC165Call)),
#(
#parsers,
)*
@@ -757,6 +760,11 @@
#(
#call_variants,
)*
+ InternalCall::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}) => {
+ let mut writer = ::evm_coder::abi::AbiWriter::default();
+ writer.bool(&InternalCall::supports_interface(interface_id));
+ return Ok(writer);
+ }
_ => {},
}
let mut writer = ::evm_coder::abi::AbiWriter::default();
crates/evm-coder/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -2,7 +2,7 @@
#[cfg(not(feature = "std"))]
extern crate alloc;
-use abi::{AbiReader, AbiWriter};
+use abi::{AbiRead, AbiReader, AbiWriter};
pub use evm_coder_macros::{event_topic, fn_selector, solidity_interface, solidity, ToLog};
pub mod abi;
pub mod events;
@@ -61,6 +61,29 @@
fn call(&mut self, call: types::Msg<C>) -> execution::Result<AbiWriter>;
}
+/// Implementation is implicitly provided for all interfaces
+///
+/// Note: no Callable implementation is provided
+#[derive(Debug)]
+pub enum ERC165Call {
+ SupportsInterface { interface_id: types::bytes4 },
+}
+
+impl ERC165Call {
+ pub const INTERFACE_ID: types::bytes4 = 0x01ffc9a7;
+}
+
+impl Call for ERC165Call {
+ fn parse(selector: u32, input: &mut AbiReader) -> execution::Result<Option<Self>> {
+ if selector != Self::INTERFACE_ID {
+ return Ok(None);
+ }
+ Ok(Some(Self::SupportsInterface {
+ interface_id: input.abi_read()?,
+ }))
+ }
+}
+
#[macro_export]
macro_rules! generate_stubgen {
($name:ident, $decl:ident, $is_impl:literal) => {
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -5,7 +5,6 @@
use cumulus_primitives_core::ParaId;
use nft_runtime::*;
-use nft_data_structs::*;
use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};
use sc_service::ChainType;
use sp_core::{sr25519, Pair, Public};
@@ -168,34 +167,6 @@
treasury: Default::default(),
sudo: SudoConfig { key: root_key },
vesting: VestingConfig { vesting: vec![] },
- nft: NftConfig {
- collection_id: vec![(
- 1,
- Collection {
- owner: get_account_id_from_seed::<sr25519::Public>("Alice"),
- mode: CollectionMode::NFT,
- access: AccessMode::Normal,
- decimal_points: 0,
- name: vec![],
- description: vec![],
- token_prefix: vec![],
- mint_mode: false,
- offchain_schema: vec![],
- schema_version: SchemaVersion::default(),
- sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<
- sr25519::Public,
- >("Alice")),
- const_on_chain_schema: vec![],
- variable_on_chain_schema: vec![],
- limits: CollectionLimits::default(),
- meta_update_permission: MetaUpdatePermission::ItemOwner,
- transfers_enabled: true,
- },
- )],
- nft_item_id: vec![],
- fungible_item_id: vec![],
- refungible_item_id: vec![],
- },
parachain_info: nft_runtime::ParachainInfoConfig { parachain_id: id },
aura: nft_runtime::AuraConfig {
authorities: initial_authorities,
node/rpc/Cargo.tomldiffbeforeafterboth--- a/node/rpc/Cargo.toml
+++ b/node/rpc/Cargo.toml
@@ -49,6 +49,8 @@
fc-mapping-sync = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
pallet-nft = { path = "../../pallets/nft" }
+uc-rpc = { path = "../../client/rpc" }
+up-rpc = { path = "../../primitives/rpc" }
nft-runtime = { path = "../../runtime" }
[features]
node/rpc/src/lib.rsdiffbeforeafterboth--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -1,4 +1,4 @@
-use nft_runtime::{Hash, AccountId, Index, opaque::Block, BlockNumber, Balance};
+use nft_runtime::{Hash, AccountId, CrossAccountId, Index, opaque::Block, BlockNumber, Balance};
use fc_rpc::{
EthBlockDataCache, OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override, StorageOverride,
};
@@ -9,7 +9,6 @@
backend::{AuxStore, StorageProvider},
client::BlockchainEvents,
};
-use pallet_nft::NftApi;
use sc_finality_grandpa::{
FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState,
};
@@ -101,9 +100,10 @@
where
Block: sp_api::BlockT,
C: ProvideRuntimeApi<Block>,
- C::Api: pallet_nft::NftApi<Block>,
+ C::Api: up_rpc::NftApi<Block, CrossAccountId, AccountId>,
{
fn code(&self, block: &sp_api::BlockId<Block>, account: sp_core::H160) -> Option<Vec<u8>> {
+ use up_rpc::NftApi;
self.client
.runtime_api()
.eth_contract_code(block, account)
@@ -127,7 +127,7 @@
// C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,
C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,
- C::Api: pallet_nft::NftApi<Block>,
+ C::Api: up_rpc::NftApi<Block, CrossAccountId, AccountId>,
B: sc_client_api::Backend<Block> + Send + Sync + 'static,
B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,
SC: SelectChain<Block> + 'static,
@@ -139,6 +139,7 @@
EthPubSubApiServer, EthSigner, HexEncodedIdProvider, NetApi, NetApiServer, Web3Api,
Web3ApiServer,
};
+ use uc_rpc::{NftApi, Nft};
// use pallet_contracts_rpc::{Contracts, ContractsApi};
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};
use substrate_frame_rpc_system::{FullSystem, SystemApi};
@@ -203,6 +204,7 @@
max_past_logs,
block_data_cache.clone(),
)));
+ io.extend_with(NftApi::to_delegate(Nft::new(client.clone())));
if let Some(filter_pool) = filter_pool {
io.extend_with(EthFilterApiServer::to_delegate(EthFilterApi::new(
pallets/common/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/pallets/common/Cargo.toml
@@ -0,0 +1,38 @@
+[package]
+name = "pallet-common"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies.codec]
+default-features = false
+features = ['derive']
+package = 'parity-scale-codec'
+version = '2.0.0'
+
+[dependencies]
+frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+nft-data-structs = { default-features = false, path = '../../primitives/nft' }
+pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
+evm-coder = { default-features = false, path = '../../crates/evm-coder' }
+
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
+serde = { version = "1.0.130", default-features = false }
+scale-info = { version = "1.0.0", default-features = false, features = [
+ "derive",
+] }
+
+[features]
+default = ["std"]
+std = [
+ "frame-support/std",
+ "frame-system/std",
+ "sp-runtime/std",
+ "sp-std/std",
+ "nft-data-structs/std",
+ "pallet-evm/std",
+]
+runtime-benchmarks = []
pallets/common/src/account.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/common/src/account.rs
@@ -0,0 +1,192 @@
+use crate::Config;
+use codec::{Encode, EncodeLike, Decode};
+use sp_core::H160;
+use scale_info::{Type, TypeInfo};
+use sp_core::crypto::AccountId32;
+use core::cmp::Ordering;
+use serde::{Serialize, Deserialize};
+use pallet_evm::AddressMapping;
+use sp_std::vec::Vec;
+use sp_std::clone::Clone;
+
+pub trait CrossAccountId<AccountId>:
+ Encode + EncodeLike + Decode + TypeInfo + Clone + PartialEq + Ord + core::fmt::Debug + Default
+// +
+// Serialize + Deserialize<'static>
+{
+ fn as_sub(&self) -> &AccountId;
+ fn as_eth(&self) -> &H160;
+
+ fn from_sub(account: AccountId) -> Self;
+ fn from_eth(account: H160) -> Self;
+}
+
+#[derive(Encode, Decode, Serialize, Deserialize, TypeInfo)]
+#[serde(rename_all = "camelCase")]
+enum BasicCrossAccountIdRepr<AccountId> {
+ Substrate(AccountId),
+ Ethereum(H160),
+}
+
+#[derive(Eq)]
+pub struct BasicCrossAccountId<T: Config> {
+ /// If true - then ethereum is canonical encoding
+ from_ethereum: bool,
+ substrate: T::AccountId,
+ ethereum: H160,
+}
+
+impl<T: Config> TypeInfo for BasicCrossAccountId<T> {
+ type Identity = Self;
+
+ fn type_info() -> Type {
+ <BasicCrossAccountIdRepr<T::AccountId>>::type_info()
+ }
+}
+
+impl<T: Config> Default for BasicCrossAccountId<T> {
+ fn default() -> Self {
+ Self::from_sub(T::AccountId::default())
+ }
+}
+
+impl<T: Config> core::fmt::Debug for BasicCrossAccountId<T> {
+ fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
+ if self.from_ethereum {
+ fmt.debug_tuple("CrossAccountId::Ethereum")
+ .field(&self.ethereum)
+ .finish()
+ } else {
+ fmt.debug_tuple("CrossAccountId::Substrate")
+ .field(&self.substrate)
+ .finish()
+ }
+ }
+}
+
+impl<T: Config> PartialOrd for BasicCrossAccountId<T> {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(self.substrate.cmp(&other.substrate))
+ }
+}
+
+impl<T: Config> Ord for BasicCrossAccountId<T> {
+ fn cmp(&self, other: &Self) -> Ordering {
+ self.partial_cmp(other)
+ .expect("substrate account is total ordered")
+ }
+}
+
+impl<T: Config> PartialEq for BasicCrossAccountId<T> {
+ fn eq(&self, other: &Self) -> bool {
+ if self.from_ethereum == other.from_ethereum {
+ self.substrate == other.substrate && self.ethereum == other.ethereum
+ } else if self.from_ethereum {
+ // ethereum is canonical encoding, but we need to compare derived address
+ self.substrate == other.substrate
+ } else {
+ self.ethereum == other.ethereum
+ }
+ }
+}
+impl<T: Config> Clone for BasicCrossAccountId<T> {
+ fn clone(&self) -> Self {
+ Self {
+ from_ethereum: self.from_ethereum,
+ substrate: self.substrate.clone(),
+ ethereum: self.ethereum,
+ }
+ }
+}
+impl<T: Config> Encode for BasicCrossAccountId<T> {
+ fn encode(&self) -> Vec<u8> {
+ BasicCrossAccountIdRepr::from(self.clone()).encode()
+ }
+}
+impl<T: Config> EncodeLike for BasicCrossAccountId<T> {}
+impl<T: Config> Decode for BasicCrossAccountId<T> {
+ fn decode<I>(input: &mut I) -> Result<Self, codec::Error>
+ where
+ I: codec::Input,
+ {
+ Ok(BasicCrossAccountIdRepr::decode(input)?.into())
+ }
+}
+impl<T> Serialize for BasicCrossAccountId<T>
+where
+ T: Config,
+ T::AccountId: Serialize,
+{
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ let repr = BasicCrossAccountIdRepr::from(self.clone());
+ (&repr).serialize(serializer)
+ }
+}
+impl<'de, T> Deserialize<'de> for BasicCrossAccountId<T>
+where
+ T: Config,
+ T::AccountId: Deserialize<'de>,
+{
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ Ok(BasicCrossAccountIdRepr::deserialize(deserializer)?.into())
+ }
+}
+impl<T: Config> CrossAccountId<T::AccountId> for BasicCrossAccountId<T> {
+ fn as_sub(&self) -> &T::AccountId {
+ &self.substrate
+ }
+ fn as_eth(&self) -> &H160 {
+ &self.ethereum
+ }
+ fn from_sub(substrate: T::AccountId) -> Self {
+ Self {
+ ethereum: T::EvmBackwardsAddressMapping::from_account_id(substrate.clone()),
+ substrate,
+ from_ethereum: false,
+ }
+ }
+ fn from_eth(ethereum: H160) -> Self {
+ Self {
+ ethereum,
+ substrate: T::EvmAddressMapping::into_account_id(ethereum),
+ from_ethereum: true,
+ }
+ }
+}
+impl<T: Config> From<BasicCrossAccountIdRepr<T::AccountId>> for BasicCrossAccountId<T> {
+ fn from(repr: BasicCrossAccountIdRepr<T::AccountId>) -> Self {
+ match repr {
+ BasicCrossAccountIdRepr::Substrate(s) => Self::from_sub(s),
+ BasicCrossAccountIdRepr::Ethereum(e) => Self::from_eth(e),
+ }
+ }
+}
+impl<T: Config> From<BasicCrossAccountId<T>> for BasicCrossAccountIdRepr<T::AccountId> {
+ fn from(v: BasicCrossAccountId<T>) -> Self {
+ if v.from_ethereum {
+ BasicCrossAccountIdRepr::Ethereum(*v.as_eth())
+ } else {
+ BasicCrossAccountIdRepr::Substrate(v.as_sub().clone())
+ }
+ }
+}
+
+pub trait EvmBackwardsAddressMapping<AccountId> {
+ fn from_account_id(account_id: AccountId) -> H160;
+}
+
+/// Should have same mapping as EnsureAddressTruncated
+pub struct MapBackwardsAddressTruncated;
+impl EvmBackwardsAddressMapping<AccountId32> for MapBackwardsAddressTruncated {
+ fn from_account_id(account_id: AccountId32) -> H160 {
+ let mut out = [0; 20];
+ out.copy_from_slice(&(account_id.as_ref() as &[u8])[0..20]);
+ H160(out)
+ }
+}
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/common/src/benchmarking.rs
@@ -0,0 +1,91 @@
+use sp_std::vec::Vec;
+use crate::{Config, CollectionHandle};
+use nft_data_structs::{
+ CollectionMode, Collection, CollectionId, MAX_COLLECTION_NAME_LENGTH,
+ MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, OFFCHAIN_SCHEMA_LIMIT,
+ VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
+};
+use frame_support::traits::{Currency, Get};
+use core::convert::TryInto;
+use sp_runtime::DispatchError;
+
+pub fn create_data(size: usize) -> Vec<u8> {
+ (0..size).map(|v| (v & 0xff) as u8).collect()
+}
+pub fn create_u16_data(size: usize) -> Vec<u16> {
+ (0..size).map(|v| (v & 0xffff) as u16).collect()
+}
+
+pub fn create_collection_raw<T: Config, R>(
+ owner: T::AccountId,
+ mode: CollectionMode,
+ handler: impl FnOnce(Collection<T>) -> Result<CollectionId, DispatchError>,
+ cast: impl FnOnce(CollectionHandle<T>) -> R,
+) -> Result<R, DispatchError> {
+ T::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
+ let name = create_u16_data(MAX_COLLECTION_NAME_LENGTH)
+ .try_into()
+ .unwrap();
+ let description = create_u16_data(MAX_COLLECTION_DESCRIPTION_LENGTH)
+ .try_into()
+ .unwrap();
+ let token_prefix = create_data(MAX_TOKEN_PREFIX_LENGTH).try_into().unwrap();
+ let offchain_schema = create_data(OFFCHAIN_SCHEMA_LIMIT as usize)
+ .try_into()
+ .unwrap();
+ let variable_on_chain_schema = create_data(VARIABLE_ON_CHAIN_SCHEMA_LIMIT as usize)
+ .try_into()
+ .unwrap();
+ let const_on_chain_schema = create_data(CONST_ON_CHAIN_SCHEMA_LIMIT as usize)
+ .try_into()
+ .unwrap();
+ handler(Collection {
+ owner,
+ mode,
+ access: Default::default(),
+ name,
+ description,
+ token_prefix,
+ mint_mode: true,
+ offchain_schema,
+ schema_version: Default::default(),
+ sponsorship: Default::default(),
+ limits: Default::default(),
+ variable_on_chain_schema,
+ const_on_chain_schema,
+ meta_update_permission: Default::default(),
+ transfers_enabled: true,
+ })
+ .and_then(CollectionHandle::try_get)
+ .map(cast)
+}
+
+#[macro_export]
+macro_rules! bench_init {
+ ($name:ident: sub $(($id:expr))?; $($rest:tt)*) => {
+ let $name: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);
+ bench_init!($($rest)*);
+ };
+ ($name:ident: collection($owner:ident); $($rest:tt)*) => {
+ let $name = create_collection::<T>($owner.clone())?;
+ bench_init!($($rest)*);
+ };
+ ($name:ident: cross; $($rest:tt)*) => {
+ let $name = T::CrossAccountId::from_sub($name);
+ bench_init!($($rest)*);
+ };
+ ($name:ident: cross_sub $(($id:expr))?; $($rest:tt)*) => {
+ let account: T::AccountId = account(stringify!($name), 0 $(+ $id)?, SEED);
+ let $name = T::CrossAccountId::from_sub(account);
+ bench_init!($($rest)*);
+ };
+ ($name:ident: cross_from_sub; $($rest:tt)*) => {
+ let $name = T::CrossAccountId::from_sub($name);
+ bench_init!($($rest)*);
+ };
+ ($name:ident: cross_from_sub($from:ident); $($rest:tt)*) => {
+ let $name = T::CrossAccountId::from_sub($from);
+ bench_init!($($rest)*);
+ };
+ () => {}
+}
pallets/common/src/erc.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/common/src/erc.rs
@@ -0,0 +1,10 @@
+pub use pallet_evm::PrecompileOutput;
+use sp_core::{H160, U256};
+
+/// Does not always represent a full collection, for RFT it is either
+/// collection (Implementing ERC721), or specific collection token (Implementing ERC20)
+pub trait CommonEvmHandler {
+ const CODE: &'static [u8];
+
+ fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileOutput>;
+}
pallets/common/src/eth.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/common/src/eth.rs
@@ -0,0 +1,50 @@
+use nft_data_structs::{CollectionId, TokenId};
+use sp_core::H160;
+
+// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 1
+// TODO: Unhardcode prefix
+const ETH_ACCOUNT_PREFIX: [u8; 16] = [
+ 0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
+];
+
+// 0xf8238ccfff8ed887463fd5e00000000100000002 - collection 1, token 2
+// TODO: Unhardcode prefix
+const ETH_ACCOUNT_TOKEN_PREFIX: [u8; 12] = [
+ 0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
+];
+
+pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {
+ if eth[0..16] != ETH_ACCOUNT_PREFIX {
+ return None;
+ }
+ let mut id_bytes = [0; 4];
+ id_bytes.copy_from_slice(ð[16..20]);
+ Some(CollectionId(u32::from_be_bytes(id_bytes)))
+}
+pub fn collection_id_to_address(id: CollectionId) -> H160 {
+ let mut out = [0; 20];
+ out[0..16].copy_from_slice(Ð_ACCOUNT_PREFIX);
+ out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));
+ H160(out)
+}
+
+pub fn map_eth_to_token_id(eth: &H160) -> Option<(CollectionId, TokenId)> {
+ if eth[0..12] != ETH_ACCOUNT_TOKEN_PREFIX {
+ return None;
+ }
+ let mut id_bytes = [0; 4];
+ let mut token_id_bytes = [0; 4];
+ id_bytes.copy_from_slice(ð[12..16]);
+ token_id_bytes.copy_from_slice(ð[16..20]);
+ Some((
+ CollectionId(u32::from_be_bytes(id_bytes)),
+ TokenId(u32::from_be_bytes(token_id_bytes)),
+ ))
+}
+pub fn collection_token_id_to_address(id: CollectionId, token: TokenId) -> H160 {
+ let mut out = [0; 20];
+ out[0..12].copy_from_slice(Ð_ACCOUNT_TOKEN_PREFIX);
+ out[12..16].copy_from_slice(&u32::to_be_bytes(id.0));
+ out[16..20].copy_from_slice(&u32::to_be_bytes(token.0));
+ H160(out)
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/common/src/lib.rs
@@ -0,0 +1,555 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use core::ops::{Deref, DerefMut};
+use sp_std::vec::Vec;
+use account::CrossAccountId;
+use frame_support::{
+ dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},
+ ensure, fail,
+ traits::{Imbalance, Get, Currency},
+};
+use nft_data_structs::{
+ COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
+ MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+ MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight, WithdrawReasons,
+};
+pub use pallet::*;
+use sp_core::H160;
+use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
+pub mod account;
+#[cfg(feature = "runtime-benchmarks")]
+pub mod benchmarking;
+pub mod erc;
+pub mod eth;
+
+#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]
+pub struct CollectionHandle<T: Config> {
+ pub id: CollectionId,
+ collection: Collection<T>,
+ pub recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,
+}
+impl<T: Config> CollectionHandle<T> {
+ pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {
+ <CollectionById<T>>::get(id).map(|collection| Self {
+ id,
+ collection,
+ recorder: pallet_evm_coder_substrate::SubstrateRecorder::new(
+ eth::collection_id_to_address(id),
+ gas_limit,
+ ),
+ })
+ }
+ pub fn new(id: CollectionId) -> Option<Self> {
+ Self::new_with_gas_limit(id, u64::MAX)
+ }
+ pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {
+ Ok(Self::new(id).ok_or_else(|| <Error<T>>::CollectionNotFound)?)
+ }
+ pub fn log(&self, log: impl evm_coder::ToLog) -> DispatchResult {
+ self.recorder.log_sub(log)
+ }
+ pub fn log_infallible(&self, log: impl evm_coder::ToLog) {
+ self.recorder.log_infallible(log)
+ }
+ #[allow(dead_code)]
+ fn consume_gas(&self, gas: u64) -> DispatchResult {
+ self.recorder.consume_gas_sub(gas)
+ }
+ pub fn consume_sload(&self) -> DispatchResult {
+ self.recorder.consume_sload_sub()
+ }
+ pub fn consume_sstores(&self, amount: usize) -> DispatchResult {
+ self.recorder.consume_sstores_sub(amount)
+ }
+ pub fn consume_sstore(&self) -> DispatchResult {
+ self.recorder.consume_sstore_sub()
+ }
+ pub fn consume_log(&self, topics: usize, data: usize) -> DispatchResult {
+ self.recorder.consume_log_sub(topics, data)
+ }
+ pub fn submit_logs(self) -> DispatchResult {
+ self.recorder.submit_logs()
+ }
+ pub fn save(self) -> DispatchResult {
+ self.recorder.submit_logs()?;
+ <CollectionById<T>>::insert(self.id, self.collection);
+ Ok(())
+ }
+}
+impl<T: Config> Deref for CollectionHandle<T> {
+ type Target = Collection<T>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.collection
+ }
+}
+
+impl<T: Config> DerefMut for CollectionHandle<T> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.collection
+ }
+}
+
+impl<T: Config> CollectionHandle<T> {
+ pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {
+ ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);
+ Ok(())
+ }
+ pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> Result<bool, DispatchError> {
+ self.consume_sload()?;
+
+ Ok(*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject.as_sub())))
+ }
+ pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {
+ ensure!(self.is_owner_or_admin(subject)?, <Error<T>>::NoPermission);
+ Ok(())
+ }
+ pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {
+ Ok(self.limits.owner_can_transfer && self.is_owner_or_admin(user)?)
+ }
+ pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {
+ Ok(self.limits.owner_can_transfer && self.is_owner_or_admin(user)?)
+ }
+ pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {
+ self.consume_sload()?;
+
+ ensure!(
+ <Allowlist<T>>::get((self.id, user.as_sub())),
+ <Error<T>>::AddressNotInAllowlist
+ );
+ Ok(())
+ }
+
+ pub fn check_can_update_meta(
+ &self,
+ subject: &T::CrossAccountId,
+ item_owner: &T::CrossAccountId,
+ ) -> DispatchResult {
+ match self.meta_update_permission {
+ MetaUpdatePermission::ItemOwner => {
+ ensure!(subject == item_owner, <Error<T>>::NoPermission);
+ Ok(())
+ }
+ MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),
+ MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),
+ }
+ }
+}
+
+#[frame_support::pallet]
+pub mod pallet {
+ use super::*;
+ use frame_support::{pallet_prelude::*};
+ use frame_support::{Blake2_128Concat, storage::Key};
+ use account::{EvmBackwardsAddressMapping, CrossAccountId};
+ use frame_support::traits::Currency;
+ use nft_data_structs::TokenId;
+ use scale_info::TypeInfo;
+
+ #[pallet::config]
+ pub trait Config: frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo {
+ type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;
+
+ type CrossAccountId: CrossAccountId<Self::AccountId>;
+
+ type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;
+ type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;
+
+ type Currency: Currency<Self::AccountId>;
+ type CollectionCreationPrice: Get<
+ <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,
+ >;
+ type TreasuryAccountId: Get<Self::AccountId>;
+ }
+
+ #[pallet::pallet]
+ #[pallet::generate_store(pub(super) trait Store)]
+ pub struct Pallet<T>(_);
+
+ #[pallet::event]
+ #[pallet::generate_deposit(pub fn deposit_event)]
+ pub enum Event<T: Config> {
+ /// New collection was created
+ ///
+ /// # Arguments
+ ///
+ /// * collection_id: Globally unique identifier of newly created collection.
+ ///
+ /// * mode: [CollectionMode] converted into u8.
+ ///
+ /// * account_id: Collection owner.
+ CollectionCreated(CollectionId, u8, T::AccountId),
+
+ /// New item was created.
+ ///
+ /// # Arguments
+ ///
+ /// * collection_id: Id of the collection where item was created.
+ ///
+ /// * item_id: Id of an item. Unique within the collection.
+ ///
+ /// * recipient: Owner of newly created item
+ ///
+ /// * amount: Always 1 for NFT
+ ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),
+
+ /// Collection item was burned.
+ ///
+ /// # Arguments
+ ///
+ /// * collection_id.
+ ///
+ /// * item_id: Identifier of burned NFT.
+ ///
+ /// * owner: which user has destroyed its tokens
+ ///
+ /// * amount: Always 1 for NFT
+ ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),
+
+ /// Item was transferred
+ ///
+ /// * collection_id: Id of collection to which item is belong
+ ///
+ /// * item_id: Id of an item
+ ///
+ /// * sender: Original owner of item
+ ///
+ /// * recipient: New owner of item
+ ///
+ /// * amount: Always 1 for NFT
+ Transfer(
+ CollectionId,
+ TokenId,
+ T::CrossAccountId,
+ T::CrossAccountId,
+ u128,
+ ),
+
+ /// * collection_id
+ ///
+ /// * item_id
+ ///
+ /// * sender
+ ///
+ /// * spender
+ ///
+ /// * amount
+ Approved(
+ CollectionId,
+ TokenId,
+ T::CrossAccountId,
+ T::CrossAccountId,
+ u128,
+ ),
+ }
+
+ #[pallet::error]
+ pub enum Error<T> {
+ /// This collection does not exist.
+ CollectionNotFound,
+ /// Sender parameter and item owner must be equal.
+ MustBeTokenOwner,
+ /// No permission to perform action
+ NoPermission,
+ /// Collection is not in mint mode.
+ PublicMintingNotAllowed,
+ /// Address is not in white list.
+ AddressNotInAllowlist,
+
+ /// Collection name can not be longer than 63 char.
+ CollectionNameLimitExceeded,
+ /// Collection description can not be longer than 255 char.
+ CollectionDescriptionLimitExceeded,
+ /// Token prefix can not be longer than 15 char.
+ CollectionTokenPrefixLimitExceeded,
+ /// Total collections bound exceeded.
+ TotalCollectionsLimitExceeded,
+ /// variable_data exceeded data limit.
+ TokenVariableDataLimitExceeded,
+
+ /// Collection settings not allowing items transferring
+ TransferNotAllowed,
+ /// Account token limit exceeded per collection
+ AccountTokenLimitExceeded,
+ /// Collection token limit exceeded
+ CollectionTokenLimitExceeded,
+ /// Metadata flag frozen
+ MetadataFlagFrozen,
+
+ /// Item not exists.
+ TokenNotFound,
+ /// Item balance not enough.
+ TokenValueTooLow,
+ /// Requested value more than approved.
+ TokenValueNotEnough,
+ /// Tried to approve more than owned
+ CantApproveMoreThanOwned,
+
+ /// Can't transfer tokens to ethereum zero address
+ AddressIsZero,
+ /// Target collection doesn't supports this operation
+ UnsupportedOperation,
+ }
+
+ #[pallet::storage]
+ pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;
+ #[pallet::storage]
+ pub type DestroyedCollectionCount<T> =
+ StorageValue<Value = CollectionId, QueryKind = ValueQuery>;
+
+ /// Collection info
+ #[pallet::storage]
+ pub type CollectionById<T> = StorageMap<
+ Hasher = Blake2_128Concat,
+ Key = CollectionId,
+ Value = Collection<T>,
+ QueryKind = OptionQuery,
+ >;
+
+ /// List of collection admins
+ #[pallet::storage]
+ pub type IsAdmin<T: Config> = StorageNMap<
+ Key = (
+ Key<Blake2_128Concat, CollectionId>,
+ Key<Blake2_128Concat, T::AccountId>,
+ ),
+ Value = bool,
+ QueryKind = ValueQuery,
+ >;
+
+ /// Allowlisted collection users
+ #[pallet::storage]
+ pub type Allowlist<T: Config> = StorageNMap<
+ Key = (
+ Key<Blake2_128Concat, CollectionId>,
+ Key<Blake2_128Concat, T::AccountId>,
+ ),
+ Value = bool,
+ QueryKind = ValueQuery,
+ >;
+}
+
+impl<T: Config> Pallet<T> {
+ /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens
+ pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {
+ ensure!(
+ &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,
+ <Error<T>>::AddressIsZero
+ );
+ Ok(())
+ }
+}
+
+impl<T: Config> Pallet<T> {
+ pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
+ {
+ ensure!(
+ data.name.len() <= MAX_COLLECTION_NAME_LENGTH,
+ Error::<T>::CollectionNameLimitExceeded
+ );
+ ensure!(
+ data.description.len() <= MAX_COLLECTION_DESCRIPTION_LENGTH,
+ Error::<T>::CollectionDescriptionLimitExceeded
+ );
+ ensure!(
+ data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH,
+ Error::<T>::CollectionTokenPrefixLimitExceeded
+ );
+ }
+
+ let created_count = <CreatedCollectionCount<T>>::get()
+ .0
+ .checked_add(1)
+ .ok_or(ArithmeticError::Overflow)?;
+ let destroyed_count = <DestroyedCollectionCount<T>>::get().0;
+ let id = CollectionId(created_count);
+
+ // bound Total number of collections
+ ensure!(
+ created_count - destroyed_count < COLLECTION_NUMBER_LIMIT,
+ <Error<T>>::TotalCollectionsLimitExceeded
+ );
+
+ // =========
+
+ // Take a (non-refundable) deposit of collection creation
+ {
+ let mut imbalance =
+ <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();
+ imbalance.subsume(
+ <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(
+ &T::TreasuryAccountId::get(),
+ T::CollectionCreationPrice::get(),
+ ),
+ );
+ <T as Config>::Currency::settle(
+ &data.owner,
+ imbalance,
+ WithdrawReasons::TRANSFER,
+ ExistenceRequirement::KeepAlive,
+ )
+ .map_err(|_| Error::<T>::NoPermission)?;
+ }
+
+ <CreatedCollectionCount<T>>::put(created_count);
+ <Pallet<T>>::deposit_event(Event::CollectionCreated(
+ id,
+ data.mode.id(),
+ data.owner.clone(),
+ ));
+ <CollectionById<T>>::insert(id, data);
+ Ok(id)
+ }
+
+ pub fn destroy_collection(
+ collection: CollectionHandle<T>,
+ sender: &T::CrossAccountId,
+ ) -> DispatchResult {
+ if !collection.limits.owner_can_destroy {
+ fail!(Error::<T>::NoPermission);
+ }
+ collection.check_is_owner(&sender)?;
+
+ let destroyed_collections = <DestroyedCollectionCount<T>>::get()
+ .0
+ .checked_add(1)
+ .ok_or(ArithmeticError::Overflow)?;
+
+ // =========
+
+ <DestroyedCollectionCount<T>>::put(destroyed_collections);
+ <CollectionById<T>>::remove(collection.id);
+ <IsAdmin<T>>::remove_prefix((collection.id,), None);
+ <Allowlist<T>>::remove_prefix((collection.id,), None);
+ Ok(())
+ }
+
+ pub fn toggle_allowlist(
+ collection: &CollectionHandle<T>,
+ sender: &T::CrossAccountId,
+ user: &T::CrossAccountId,
+ allowed: bool,
+ ) -> DispatchResult {
+ collection.check_is_owner_or_admin(&sender)?;
+
+ // =========
+
+ if allowed {
+ <Allowlist<T>>::insert((collection.id, user.as_sub()), true);
+ } else {
+ <Allowlist<T>>::remove((collection.id, user.as_sub()));
+ }
+
+ Ok(())
+ }
+}
+
+#[macro_export]
+macro_rules! unsupported {
+ () => {
+ Err(<Error<T>>::UnsupportedOperation.into())
+ };
+}
+
+/// Worst cases
+pub trait CommonWeightInfo {
+ fn create_item() -> Weight;
+ fn create_multiple_items(amount: u32) -> Weight;
+ fn burn_item() -> Weight;
+ fn transfer() -> Weight;
+ fn approve() -> Weight;
+ fn transfer_from() -> Weight;
+ fn burn_from() -> Weight;
+ fn set_variable_metadata(bytes: u32) -> Weight;
+}
+
+pub trait CommonCollectionOperations<T: Config> {
+ fn create_item(
+ &self,
+ sender: T::CrossAccountId,
+ to: T::CrossAccountId,
+ data: CreateItemData,
+ ) -> DispatchResultWithPostInfo;
+ fn create_multiple_items(
+ &self,
+ sender: T::CrossAccountId,
+ to: T::CrossAccountId,
+ data: Vec<CreateItemData>,
+ ) -> DispatchResultWithPostInfo;
+ fn burn_item(
+ &self,
+ sender: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo;
+
+ fn transfer(
+ &self,
+ sender: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo;
+ fn approve(
+ &self,
+ sender: T::CrossAccountId,
+ spender: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo;
+ fn transfer_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo;
+ fn burn_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo;
+
+ fn set_variable_metadata(
+ &self,
+ sender: T::CrossAccountId,
+ token: TokenId,
+ data: Vec<u8>,
+ ) -> DispatchResultWithPostInfo;
+
+ fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;
+ fn token_exists(&self, token: TokenId) -> bool;
+ fn last_token_id(&self) -> TokenId;
+
+ fn token_owner(&self, token: TokenId) -> T::CrossAccountId;
+ fn const_metadata(&self, token: TokenId) -> Vec<u8>;
+ fn variable_metadata(&self, token: TokenId) -> Vec<u8>;
+
+ /// How many tokens collection contains (Applicable to nonfungible/refungible)
+ fn collection_tokens(&self) -> u32;
+ /// Amount of different tokens account has (Applicable to nonfungible/refungible)
+ fn account_balance(&self, account: T::CrossAccountId) -> u32;
+ /// Amount of specific token account have (Applicable to fungible/refungible)
+ fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;
+ fn allowance(
+ &self,
+ sender: T::CrossAccountId,
+ spender: T::CrossAccountId,
+ token: TokenId,
+ ) -> u128;
+}
+
+// Flexible enough for implementing CommonCollectionOperations
+pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {
+ let post_info = PostDispatchInfo {
+ actual_weight: Some(weight),
+ pays_fee: Pays::Yes,
+ };
+ match res {
+ Ok(()) => Ok(post_info),
+ Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),
+ }
+}
pallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -16,7 +16,7 @@
execution::{self, Result},
types::{Msg, value},
};
- use frame_support::ensure;
+ use frame_support::{ensure};
use pallet_evm::{ExitError, ExitReason, ExitRevert, ExitSucceed, PrecompileOutput};
pub use frame_support::dispatch::DispatchResult;
use pallet_ethereum::EthereumTransactionSender;
@@ -106,6 +106,10 @@
self.logs.borrow_mut().push(log);
Ok(())
}
+ /// Doesn't consumes any gas, should be used after consume_log_sub
+ pub fn log_infallible(&self, log: impl ToLog) {
+ self.logs.borrow_mut().push(log.to_log(self.contract));
+ }
pub fn retrieve_logs(self) -> Vec<Log> {
self.logs.into_inner()
}
@@ -116,9 +120,15 @@
pub fn consume_sload_sub(&self) -> DispatchResult {
self.consume_gas_sub(G_SLOAD_WORD)
}
+ pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {
+ self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))
+ }
pub fn consume_sstore_sub(&self) -> DispatchResult {
self.consume_gas_sub(G_SSTORE_WORD)
}
+ pub fn consume_log_sub(&self, topics: usize, data: usize) -> DispatchResult {
+ self.consume_gas_sub(log_price(data, topics))
+ }
pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {
ensure!(gas != u64::MAX, Error::<T>::OutOfGas);
let mut gas_limit = self.gas_limit.borrow_mut();
pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
+++ b/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
@@ -9,7 +9,19 @@
string stub_error = "this contract is implemented in native";
}
-contract ContractHelpers is Dummy {
+contract ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID)
+ external
+ view
+ returns (bool)
+ {
+ require(false, stub_error);
+ interfaceID;
+ return true;
+ }
+}
+
+contract ContractHelpers is Dummy, ERC165 {
// Selector: contractOwner(address) 5152b14c
function contractOwner(address contractAddress)
public
pallets/fungible/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/pallets/fungible/Cargo.toml
@@ -0,0 +1,42 @@
+[package]
+name = "pallet-fungible"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies.codec]
+default-features = false
+features = ['derive']
+package = 'parity-scale-codec'
+version = '2.0.0'
+
+[dependencies]
+frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+pallet-common = { default-features = false, path = '../common' }
+nft-data-structs = { default-features = false, path = '../../primitives/nft' }
+evm-coder = { default-features = false, path = '../../crates/evm-coder' }
+pallet-evm-coder-substrate = { default-features = false, path = '../evm-coder-substrate' }
+ethereum = { git = "https://github.com/purestake/ethereum", branch = "joshy-scale-info", default-features = false }
+frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+scale-info = { version = "1.0.0", default-features = false, features = [
+ "derive",
+] }
+
+[features]
+default = ["std"]
+std = [
+ "frame-support/std",
+ "frame-system/std",
+ "sp-runtime/std",
+ "sp-std/std",
+ "nft-data-structs/std",
+ "pallet-common/std",
+ "evm-coder/std",
+ "ethereum/std",
+ "pallet-evm-coder-substrate/std",
+ 'frame-benchmarking/std',
+]
+runtime-benchmarks = ['frame-benchmarking', 'pallet-common/runtime-benchmarks']
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/fungible/src/benchmarking.rs
@@ -0,0 +1,61 @@
+use super::*;
+use crate::{Pallet, Config, FungibleHandle};
+
+use sp_std::prelude::*;
+use pallet_common::benchmarking::create_collection_raw;
+use frame_benchmarking::{benchmarks, account};
+use nft_data_structs::{CollectionMode};
+use pallet_common::bench_init;
+
+const SEED: u32 = 1;
+
+fn create_collection<T: Config>(owner: T::AccountId) -> Result<FungibleHandle<T>, DispatchError> {
+ create_collection_raw(
+ owner,
+ CollectionMode::Fungible(0),
+ <Pallet<T>>::init_collection,
+ FungibleHandle::cast,
+ )
+}
+
+benchmarks! {
+ create_item {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); to: cross_sub;
+ };
+ }: {<Pallet<T>>::create_item(&collection, &sender, (to, 200))?}
+
+ burn_item {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; burner: cross_sub;
+ };
+ <Pallet<T>>::create_item(&collection, &owner, (burner.clone(), 200))?;
+ }: {<Pallet<T>>::burn(&collection, &burner, 100)?}
+
+ transfer {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; to: cross_sub;
+ };
+ <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200))?;
+ }: {<Pallet<T>>::transfer(&collection, &sender, &to, 200)?}
+
+ approve {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+ };
+ <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200))?;
+ }: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, 100)?}
+
+ transfer_from {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+ };
+ <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200))?;
+ <Pallet<T>>::set_allowance(&collection, &sender, &spender, 200)?;
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, 100)?}
+}
pallets/fungible/src/common.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/fungible/src/common.rs
@@ -0,0 +1,246 @@
+use core::marker::PhantomData;
+
+use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
+use nft_data_structs::TokenId;
+use pallet_common::{
+ CommonCollectionOperations, CommonWeightInfo, account::CrossAccountId, with_weight,
+};
+use sp_runtime::ArithmeticError;
+use sp_std::{vec::Vec, vec};
+
+use crate::{
+ Allowance, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf, weights::WeightInfo,
+};
+
+pub struct CommonWeights<T: Config>(PhantomData<T>);
+impl<T: Config> CommonWeightInfo for CommonWeights<T> {
+ fn create_item() -> Weight {
+ <SelfWeightOf<T>>::create_item()
+ }
+
+ fn create_multiple_items(_amount: u32) -> Weight {
+ Self::create_item()
+ }
+
+ fn burn_item() -> Weight {
+ <SelfWeightOf<T>>::burn_item()
+ }
+
+ fn transfer() -> Weight {
+ <SelfWeightOf<T>>::transfer()
+ }
+
+ fn approve() -> Weight {
+ <SelfWeightOf<T>>::approve()
+ }
+
+ fn transfer_from() -> Weight {
+ <SelfWeightOf<T>>::transfer_from()
+ }
+
+ fn burn_from() -> Weight {
+ 0
+ }
+
+ fn set_variable_metadata(_bytes: u32) -> Weight {
+ // Error
+ 0
+ }
+}
+
+impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {
+ fn create_item(
+ &self,
+ sender: T::CrossAccountId,
+ to: T::CrossAccountId,
+ data: nft_data_structs::CreateItemData,
+ ) -> DispatchResultWithPostInfo {
+ match data {
+ nft_data_structs::CreateItemData::Fungible(data) => with_weight(
+ <Pallet<T>>::create_item(self, &sender, (to, data.value)),
+ <CommonWeights<T>>::create_item(),
+ ),
+ _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
+ }
+ }
+
+ fn create_multiple_items(
+ &self,
+ sender: T::CrossAccountId,
+ to: T::CrossAccountId,
+ data: Vec<nft_data_structs::CreateItemData>,
+ ) -> DispatchResultWithPostInfo {
+ let mut sum: u128 = 0;
+ for data in data {
+ match data {
+ nft_data_structs::CreateItemData::Fungible(data) => {
+ sum = sum
+ .checked_add(data.value)
+ .ok_or(ArithmeticError::Overflow)?;
+ }
+ _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
+ }
+ }
+
+ with_weight(
+ <Pallet<T>>::create_item(self, &sender, (to, sum)),
+ <CommonWeights<T>>::create_item(),
+ )
+ }
+
+ fn burn_item(
+ &self,
+ sender: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(
+ token == TokenId::default(),
+ <Error<T>>::FungibleItemsHaveNoId
+ );
+
+ with_weight(
+ <Pallet<T>>::burn(self, &sender, amount),
+ <CommonWeights<T>>::burn_item(),
+ )
+ }
+
+ fn transfer(
+ &self,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(
+ token == TokenId::default(),
+ <Error<T>>::FungibleItemsHaveNoId
+ );
+
+ with_weight(
+ <Pallet<T>>::transfer(&self, &from, &to, amount),
+ <CommonWeights<T>>::transfer(),
+ )
+ }
+
+ fn approve(
+ &self,
+ sender: T::CrossAccountId,
+ spender: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(
+ token == TokenId::default(),
+ <Error<T>>::FungibleItemsHaveNoId
+ );
+
+ with_weight(
+ <Pallet<T>>::set_allowance(&self, &sender, &spender, amount),
+ <CommonWeights<T>>::approve(),
+ )
+ }
+
+ fn transfer_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(
+ token == TokenId::default(),
+ <Error<T>>::FungibleItemsHaveNoId
+ );
+
+ with_weight(
+ <Pallet<T>>::transfer_from(&self, &sender, &from, &to, amount),
+ <CommonWeights<T>>::transfer_from(),
+ )
+ }
+
+ fn burn_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(
+ token == TokenId::default(),
+ <Error<T>>::FungibleItemsHaveNoId
+ );
+
+ with_weight(
+ <Pallet<T>>::burn_from(&self, &sender, &from, amount),
+ <CommonWeights<T>>::burn_from(),
+ )
+ }
+
+ fn set_variable_metadata(
+ &self,
+ _sender: T::CrossAccountId,
+ _token: TokenId,
+ _data: Vec<u8>,
+ ) -> DispatchResultWithPostInfo {
+ fail!(<Error<T>>::FungibleItemsHaveData)
+ }
+
+ fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
+ if <Balance<T>>::get((self.id, account.as_sub())) != 0 {
+ vec![TokenId::default()]
+ } else {
+ vec![]
+ }
+ }
+
+ fn token_exists(&self, token: TokenId) -> bool {
+ token == TokenId::default()
+ }
+
+ fn last_token_id(&self) -> TokenId {
+ TokenId::default()
+ }
+
+ fn token_owner(&self, _token: TokenId) -> T::CrossAccountId {
+ T::CrossAccountId::default()
+ }
+ fn const_metadata(&self, _token: TokenId) -> Vec<u8> {
+ Vec::new()
+ }
+ fn variable_metadata(&self, _token: TokenId) -> Vec<u8> {
+ Vec::new()
+ }
+
+ fn collection_tokens(&self) -> u32 {
+ 1
+ }
+
+ fn account_balance(&self, account: T::CrossAccountId) -> u32 {
+ if <Balance<T>>::get((self.id, account.as_sub())) != 0 {
+ 1
+ } else {
+ 0
+ }
+ }
+
+ fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {
+ if token != TokenId::default() {
+ return 0;
+ }
+ <Balance<T>>::get((self.id, account.as_sub()))
+ }
+
+ fn allowance(
+ &self,
+ sender: T::CrossAccountId,
+ spender: T::CrossAccountId,
+ token: TokenId,
+ ) -> u128 {
+ if token != TokenId::default() {
+ return 0;
+ }
+ <Allowance<T>>::get((self.id, sender.as_sub(), spender.as_sub()))
+ }
+}
pallets/fungible/src/erc.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/fungible/src/erc.rs
@@ -0,0 +1,124 @@
+use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
+use core::convert::TryInto;
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*};
+use nft_data_structs::CollectionMode;
+use pallet_common::erc::CommonEvmHandler;
+use sp_core::{H160, U256};
+use sp_std::vec::Vec;
+use pallet_common::account::CrossAccountId;
+use pallet_common::erc::PrecompileOutput;
+use pallet_evm_coder_substrate::{call_internal, dispatch_to_evm};
+
+use crate::{Allowance, Balance, Config, FungibleHandle, Pallet, TotalSupply};
+
+#[derive(ToLog)]
+pub enum ERC20Events {
+ Transfer {
+ #[indexed]
+ from: address,
+ #[indexed]
+ to: address,
+ value: uint256,
+ },
+ Approval {
+ #[indexed]
+ owner: address,
+ #[indexed]
+ spender: address,
+ value: uint256,
+ },
+}
+
+#[solidity_interface(name = "ERC20", events(ERC20Events))]
+impl<T: Config> FungibleHandle<T> {
+ fn name(&self) -> Result<string> {
+ Ok(decode_utf16(self.name.iter().copied())
+ .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+ .collect::<string>())
+ }
+ fn symbol(&self) -> Result<string> {
+ Ok(string::from_utf8_lossy(&self.token_prefix).into())
+ }
+ fn total_supply(&self) -> Result<uint256> {
+ Ok(<TotalSupply<T>>::get(self.id).into())
+ }
+
+ fn decimals(&self) -> Result<uint8> {
+ Ok(if let CollectionMode::Fungible(decimals) = &self.mode {
+ *decimals
+ } else {
+ unreachable!()
+ })
+ }
+ fn balance_of(&self, owner: address) -> Result<uint256> {
+ let owner = T::CrossAccountId::from_eth(owner);
+ let balance = <Balance<T>>::get((self.id, owner.as_sub()));
+ Ok(balance.into())
+ }
+ fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let to = T::CrossAccountId::from_eth(to);
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+
+ <Pallet<T>>::transfer(self, &caller, &to, amount).map_err(|_| "transfer error")?;
+ Ok(true)
+ }
+ fn transfer_from(
+ &mut self,
+ caller: caller,
+ from: address,
+ to: address,
+ amount: uint256,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let from = T::CrossAccountId::from_eth(from);
+ let to = T::CrossAccountId::from_eth(to);
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+
+ <Pallet<T>>::transfer_from(self, &caller, &from, &to, amount)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+ fn approve(&mut self, caller: caller, spender: address, amount: uint256) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let spender = T::CrossAccountId::from_eth(spender);
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+
+ <Pallet<T>>::set_allowance(self, &caller, &spender, amount)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+ fn allowance(&self, owner: address, spender: address) -> Result<uint256> {
+ let owner = T::CrossAccountId::from_eth(owner);
+ let spender = T::CrossAccountId::from_eth(spender);
+
+ Ok(<Allowance<T>>::get((self.id, owner.as_sub(), spender.as_sub())).into())
+ }
+}
+
+#[solidity_interface(name = "ERC20UniqueExtensions")]
+impl<T: Config> FungibleHandle<T> {
+ fn burn_from(&mut self, caller: caller, from: address, amount: uint256) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let from = T::CrossAccountId::from_eth(from);
+ let amount = amount.try_into().map_err(|_| "amount overflow")?;
+
+ <Pallet<T>>::burn_from(self, &caller, &from, amount).map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+}
+
+#[solidity_interface(name = "UniqueFungible", is(ERC20))]
+impl<T: Config> FungibleHandle<T> {}
+
+generate_stubgen!(gen_impl, UniqueFungibleCall, true);
+generate_stubgen!(gen_iface, UniqueFungibleCall, false);
+
+impl<T: Config> CommonEvmHandler for FungibleHandle<T> {
+ const CODE: &'static [u8] = include_bytes!("./stubs/UniqueFungible.raw");
+
+ fn call(mut self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileOutput> {
+ let result = call_internal::<UniqueFungibleCall, _>(*source, &mut self, value, input);
+ self.0.recorder.evm_to_precompile_output(result)
+ }
+}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/fungible/src/lib.rs
@@ -0,0 +1,399 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use core::ops::Deref;
+use frame_support::{ensure};
+use nft_data_structs::{AccessMode, Collection, CollectionId, TokenId};
+use pallet_common::{
+ Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
+};
+use sp_core::H160;
+use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
+use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
+
+pub use pallet::*;
+
+use crate::erc::ERC20Events;
+#[cfg(feature = "runtime-benchmarks")]
+pub mod benchmarking;
+pub mod common;
+pub mod erc;
+pub mod weights;
+
+pub type CreateItemData<T> = (<T as pallet_common::Config>::CrossAccountId, u128);
+pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
+
+#[frame_support::pallet]
+pub mod pallet {
+ use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};
+ use nft_data_structs::CollectionId;
+ use super::weights::WeightInfo;
+
+ #[pallet::error]
+ pub enum Error<T> {
+ /// Not Fungible item data used to mint in Fungible collection.
+ NotFungibleDataUsedToMintFungibleCollectionToken,
+ /// Not default id passed as TokenId argument
+ FungibleItemsHaveNoId,
+ /// Tried to set data for fungible item
+ FungibleItemsHaveData,
+ }
+
+ #[pallet::config]
+ pub trait Config: frame_system::Config + pallet_common::Config {
+ type WeightInfo: WeightInfo;
+ }
+
+ #[pallet::pallet]
+ #[pallet::generate_store(pub(super) trait Store)]
+ pub struct Pallet<T>(_);
+
+ #[pallet::storage]
+ pub(super) type TotalSupply<T: Config> =
+ StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;
+
+ #[pallet::storage]
+ pub(super) type Balance<T: Config> = StorageNMap<
+ Key = (
+ Key<Twox64Concat, CollectionId>,
+ Key<Blake2_128Concat, T::AccountId>,
+ ),
+ Value = u128,
+ QueryKind = ValueQuery,
+ >;
+
+ #[pallet::storage]
+ pub(super) type Allowance<T: Config> = StorageNMap<
+ Key = (
+ Key<Twox64Concat, CollectionId>,
+ Key<Blake2_128, T::AccountId>,
+ Key<Blake2_128Concat, T::AccountId>,
+ ),
+ Value = u128,
+ QueryKind = ValueQuery,
+ >;
+}
+
+pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);
+impl<T: Config> FungibleHandle<T> {
+ pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {
+ Self(inner)
+ }
+ pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
+ self.0
+ }
+}
+impl<T: Config> Deref for FungibleHandle<T> {
+ type Target = pallet_common::CollectionHandle<T>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl<T: Config> Pallet<T> {
+ pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
+ PalletCommon::init_collection(data)
+ }
+ pub fn destroy_collection(
+ collection: FungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ ) -> DispatchResult {
+ let id = collection.id;
+
+ // =========
+
+ PalletCommon::destroy_collection(collection.0, sender)?;
+
+ <TotalSupply<T>>::remove(id);
+ <Balance<T>>::remove_prefix((id,), None);
+ <Allowance<T>>::remove_prefix((id,), None);
+ Ok(())
+ }
+
+ pub fn burn(
+ collection: &FungibleHandle<T>,
+ owner: &T::CrossAccountId,
+ amount: u128,
+ ) -> DispatchResult {
+ let total_supply = <TotalSupply<T>>::get(collection.id)
+ .checked_sub(amount)
+ .ok_or(<CommonError<T>>::TokenValueTooLow)?;
+
+ let balance = <Balance<T>>::get((collection.id, owner.as_sub()))
+ .checked_sub(amount)
+ .ok_or(<CommonError<T>>::TokenValueTooLow)?;
+
+ if collection.access == AccessMode::WhiteList {
+ collection.check_allowlist(owner)?;
+ }
+
+ // =========
+
+ if balance == 0 {
+ <Balance<T>>::remove((collection.id, owner.as_sub()));
+ } else {
+ <Balance<T>>::insert((collection.id, owner.as_sub()), balance);
+ }
+ <TotalSupply<T>>::insert(collection.id, total_supply);
+
+ collection.log_infallible(ERC20Events::Transfer {
+ from: *owner.as_eth(),
+ to: H160::default(),
+ value: amount.into(),
+ });
+ <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
+ collection.id,
+ TokenId::default(),
+ owner.clone(),
+ amount,
+ ));
+ Ok(())
+ }
+
+ pub fn transfer(
+ collection: &FungibleHandle<T>,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ amount: u128,
+ ) -> DispatchResult {
+ ensure!(
+ collection.transfers_enabled,
+ <CommonError<T>>::TransferNotAllowed
+ );
+
+ if collection.access == AccessMode::WhiteList {
+ collection.check_allowlist(from)?;
+ collection.check_allowlist(to)?;
+ }
+ <PalletCommon<T>>::ensure_correct_receiver(to)?;
+
+ let balance_from = <Balance<T>>::get((collection.id, from.as_sub()))
+ .checked_sub(amount)
+ .ok_or(<CommonError<T>>::TokenValueTooLow)?;
+ let balance_to = if from != to {
+ Some(
+ <Balance<T>>::get((collection.id, to.as_sub()))
+ .checked_add(amount)
+ .ok_or(ArithmeticError::Overflow)?,
+ )
+ } else {
+ None
+ };
+
+ collection.consume_sstore()?;
+ collection.consume_sstore()?;
+ collection.consume_log(2, 32)?;
+ collection.consume_sstore()?;
+
+ // =========
+
+ if let Some(balance_to) = balance_to {
+ // from != to
+ if balance_from == 0 {
+ <Balance<T>>::remove((collection.id, from.as_sub()));
+ } else {
+ <Balance<T>>::insert((collection.id, from.as_sub()), balance_from);
+ }
+ <Balance<T>>::insert((collection.id, to.as_sub()), balance_to);
+ }
+
+ collection.log_infallible(ERC20Events::Transfer {
+ from: *from.as_eth(),
+ to: *to.as_eth(),
+ value: amount.into(),
+ });
+ <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(
+ collection.id,
+ TokenId::default(),
+ from.clone(),
+ to.clone(),
+ amount,
+ ));
+ Ok(())
+ }
+
+ pub fn create_multiple_items(
+ collection: &FungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ data: Vec<CreateItemData<T>>,
+ ) -> DispatchResult {
+ let unrestricted_minting = collection.is_owner_or_admin(sender)?;
+ if !unrestricted_minting {
+ ensure!(
+ collection.mint_mode,
+ <CommonError<T>>::PublicMintingNotAllowed
+ );
+ collection.check_allowlist(sender)?;
+
+ for (owner, _) in data.iter() {
+ collection.check_allowlist(owner)?;
+ }
+ }
+
+ let mut balances = BTreeMap::new();
+
+ let total_supply = data
+ .iter()
+ .map(|u| u.1)
+ .try_fold(0u128, |acc, v| acc.checked_add(v))
+ .ok_or(ArithmeticError::Overflow)?;
+
+ for (user, amount) in data.into_iter() {
+ collection.consume_sload()?;
+ let balance = balances
+ .entry(user.clone())
+ .or_insert_with(|| <Balance<T>>::get((collection.id, user.as_sub())));
+ *balance = (*balance)
+ .checked_add(amount)
+ .ok_or(ArithmeticError::Overflow)?;
+ }
+
+ collection.consume_sstore()?;
+ for _ in &balances {
+ collection.consume_sstore()?;
+ collection.consume_log(2, 32)?;
+ collection.consume_sstore()?;
+ }
+
+ // =========
+
+ <TotalSupply<T>>::insert(collection.id, total_supply);
+ for (user, amount) in balances {
+ <Balance<T>>::insert((collection.id, user.as_sub()), amount);
+
+ collection.log_infallible(ERC20Events::Transfer {
+ from: H160::default(),
+ to: *user.as_eth(),
+ value: amount.into(),
+ });
+ <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
+ collection.id,
+ TokenId::default(),
+ user.clone(),
+ amount,
+ ));
+ }
+
+ Ok(())
+ }
+
+ fn set_allowance_unchecked(
+ collection: &FungibleHandle<T>,
+ owner: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
+ amount: u128,
+ ) {
+ <Allowance<T>>::insert((collection.id, owner.as_sub(), spender.as_sub()), amount);
+
+ collection.log_infallible(ERC20Events::Approval {
+ owner: *owner.as_eth(),
+ spender: *spender.as_eth(),
+ value: amount.into(),
+ });
+ <PalletCommon<T>>::deposit_event(CommonEvent::Approved(
+ collection.id,
+ TokenId(0),
+ owner.clone(),
+ spender.clone(),
+ amount,
+ ));
+ }
+
+ pub fn set_allowance(
+ collection: &FungibleHandle<T>,
+ owner: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
+ amount: u128,
+ ) -> DispatchResult {
+ if collection.access == AccessMode::WhiteList {
+ collection.check_allowlist(&owner)?;
+ collection.check_allowlist(&spender)?;
+ }
+
+ if <Balance<T>>::get((collection.id, owner.as_sub())) < amount {
+ ensure!(
+ collection.ignores_owned_amount(owner)?,
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, owner, spender, amount);
+ Ok(())
+ }
+
+ pub fn transfer_from(
+ collection: &FungibleHandle<T>,
+ spender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ amount: u128,
+ ) -> DispatchResult {
+ if spender == from {
+ return Self::transfer(collection, from, to, amount);
+ }
+ if collection.access == AccessMode::WhiteList {
+ // `from`, `to` checked in [`transfer`]
+ collection.check_allowlist(spender)?;
+ }
+
+ let allowance = <Allowance<T>>::get((collection.id, from.as_sub(), spender.as_sub()))
+ .checked_sub(amount);
+ if allowance.is_none() {
+ ensure!(
+ collection.ignores_allowance(spender)?,
+ <CommonError<T>>::TokenValueNotEnough
+ );
+ }
+
+ // =========
+
+ Self::transfer(collection, from, to, amount)?;
+ if let Some(allowance) = allowance {
+ Self::set_allowance_unchecked(collection, from, spender, allowance);
+ }
+ Ok(())
+ }
+
+ pub fn burn_from(
+ collection: &FungibleHandle<T>,
+ spender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ amount: u128,
+ ) -> DispatchResult {
+ if spender == from {
+ return Self::burn(collection, from, amount);
+ }
+ if collection.access == AccessMode::WhiteList {
+ // `from` checked in [`burn`]
+ collection.check_allowlist(spender)?;
+ }
+
+ let allowance = <Allowance<T>>::get((collection.id, from.as_sub(), spender.as_sub()))
+ .checked_sub(amount);
+ if allowance.is_none() {
+ ensure!(
+ collection.ignores_allowance(spender)?,
+ <CommonError<T>>::TokenValueNotEnough
+ );
+ }
+
+ // =========
+
+ Self::burn(collection, from, amount)?;
+ if let Some(allowance) = allowance {
+ Self::set_allowance_unchecked(collection, from, spender, allowance);
+ }
+ Ok(())
+ }
+
+ /// Delegated to `create_multiple_items`
+ pub fn create_item(
+ collection: &FungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ data: CreateItemData<T>,
+ ) -> DispatchResult {
+ Self::create_multiple_items(collection, sender, vec![data])
+ }
+}
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- /dev/null
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+// Common stubs holder
+contract Dummy {
+ uint8 dummy;
+ string stub_error = "this contract is implemented in native";
+}
+
+contract ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID)
+ external
+ view
+ returns (bool)
+ {
+ require(false, stub_error);
+ interfaceID;
+ return true;
+ }
+}
+
+// Inline
+contract ERC20Events {
+ event Transfer(address indexed from, address indexed to, uint256 value);
+ event Approval(
+ address indexed owner,
+ address indexed spender,
+ uint256 value
+ );
+}
+
+contract ERC20 is Dummy, ERC165, ERC20Events {
+ // Selector: name() 06fdde03
+ function name() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ // Selector: symbol() 95d89b41
+ function symbol() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ // Selector: totalSupply() 18160ddd
+ function totalSupply() public view returns (uint256) {
+ require(false, stub_error);
+ dummy;
+ return 0;
+ }
+
+ // Selector: decimals() 313ce567
+ function decimals() public view returns (uint8) {
+ require(false, stub_error);
+ dummy;
+ return 0;
+ }
+
+ // Selector: balanceOf(address) 70a08231
+ function balanceOf(address owner) public view returns (uint256) {
+ require(false, stub_error);
+ owner;
+ dummy;
+ return 0;
+ }
+
+ // Selector: transfer(address,uint256) a9059cbb
+ function transfer(address to, uint256 amount) public returns (bool) {
+ require(false, stub_error);
+ to;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: transferFrom(address,address,uint256) 23b872dd
+ function transferFrom(
+ address from,
+ address to,
+ uint256 amount
+ ) public returns (bool) {
+ require(false, stub_error);
+ from;
+ to;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: approve(address,uint256) 095ea7b3
+ function approve(address spender, uint256 amount) public returns (bool) {
+ require(false, stub_error);
+ spender;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: allowance(address,address) dd62ed3e
+ function allowance(address owner, address spender)
+ public
+ view
+ returns (uint256)
+ {
+ require(false, stub_error);
+ owner;
+ spender;
+ dummy;
+ return 0;
+ }
+}
+
+contract UniqueFungible is Dummy, ERC165, ERC20 {}
pallets/fungible/src/weights.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/fungible/src/weights.rs
@@ -0,0 +1,116 @@
+// Template adopted from https://github.com/paritytech/substrate/blob/master/.maintain/frame-weight-template.hbs
+
+//! Autogenerated weights for pallet_fungible
+//!
+//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
+//! DATE: 2021-10-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 128
+
+// Executed Command:
+// target/release/nft
+// benchmark
+// --pallet
+// pallet-fungible
+// --wasm-execution
+// compiled
+// --extrinsic
+// *
+// --template
+// .maintain/frame-weight-template.hbs
+// --steps=50
+// --repeat=20
+// --output=./pallets/fungible/src/weights.rs
+
+
+#![cfg_attr(rustfmt, rustfmt_skip)]
+#![allow(unused_parens)]
+#![allow(unused_imports)]
+
+use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
+use sp_std::marker::PhantomData;
+
+/// Weight functions needed for pallet_fungible.
+pub trait WeightInfo {
+ fn create_item() -> Weight;
+ fn burn_item() -> Weight;
+ fn transfer() -> Weight;
+ fn approve() -> Weight;
+ fn transfer_from() -> Weight;
+}
+
+/// Weights for pallet_fungible using the Substrate node and recommended hardware.
+pub struct SubstrateWeight<T>(PhantomData<T>);
+impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
+ // Storage: Fungible Balance (r:1 w:1)
+ // Storage: Fungible TotalSupply (r:0 w:1)
+ fn create_item() -> Weight {
+ (12_069_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Fungible TotalSupply (r:1 w:1)
+ // Storage: Fungible Balance (r:1 w:1)
+ fn burn_item() -> Weight {
+ (14_096_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Fungible Balance (r:2 w:2)
+ fn transfer() -> Weight {
+ (15_436_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Fungible Balance (r:1 w:0)
+ // Storage: Fungible Allowance (r:0 w:1)
+ fn approve() -> Weight {
+ (12_867_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Fungible Allowance (r:1 w:1)
+ // Storage: Fungible Balance (r:2 w:2)
+ fn transfer_from() -> Weight {
+ (21_462_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(3 as Weight))
+ .saturating_add(T::DbWeight::get().writes(3 as Weight))
+ }
+}
+
+// For backwards compatibility and tests
+impl WeightInfo for () {
+ // Storage: Fungible Balance (r:1 w:1)
+ // Storage: Fungible TotalSupply (r:0 w:1)
+ fn create_item() -> Weight {
+ (12_069_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Fungible TotalSupply (r:1 w:1)
+ // Storage: Fungible Balance (r:1 w:1)
+ fn burn_item() -> Weight {
+ (14_096_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Fungible Balance (r:2 w:2)
+ fn transfer() -> Weight {
+ (15_436_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Fungible Balance (r:1 w:0)
+ // Storage: Fungible Allowance (r:0 w:1)
+ fn approve() -> Weight {
+ (12_867_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Fungible Allowance (r:1 w:1)
+ // Storage: Fungible Balance (r:2 w:2)
+ fn transfer_from() -> Weight {
+ (21_462_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(3 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(3 as Weight))
+ }
+}
pallets/inflation/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/inflation/src/benchmarking.rs
+++ b/pallets/inflation/src/benchmarking.rs
@@ -3,8 +3,6 @@
use super::*;
use crate::Module as Inflation;
-use sp_std::prelude::*;
-use frame_system::RawOrigin;
use frame_benchmarking::{benchmarks};
use frame_support::traits::OnInitialize;
pallets/nft/Cargo.tomldiffbeforeafterboth--- a/pallets/nft/Cargo.toml
+++ b/pallets/nft/Cargo.toml
@@ -16,7 +16,7 @@
[features]
default = ['std']
-runtime-benchmarks = ['frame-benchmarking']
+runtime-benchmarks = ['frame-benchmarking', 'pallet-common/runtime-benchmarks']
std = [
'codec/std',
'serde/std',
@@ -27,6 +27,10 @@
'pallet-timestamp/std',
'pallet-randomness-collective-flip/std',
'pallet-transaction-payment/std',
+ 'pallet-common/std',
+ 'pallet-fungible/std',
+ 'pallet-nonfungible/std',
+ 'pallet-refungible/std',
'fp-evm/std',
'nft-data-structs/std',
'up-sponsorship/std',
@@ -129,7 +133,9 @@
[dependencies]
-scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
+scale-info = { version = "1.0.0", default-features = false, features = [
+ "derive",
+] }
ethereum = { version = "0.9", git = "https://github.com/purestake/ethereum", branch = "joshy-scale-info", default-features = false }
rlp = { default-features = false, version = "0.5.0" }
sp-api = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.12" }
@@ -144,3 +150,8 @@
pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
hex-literal = "0.3.3"
+
+pallet-common = { default-features = false, path = "../common" }
+pallet-fungible = { default-features = false, path = "../fungible" }
+pallet-nonfungible = { default-features = false, path = "../nonfungible" }
+pallet-refungible = { default-features = false, path = "../refungible" }
pallets/nft/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nft/src/benchmarking.rs
+++ b/pallets/nft/src/benchmarking.rs
@@ -7,35 +7,10 @@
use nft_data_structs::*;
use core::convert::TryInto;
use sp_runtime::DispatchError;
+use pallet_common::benchmarking::{create_data, create_u16_data};
const SEED: u32 = 1;
-
-fn create_data(size: usize) -> Vec<u8> {
- (0..size).map(|v| (v & 0xff) as u8).collect()
-}
-fn create_u16_data(size: usize) -> Vec<u16> {
- (0..size).map(|v| (v & 0xffff) as u16).collect()
-}
-
-fn default_nft_data() -> CreateItemData {
- CreateItemData::NFT(CreateNftData {
- const_data: create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap(),
- variable_data: create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap(),
- })
-}
-fn default_fungible_data() -> CreateItemData {
- CreateItemData::Fungible(CreateFungibleData { value: 1000 })
-}
-
-fn default_re_fungible_data() -> CreateItemData {
- CreateItemData::ReFungible(CreateReFungibleData {
- const_data: create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap(),
- variable_data: create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap(),
- pieces: 1000,
- })
-}
-
fn create_collection_helper<T: Config>(
owner: T::AccountId,
mode: CollectionMode,
@@ -55,20 +30,10 @@
token_prefix,
mode,
)?;
- Ok(CreatedCollectionCount::get())
+ Ok(<pallet_common::CreatedCollectionCount<T>>::get())
}
fn create_nft_collection<T: Config>(owner: T::AccountId) -> Result<CollectionId, DispatchError> {
create_collection_helper::<T>(owner, CollectionMode::NFT)
-}
-fn create_fungible_collection<T: Config>(
- owner: T::AccountId,
-) -> Result<CollectionId, DispatchError> {
- create_collection_helper::<T>(owner, CollectionMode::Fungible(0))
-}
-fn create_refungible_collection<T: Config>(
- owner: T::AccountId,
-) -> Result<CollectionId, DispatchError> {
- create_collection_helper::<T>(owner, CollectionMode::ReFungible)
}
benchmarks! {
@@ -82,7 +47,7 @@
T::Currency::deposit_creating(&caller, T::CollectionCreationPrice::get());
}: _(RawOrigin::Signed(caller.clone()), col_name.clone(), col_desc.clone(), token_prefix.clone(), mode)
verify {
- assert_eq!(<Pallet<T>>::collection_id(2).unwrap().owner, caller);
+ assert_eq!(<pallet_common::CollectionById<T>>::get(CollectionId(1)).unwrap().owner, caller);
}
destroy_collection {
@@ -129,7 +94,7 @@
let caller: T::AccountId = account("caller", 0, SEED);
let collection = create_nft_collection::<T>(caller.clone())?;
let new_admin: T::AccountId = account("admin", 0, SEED);
- <Pallet<T>>::add_collection_admin(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(new_admin.clone()))?;
+ <Pallet<T>>::add_collection_admin(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(new_admin.clone()))?;
}: _(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(new_admin))
set_collection_sponsor {
@@ -140,152 +105,21 @@
confirm_sponsorship {
let caller: T::AccountId = account("caller", 0, SEED);
let collection = create_nft_collection::<T>(caller.clone())?;
- <Pallet<T>>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone())?;
+ <Pallet<T>>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), collection, caller.clone())?;
}: _(RawOrigin::Signed(caller.clone()), collection)
remove_collection_sponsor {
let caller: T::AccountId = account("caller", 0, SEED);
let collection = create_nft_collection::<T>(caller.clone())?;
- <Pallet<T>>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone())?;
- <Pallet<T>>::confirm_sponsorship(RawOrigin::Signed(caller.clone()).into(), 2)?;
+ <Pallet<T>>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), collection, caller.clone())?;
+ <Pallet<T>>::confirm_sponsorship(RawOrigin::Signed(caller.clone()).into(), collection)?;
}: _(RawOrigin::Signed(caller.clone()), collection)
-
- // nft item
- create_item_nft {
- let b in 0..(CUSTOM_DATA_LIMIT * 2);
-
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- let data = CreateItemData::NFT(CreateNftData {
- const_data: create_data(b.min(CUSTOM_DATA_LIMIT) as usize).try_into().unwrap(),
- variable_data: create_data(b.saturating_sub(CUSTOM_DATA_LIMIT) as usize).try_into().unwrap(),
- });
- }: create_item(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
-
- create_multiple_items_nft {
- // TODO: Take item data size into account. As create_item_nft bench shows, this parameter has no effect on execution time,
- // but it may if we increase CUSTOM_DATA_LIMIT
- let b in 1..1000;
-
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- let data = (0..b).map(|_| default_nft_data()).collect();
- }: create_multiple_items(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
- // fungible item
- create_item_fungible {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_fungible_collection::<T>(caller.clone())?;
- let data = CreateItemData::Fungible(CreateFungibleData {
- value: 1000,
- });
- }: create_item(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
-
- create_multiple_items_fungible {
- let b in 1..1000;
-
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_fungible_collection::<T>(caller.clone())?;
- let data = (0..b).map(|_| default_fungible_data()).collect();
- }: create_multiple_items(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
-
- // refungible item
- create_item_refungible {
- let b in 0..(CUSTOM_DATA_LIMIT * 2);
-
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_refungible_collection::<T>(caller.clone())?;
- let data = CreateItemData::ReFungible(CreateReFungibleData {
- const_data: create_data(b.min(CUSTOM_DATA_LIMIT) as usize).try_into().unwrap(),
- variable_data: create_data(b.saturating_sub(CUSTOM_DATA_LIMIT) as usize).try_into().unwrap(),
- pieces: 1000,
- });
- }: create_item(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
-
- create_multiple_items_refungible {
- // TODO: Take item data size into account. As create_item_nft bench shows, this parameter has no effect on execution time,
- // but it may if we increase CUSTOM_DATA_LIMIT
- let b in 1..1000;
-
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_refungible_collection::<T>(caller.clone())?;
- let data = (0..b).map(|_| default_re_fungible_data()).collect();
- }: create_multiple_items(RawOrigin::Signed(caller.clone()), collection, T::CrossAccountId::from_sub(caller.clone()), data)
-
- burn_item_nft {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- let data = default_nft_data();
- <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(caller.clone()), data)?;
- }: burn_item(RawOrigin::Signed(caller.clone()), collection, 1, 1)
-
- transfer_nft {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- let recipient: T::AccountId = account("recipient", 0, SEED);
- let data = default_nft_data();
- <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(caller.clone()), data)?;
- }: transfer(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), collection, 1, 1)
-
- transfer_fungible {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_fungible_collection::<T>(caller.clone())?;
- let recipient: T::AccountId = account("recipient", 0, SEED);
- let data = default_fungible_data();
- <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(caller.clone()), data)?;
- }: transfer(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), collection, 1, 1)
-
- transfer_refungible {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_refungible_collection::<T>(caller.clone())?;
- let recipient: T::AccountId = account("recipient", 0, SEED);
- let data = default_re_fungible_data();
- <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), collection, T::CrossAccountId::from_sub(caller.clone()), data)?;
- }: transfer(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), collection, 1, 1)
-
set_transfers_enabled_flag {
let caller: T::AccountId = account("caller", 0, SEED);
let collection = create_nft_collection::<T>(caller.clone())?;
}: _(RawOrigin::Signed(caller.clone()), collection, false)
-
- approve_nft {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- let recipient: T::AccountId = account("recipient", 0, SEED);
- let data = default_nft_data();
- <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(caller.clone()), data)?;
- }: approve(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), collection, 1, 1)
- // Nft
- transfer_from_nft {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- let recipient: T::AccountId = account("recipient", 0, SEED);
- let data = default_nft_data();
- <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(caller.clone()), data)?;
- <Pallet<T>>::approve(RawOrigin::Signed(caller.clone()).into(), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)?;
- }: transfer_from(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)
-
- // Fungible
- transfer_from_fungible {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_fungible_collection::<T>(caller.clone())?;
- let recipient: T::AccountId = account("recipient", 0, SEED);
- let data = default_fungible_data();
- <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(caller.clone()), data)?;
- <Pallet<T>>::approve(RawOrigin::Signed(caller.clone()).into(), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)?;
- }: transfer_from(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)
-
- // ReFungible
- transfer_from_refungible {
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_refungible_collection::<T>(caller.clone())?;
- let recipient: T::AccountId = account("recipient", 0, SEED);
- let data = default_re_fungible_data();
- <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(caller.clone()), data)?;
- <Pallet<T>>::approve(RawOrigin::Signed(caller.clone()).into(), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)?;
- }: transfer_from(RawOrigin::Signed(caller.clone()), T::CrossAccountId::from_sub(caller.clone()), T::CrossAccountId::from_sub(recipient.clone()), 2, 1, 1)
-
set_offchain_schema {
let b in 0..OFFCHAIN_SCHEMA_LIMIT;
@@ -308,29 +142,19 @@
let caller: T::AccountId = account("caller", 0, SEED);
let collection = create_nft_collection::<T>(caller.clone())?;
let data = create_data(b as usize);
- }: set_variable_on_chain_schema(RawOrigin::Signed(caller.clone()), 2, data)
-
- set_variable_meta_data_nft {
- let b in 0..CUSTOM_DATA_LIMIT;
-
- let caller: T::AccountId = account("caller", 0, SEED);
- let collection = create_nft_collection::<T>(caller.clone())?;
- let data = default_nft_data();
- <Pallet<T>>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, T::CrossAccountId::from_sub(caller.clone()), data)?;
- let data = create_data(b as usize);
- }: set_variable_meta_data(RawOrigin::Signed(caller.clone()), collection, 1, data)
+ }: set_variable_on_chain_schema(RawOrigin::Signed(caller.clone()), collection, data)
set_schema_version {
let caller: T::AccountId = account("caller", 0, SEED);
let collection = create_nft_collection::<T>(caller.clone())?;
- }: set_schema_version(RawOrigin::Signed(caller.clone()), 2, SchemaVersion::Unique)
+ }: set_schema_version(RawOrigin::Signed(caller.clone()), collection, SchemaVersion::Unique)
set_collection_limits{
let caller: T::AccountId = account("caller", 0, SEED);
let collection = create_nft_collection::<T>(caller.clone())?;
let cl = CollectionLimits {
- account_token_ownership_limit: 0,
+ account_token_ownership_limit: Some(0),
sponsored_data_size: 0,
token_limit: 1,
sponsor_transfer_timeout: 0,
@@ -338,5 +162,10 @@
owner_can_transfer: true,
sponsored_data_rate_limit: None,
};
- }: set_collection_limits(RawOrigin::Signed(caller.clone()), 2, cl)
+ }: set_collection_limits(RawOrigin::Signed(caller.clone()), collection, cl)
+
+ set_meta_update_permission_flag {
+ let caller: T::AccountId = account("caller", 0, SEED);
+ let collection = create_nft_collection::<T>(caller.clone())?;
+ }: _(RawOrigin::Signed(caller.clone()), collection, MetaUpdatePermission::Admin)
}
pallets/nft/src/common.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/nft/src/common.rs
@@ -0,0 +1,52 @@
+use core::marker::PhantomData;
+use frame_support::{weights::Weight};
+use pallet_common::{CommonWeightInfo};
+
+use pallet_fungible::{common::CommonWeights as FungibleWeights};
+use pallet_nonfungible::{common::CommonWeights as NonfungibleWeights};
+use pallet_refungible::{common::CommonWeights as RefungibleWeights};
+
+use crate::{Config, dispatch::dispatch_weight};
+
+macro_rules! max_weight_of {
+ ($method:ident ( $($args:tt)* )) => {
+ <FungibleWeights<T>>::$method($($args)*)
+ .max(<NonfungibleWeights<T>>::$method($($args)*))
+ .max(<RefungibleWeights<T>>::$method($($args)*))
+ };
+}
+
+pub struct CommonWeights<T: Config>(PhantomData<T>);
+impl<T: Config> CommonWeightInfo for CommonWeights<T> {
+ fn create_item() -> nft_data_structs::Weight {
+ dispatch_weight::<T>() + max_weight_of!(create_item())
+ }
+
+ fn create_multiple_items(amount: u32) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(create_multiple_items(amount))
+ }
+
+ fn burn_item() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(burn_item())
+ }
+
+ fn transfer() -> nft_data_structs::Weight {
+ dispatch_weight::<T>() + max_weight_of!(transfer())
+ }
+
+ fn approve() -> nft_data_structs::Weight {
+ dispatch_weight::<T>() + max_weight_of!(approve())
+ }
+
+ fn transfer_from() -> nft_data_structs::Weight {
+ dispatch_weight::<T>() + max_weight_of!(transfer_from())
+ }
+
+ fn set_variable_metadata(bytes: u32) -> nft_data_structs::Weight {
+ dispatch_weight::<T>() + max_weight_of!(set_variable_metadata(bytes))
+ }
+
+ fn burn_from() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(burn_from())
+ }
+}
pallets/nft/src/dispatch.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/nft/src/dispatch.rs
@@ -0,0 +1,92 @@
+use frame_support::{
+ dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},
+ traits::Get,
+ weights::Weight,
+};
+use nft_data_structs::{CollectionId, CollectionMode, Pays, PostDispatchInfo};
+use pallet_common::{CollectionHandle, CommonCollectionOperations};
+use pallet_fungible::FungibleHandle;
+use pallet_nonfungible::NonfungibleHandle;
+use pallet_refungible::RefungibleHandle;
+
+use crate::Config;
+
+// TODO: move to benchmarking
+/// Price of [`dispatch_call`] call with noop `call` argument
+pub fn dispatch_weight<T: Config>() -> Weight {
+ // Read collection
+ <T as frame_system::Config>::DbWeight::get().reads(1)
+ // Dynamic dispatch?
+ + 6_000_000
+ // submit_logs is measured as part of collection pallets
+}
+
+pub enum Dispatched<T: Config> {
+ Fungible(FungibleHandle<T>),
+ Nonfungible(NonfungibleHandle<T>),
+ Refungible(RefungibleHandle<T>),
+}
+impl<T: Config> Dispatched<T> {
+ pub fn dispatch(handle: CollectionHandle<T>) -> Self {
+ match handle.mode {
+ CollectionMode::Fungible(_) => Self::Fungible(FungibleHandle::cast(handle)),
+ CollectionMode::NFT => Self::Nonfungible(NonfungibleHandle::cast(handle)),
+ CollectionMode::ReFungible => Self::Refungible(RefungibleHandle::cast(handle)),
+ }
+ }
+ fn into_inner(self) -> CollectionHandle<T> {
+ match self {
+ Dispatched::Fungible(f) => f.into_inner(),
+ Dispatched::Nonfungible(f) => f.into_inner(),
+ Dispatched::Refungible(f) => f.into_inner(),
+ }
+ }
+ pub fn as_dyn(&self) -> &dyn CommonCollectionOperations<T> {
+ match self {
+ Dispatched::Fungible(h) => h,
+ Dispatched::Nonfungible(h) => h,
+ Dispatched::Refungible(h) => h,
+ }
+ }
+}
+
+/// Helper function to implement substrate calls for common collection methods
+pub fn dispatch_call<
+ T: Config,
+ C: FnOnce(&dyn pallet_common::CommonCollectionOperations<T>) -> DispatchResultWithPostInfo,
+>(
+ collection: CollectionId,
+ call: C,
+) -> DispatchResultWithPostInfo {
+ let handle =
+ CollectionHandle::try_get(collection).map_err(|error| DispatchErrorWithPostInfo {
+ post_info: PostDispatchInfo {
+ actual_weight: Some(dispatch_weight::<T>()),
+ pays_fee: Pays::Yes,
+ },
+ error,
+ })?;
+ let dispatched = Dispatched::dispatch(handle);
+ let mut result = call(dispatched.as_dyn());
+ match &mut result {
+ Ok(PostDispatchInfo {
+ actual_weight: Some(weight),
+ ..
+ })
+ | Err(DispatchErrorWithPostInfo {
+ post_info: PostDispatchInfo {
+ actual_weight: Some(weight),
+ ..
+ },
+ ..
+ }) => *weight += dispatch_weight::<T>(),
+ _ => {}
+ }
+
+ // TODO: Make submit_logs infallible, but it shouldn't fail here anyway
+ dispatched
+ .into_inner()
+ .submit_logs()
+ .expect("should succeed");
+ result
+}
pallets/nft/src/eth/account.rsdiffbeforeafterboth--- a/pallets/nft/src/eth/account.rs
+++ /dev/null
@@ -1,168 +0,0 @@
-use crate::Config;
-use codec::{Encode, EncodeLike, Decode};
-use scale_info::build::{FieldsBuilder, UnnamedFields, Variants};
-use scale_info::{Path, Type, TypeInfo};
-use sp_core::crypto::AccountId32;
-use primitive_types::H160;
-use core::cmp::Ordering;
-use serde::{Serialize, Deserialize};
-use pallet_evm::AddressMapping;
-use sp_std::vec::Vec;
-use sp_std::clone::Clone;
-
-pub trait CrossAccountId<AccountId>:
- Encode + EncodeLike + Decode + TypeInfo + Clone + PartialEq + Ord + core::fmt::Debug
-// +
-// Serialize + Deserialize<'static>
-{
- fn as_sub(&self) -> &AccountId;
- fn as_eth(&self) -> &H160;
-
- fn from_sub(account: AccountId) -> Self;
- fn from_eth(account: H160) -> Self;
-}
-
-#[derive(Eq, Serialize, Deserialize)]
-pub struct BasicCrossAccountId<T: Config> {
- /// If true - then ethereum is canonical encoding
- from_ethereum: bool,
- substrate: T::AccountId,
- ethereum: H160,
-}
-
-impl<T: Config> TypeInfo for BasicCrossAccountId<T> {
- type Identity = Self;
-
- fn type_info() -> Type {
- Type::builder()
- .path(Path::new("BasicCrossAccountId", "pallet_nft::eth::account"))
- // At runtime side this type has no type parameters, as AccountId is inlined?
- // .type_params([TypeParameter::new(
- // "AccountId",
- // Some(scale_info::meta_type::<T::AccountId>()),
- // )])
- .variant(
- Variants::new()
- .variant("Substrate", |t| {
- t.fields(
- <FieldsBuilder<UnnamedFields>>::default()
- .field(|f| f.ty::<T::AccountId>()),
- )
- .index(0)
- })
- .variant("Ethereum", |t| {
- t.fields(
- <FieldsBuilder<UnnamedFields>>::default().field(|f| f.ty::<H160>()),
- )
- .index(1)
- }),
- )
- }
-}
-
-impl<T: Config> core::fmt::Debug for BasicCrossAccountId<T> {
- fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
- if self.from_ethereum {
- fmt.debug_tuple("CrossAccountId::Ethereum")
- .field(&self.ethereum)
- .finish()
- } else {
- fmt.debug_tuple("CrossAccountId::Substrate")
- .field(&self.substrate)
- .finish()
- }
- }
-}
-
-impl<T: Config> PartialOrd for BasicCrossAccountId<T> {
- fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
- Some(self.substrate.cmp(&other.substrate))
- }
-}
-
-impl<T: Config> Ord for BasicCrossAccountId<T> {
- fn cmp(&self, other: &Self) -> Ordering {
- self.partial_cmp(other)
- .expect("substrate account is total ordered")
- }
-}
-
-impl<T: Config> PartialEq for BasicCrossAccountId<T> {
- fn eq(&self, other: &Self) -> bool {
- if self.from_ethereum == other.from_ethereum {
- self.substrate == other.substrate && self.ethereum == other.ethereum
- } else if self.from_ethereum {
- // ethereum is canonical encoding, but we need to compare derived address
- self.substrate == other.substrate
- } else {
- self.ethereum == other.ethereum
- }
- }
-}
-impl<T: Config> Clone for BasicCrossAccountId<T> {
- fn clone(&self) -> Self {
- Self {
- from_ethereum: self.from_ethereum,
- substrate: self.substrate.clone(),
- ethereum: self.ethereum,
- }
- }
-}
-impl<T: Config> Encode for BasicCrossAccountId<T> {
- fn encode(&self) -> Vec<u8> {
- let as_result = if !self.from_ethereum {
- Ok(self.substrate.clone())
- } else {
- Err(self.ethereum)
- };
- as_result.encode()
- }
-}
-impl<T: Config> EncodeLike for BasicCrossAccountId<T> {}
-impl<T: Config> Decode for BasicCrossAccountId<T> {
- fn decode<I>(input: &mut I) -> Result<Self, codec::Error>
- where
- I: codec::Input,
- {
- Ok(match <Result<T::AccountId, H160>>::decode(input)? {
- Ok(s) => Self::from_sub(s),
- Err(e) => Self::from_eth(e),
- })
- }
-}
-impl<T: Config> CrossAccountId<T::AccountId> for BasicCrossAccountId<T> {
- fn as_sub(&self) -> &T::AccountId {
- &self.substrate
- }
- fn as_eth(&self) -> &H160 {
- &self.ethereum
- }
- fn from_sub(substrate: T::AccountId) -> Self {
- Self {
- ethereum: T::EvmBackwardsAddressMapping::from_account_id(substrate.clone()),
- substrate,
- from_ethereum: false,
- }
- }
- fn from_eth(ethereum: H160) -> Self {
- Self {
- ethereum,
- substrate: T::EvmAddressMapping::into_account_id(ethereum),
- from_ethereum: true,
- }
- }
-}
-
-pub trait EvmBackwardsAddressMapping<AccountId> {
- fn from_account_id(account_id: AccountId) -> H160;
-}
-
-/// Should have same mapping as EnsureAddressTruncated
-pub struct MapBackwardsAddressTruncated;
-impl EvmBackwardsAddressMapping<AccountId32> for MapBackwardsAddressTruncated {
- fn from_account_id(account_id: AccountId32) -> H160 {
- let mut out = [0; 20];
- out.copy_from_slice(&(account_id.as_ref() as &[u8])[0..20]);
- H160(out)
- }
-}
pallets/nft/src/eth/erc.rsdiffbeforeafterboth--- a/pallets/nft/src/eth/erc.rs
+++ /dev/null
@@ -1,497 +0,0 @@
-use core::char::{decode_utf16, REPLACEMENT_CHARACTER};
-use evm_coder::{ToLog, execution::Result, generate_stubgen, solidity, solidity_interface, types::*};
-use nft_data_structs::{CreateItemData, CreateNftData};
-use core::convert::TryInto;
-use crate::{
- Allowances, Module, Balance, CollectionHandle, CollectionMode, Config, NftItemList,
- ItemListIndex,
-};
-use frame_support::storage::{StorageMap, StorageDoubleMap};
-use pallet_evm::AddressMapping;
-use pallet_evm_coder_substrate::dispatch_to_evm;
-use super::account::CrossAccountId;
-use sp_std::{vec, vec::Vec};
-
-#[solidity_interface(name = "ERC165")]
-impl<T: Config> CollectionHandle<T> {
- fn supports_interface(&self, interface_id: bytes4) -> Result<bool> {
- Ok(match self.mode {
- CollectionMode::Fungible(_) => UniqueFungibleCall::supports_interface(interface_id),
- CollectionMode::NFT => UniqueNFTCall::supports_interface(interface_id),
- _ => false,
- })
- }
-}
-
-#[solidity_interface(name = "InlineNameSymbol")]
-impl<T: Config> CollectionHandle<T> {
- fn name(&self) -> Result<string> {
- Ok(decode_utf16(self.name.iter().copied())
- .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
- .collect::<string>())
- }
-
- fn symbol(&self) -> Result<string> {
- Ok(string::from_utf8_lossy(&self.token_prefix).into())
- }
-}
-
-#[solidity_interface(name = "InlineTotalSupply")]
-impl<T: Config> CollectionHandle<T> {
- fn total_supply(&self) -> Result<uint256> {
- // TODO: we do not track total amount of all tokens
- Ok(0.into())
- }
-}
-
-#[solidity_interface(name = "ERC721Metadata", inline_is(InlineNameSymbol))]
-impl<T: Config> CollectionHandle<T> {
- #[solidity(rename_selector = "tokenURI")]
- fn token_uri(&self, token_id: uint256) -> Result<string> {
- let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
- Ok(string::from_utf8_lossy(
- &<NftItemList<T>>::get(self.id, token_id)
- .ok_or("token not found")?
- .const_data,
- )
- .into())
- }
-}
-
-#[solidity_interface(name = "ERC721Enumerable", inline_is(InlineTotalSupply))]
-impl<T: Config> CollectionHandle<T> {
- fn token_by_index(&self, index: uint256) -> Result<uint256> {
- Ok(index)
- }
-
- fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {
- // TODO: Not implemetable
- Err("not implemented".into())
- }
-}
-
-#[derive(ToLog)]
-pub enum ERC721Events {
- Transfer {
- #[indexed]
- from: address,
- #[indexed]
- to: address,
- #[indexed]
- token_id: uint256,
- },
- Approval {
- #[indexed]
- owner: address,
- #[indexed]
- approved: address,
- #[indexed]
- token_id: uint256,
- },
- #[allow(dead_code)]
- ApprovalForAll {
- #[indexed]
- owner: address,
- #[indexed]
- operator: address,
- approved: bool,
- },
-}
-
-#[solidity_interface(name = "ERC721", is(ERC165), events(ERC721Events))]
-impl<T: Config> CollectionHandle<T> {
- #[solidity(rename_selector = "balanceOf")]
- fn balance_of_nft(&self, owner: address) -> Result<uint256> {
- let owner = T::EvmAddressMapping::into_account_id(owner);
- let balance = <Balance<T>>::get(self.id, owner);
- Ok(balance.into())
- }
- fn owner_of(&self, token_id: uint256) -> Result<address> {
- let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
- let token = <NftItemList<T>>::get(self.id, token_id).ok_or("unknown token")?;
- Ok(*token.owner.as_eth())
- }
- fn safe_transfer_from_with_data(
- &mut self,
- _from: address,
- _to: address,
- _token_id: uint256,
- _data: bytes,
- _value: value,
- ) -> Result<void> {
- // TODO: Not implemetable
- Err("not implemented".into())
- }
- fn safe_transfer_from(
- &mut self,
- _from: address,
- _to: address,
- _token_id: uint256,
- _value: value,
- ) -> Result<void> {
- // TODO: Not implemetable
- Err("not implemented".into())
- }
-
- fn transfer_from(
- &mut self,
- caller: caller,
- from: address,
- to: address,
- token_id: uint256,
- _value: value,
- ) -> Result<void> {
- let caller = T::CrossAccountId::from_eth(caller);
- let from = T::CrossAccountId::from_eth(from);
- let to = T::CrossAccountId::from_eth(to);
- let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;
-
- <Module<T>>::transfer_from_internal(&caller, &from, &to, self, token_id, 1)
- .map_err(|_| "transferFrom error")?;
- Ok(())
- }
-
- fn approve(
- &mut self,
- caller: caller,
- approved: address,
- token_id: uint256,
- _value: value,
- ) -> Result<void> {
- let caller = T::CrossAccountId::from_eth(caller);
- let approved = T::CrossAccountId::from_eth(approved);
- let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;
-
- <Module<T>>::approve_internal(&caller, &approved, self, token_id, 1)
- .map_err(|_| "approve internal")?;
- Ok(())
- }
-
- fn set_approval_for_all(
- &mut self,
- _caller: caller,
- _operator: address,
- _approved: bool,
- ) -> Result<void> {
- // TODO: Not implemetable
- Err("not implemented".into())
- }
-
- fn get_approved(&self, _token_id: uint256) -> Result<address> {
- // TODO: Not implemetable
- Err("not implemented".into())
- }
-
- fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {
- // TODO: Not implemetable
- Err("not implemented".into())
- }
-}
-
-#[solidity_interface(name = "ERC721Burnable")]
-impl<T: Config> CollectionHandle<T> {
- fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {
- let caller = T::CrossAccountId::from_eth(caller);
- let token_id = token_id.try_into().map_err(|_| "amount overflow")?;
-
- <Module<T>>::burn_item_internal(&caller, &self, token_id, 1, true)
- .map_err(|_| "burn error")?;
- Ok(())
- }
-}
-
-#[derive(ToLog)]
-pub enum ERC721MintableEvents {
- #[allow(dead_code)]
- MintingFinished {},
-}
-
-#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]
-impl<T: Config> CollectionHandle<T> {
- fn minting_finished(&self) -> Result<bool> {
- Ok(false)
- }
-
- fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
- let caller = T::CrossAccountId::from_eth(caller);
- let to = T::CrossAccountId::from_eth(to);
- let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;
- if <ItemListIndex>::get(self.id)
- .checked_add(1)
- .ok_or("item id overflow")?
- != token_id
- {
- return Err("item id should be next".into());
- }
-
- <Module<T>>::create_item_internal(
- &caller,
- &self,
- &to,
- CreateItemData::NFT(CreateNftData {
- const_data: vec![].try_into().unwrap(),
- variable_data: vec![].try_into().unwrap(),
- }),
- )
- .map_err(|_| "mint error")?;
- Ok(true)
- }
-
- #[solidity(rename_selector = "mintWithTokenURI")]
- fn mint_with_token_uri(
- &mut self,
- caller: caller,
- to: address,
- token_id: uint256,
- token_uri: string,
- ) -> Result<bool> {
- let caller = T::CrossAccountId::from_eth(caller);
- let to = T::CrossAccountId::from_eth(to);
- let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;
- if <ItemListIndex>::get(self.id)
- .checked_add(1)
- .ok_or("item id overflow")?
- != token_id
- {
- return Err("item id should be next".into());
- }
-
- <Module<T>>::create_item_internal(
- &caller,
- &self,
- &to,
- CreateItemData::NFT(CreateNftData {
- const_data: Vec::<u8>::from(token_uri)
- .try_into()
- .map_err(|_| "token uri is too long")?,
- variable_data: vec![].try_into().unwrap(),
- }),
- )
- .map_err(|_| "mint error")?;
- Ok(true)
- }
-
- fn finish_minting(&mut self, _caller: caller) -> Result<bool> {
- Err("not implementable".into())
- }
-}
-
-#[solidity_interface(name = "ERC721UniqueExtensions")]
-impl<T: Config> CollectionHandle<T> {
- #[solidity(rename_selector = "transfer")]
- fn transfer_nft(
- &mut self,
- caller: caller,
- to: address,
- token_id: uint256,
- _value: value,
- ) -> Result<void> {
- let caller = T::CrossAccountId::from_eth(caller);
- let to = T::CrossAccountId::from_eth(to);
- let token_id = token_id.try_into().map_err(|_| "amount overflow")?;
-
- <Module<T>>::transfer_internal(&caller, &to, self, token_id, 1)
- .map_err(|_| "transfer error")?;
- Ok(())
- }
-
- fn next_token_id(&self) -> Result<uint256> {
- Ok(ItemListIndex::get(self.id)
- .checked_add(1)
- .ok_or("item id overflow")?
- .into())
- }
-
- fn set_variable_metadata(
- &mut self,
- caller: caller,
- token_id: uint256,
- data: bytes,
- ) -> Result<void> {
- let caller = T::CrossAccountId::from_eth(caller);
- let token_id = token_id.try_into().map_err(|_| "token id overflow")?;
-
- <Module<T>>::set_variable_meta_data_internal(&caller, self, token_id, data)
- .map_err(dispatch_to_evm::<T>)?;
- Ok(())
- }
-
- fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {
- let token_id = token_id.try_into().map_err(|_| "token id overflow")?;
-
- <Module<T>>::get_variable_metadata(self, token_id).map_err(dispatch_to_evm::<T>)
- }
-
- fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {
- let caller = T::CrossAccountId::from_eth(caller);
- let to = T::CrossAccountId::from_eth(to);
- let mut expected_index = <ItemListIndex>::get(self.id)
- .checked_add(1)
- .ok_or("item id overflow")?;
-
- let total_tokens = token_ids.len();
- for id in token_ids.into_iter() {
- let id: u32 = id.try_into().map_err(|_| "token id overflow")?;
- if id != expected_index {
- return Err("item id should be next".into());
- }
- expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
- }
-
- let data = (0..total_tokens)
- .map(|_| {
- CreateItemData::NFT(CreateNftData {
- const_data: vec![].try_into().unwrap(),
- variable_data: vec![].try_into().unwrap(),
- })
- })
- .collect();
-
- <Module<T>>::create_multiple_items_internal(&caller, self, &to, data)
- .map_err(dispatch_to_evm::<T>)?;
- Ok(true)
- }
-
- #[solidity(rename_selector = "mintBulkWithTokenURI")]
- fn mint_bulk_with_token_uri(
- &mut self,
- caller: caller,
- to: address,
- tokens: Vec<(uint256, string)>,
- ) -> Result<bool> {
- let caller = T::CrossAccountId::from_eth(caller);
- let to = T::CrossAccountId::from_eth(to);
- let mut expected_index = <ItemListIndex>::get(self.id)
- .checked_add(1)
- .ok_or("item id overflow")?;
-
- let mut data = Vec::with_capacity(tokens.len());
- for (id, token_uri) in tokens {
- let id: u32 = id.try_into().map_err(|_| "token id overflow")?;
- if id != expected_index {
- panic!("item id should be next ({}) but got {}", expected_index, id);
- }
- expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
-
- data.push(CreateItemData::NFT(CreateNftData {
- const_data: Vec::<u8>::from(token_uri)
- .try_into()
- .map_err(|_| "token uri is too long")?,
- variable_data: vec![].try_into().unwrap(),
- }));
- }
-
- <Module<T>>::create_multiple_items_internal(&caller, self, &to, data)
- .map_err(dispatch_to_evm::<T>)?;
- Ok(true)
- }
-}
-
-#[solidity_interface(
- name = "UniqueNFT",
- is(
- ERC165,
- ERC721,
- ERC721Metadata,
- ERC721Enumerable,
- ERC721UniqueExtensions,
- ERC721Mintable,
- ERC721Burnable,
- )
-)]
-impl<T: Config> CollectionHandle<T> {}
-
-#[derive(ToLog)]
-pub enum ERC20Events {
- Transfer {
- #[indexed]
- from: address,
- #[indexed]
- to: address,
- value: uint256,
- },
- Approval {
- #[indexed]
- owner: address,
- #[indexed]
- spender: address,
- value: uint256,
- },
-}
-
-#[solidity_interface(
- name = "ERC20",
- inline_is(InlineNameSymbol, InlineTotalSupply),
- events(ERC20Events)
-)]
-impl<T: Config> CollectionHandle<T> {
- fn decimals(&self) -> Result<uint8> {
- Ok(if let CollectionMode::Fungible(decimals) = &self.mode {
- *decimals
- } else {
- unreachable!()
- })
- }
- fn balance_of(&self, owner: address) -> Result<uint256> {
- let owner = T::EvmAddressMapping::into_account_id(owner);
- let balance = <Balance<T>>::get(self.id, owner);
- Ok(balance.into())
- }
- fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {
- let caller = T::CrossAccountId::from_eth(caller);
- let to = T::CrossAccountId::from_eth(to);
- let amount = amount.try_into().map_err(|_| "amount overflow")?;
-
- <Module<T>>::transfer_internal(&caller, &to, self, 1, amount)
- .map_err(|_| "transfer error")?;
- Ok(true)
- }
- #[solidity(rename_selector = "transferFrom")]
- fn transfer_from_fungible(
- &mut self,
- caller: caller,
- from: address,
- to: address,
- amount: uint256,
- ) -> Result<bool> {
- let caller = T::CrossAccountId::from_eth(caller);
- let from = T::CrossAccountId::from_eth(from);
- let to = T::CrossAccountId::from_eth(to);
- let amount = amount.try_into().map_err(|_| "amount overflow")?;
-
- <Module<T>>::transfer_from_internal(&caller, &from, &to, self, 1, amount)
- .map_err(|_| "transferFrom error")?;
- Ok(true)
- }
- #[solidity(rename_selector = "approve")]
- fn approve_fungible(
- &mut self,
- caller: caller,
- spender: address,
- amount: uint256,
- ) -> Result<bool> {
- let caller = T::CrossAccountId::from_eth(caller);
- let spender = T::CrossAccountId::from_eth(spender);
- let amount = amount.try_into().map_err(|_| "amount overflow")?;
-
- <Module<T>>::approve_internal(&caller, &spender, self, 1, amount)
- .map_err(|_| "approve internal")?;
- Ok(true)
- }
- fn allowance(&self, owner: address, spender: address) -> Result<uint256> {
- let owner = T::CrossAccountId::from_eth(owner);
- let spender = T::CrossAccountId::from_eth(spender);
-
- Ok(<Allowances<T>>::get(self.id, (1, owner.as_sub(), spender.as_sub())).into())
- }
-}
-
-#[solidity_interface(name = "UniqueFungible", is(ERC165, ERC20))]
-impl<T: Config> CollectionHandle<T> {}
-
-// Not a tests, but code generators
-generate_stubgen!(nft_impl, UniqueNFTCall, true);
-generate_stubgen!(nft_iface, UniqueNFTCall, false);
-
-generate_stubgen!(fungible_impl, UniqueFungibleCall, true);
-generate_stubgen!(fungible_iface, UniqueFungibleCall, false);
pallets/nft/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/nft/src/eth/mod.rs
+++ b/pallets/nft/src/eth/mod.rs
@@ -1,86 +1,21 @@
-pub mod account;
-pub mod erc;
pub mod sponsoring;
-use pallet_evm_coder_substrate::call_internal;
+use pallet_common::{
+ CollectionById,
+ erc::CommonEvmHandler,
+ eth::{map_eth_to_id, map_eth_to_token_id},
+};
+use pallet_fungible::FungibleHandle;
+use pallet_nonfungible::NonfungibleHandle;
+use pallet_refungible::{RefungibleHandle, erc::RefungibleTokenHandle};
use sp_std::borrow::ToOwned;
use sp_std::vec::Vec;
use pallet_evm::{PrecompileOutput};
use sp_core::{H160, U256};
-use frame_support::storage::StorageMap;
-use crate::{Config, CollectionById, CollectionHandle, CollectionId, CollectionMode};
-use erc::{UniqueFungibleCall, UniqueNFTCall};
+use crate::{CollectionMode, Config, dispatch::Dispatched};
+use pallet_common::CollectionHandle;
pub struct NftErcSupport<T: Config>(core::marker::PhantomData<T>);
-
-// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection
-// TODO: Unhardcode prefix
-const ETH_ACCOUNT_PREFIX: [u8; 16] = [
- 0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
-];
-
-fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {
- if eth[0..16] != ETH_ACCOUNT_PREFIX {
- return None;
- }
- let mut id_bytes = [0; 4];
- id_bytes.copy_from_slice(ð[16..20]);
- Some(u32::from_be_bytes(id_bytes))
-}
-pub fn collection_id_to_address(id: u32) -> H160 {
- let mut out = [0; 20];
- out[0..16].copy_from_slice(Ð_ACCOUNT_PREFIX);
- out[16..20].copy_from_slice(&u32::to_be_bytes(id));
- H160(out)
-}
-
-/*
-fn call_internal<T: Config>(
- collection: &mut CollectionHandle<T>,
- caller: caller,
- method_id: u32,
- mut input: AbiReader,
- value: U256,
-) -> Result<Option<AbiWriter>> {
- match collection.mode.clone() {
- CollectionMode::Fungible(_) => {
- call_internal();
- let call = match UniqueFungibleCall::parse(method_id, &mut input)? {
- Some(v) => v,
- None => {
- #[cfg(feature = "std")]
- {
- println!("Method not found");
- }
- return Ok(None);
- }
- };
- Ok(Some(<CollectionHandle<T> as UniqueFungible>::call(
- collection,
- Msg {
- call,
- caller,
- value,
- },
- )?))
- }
- CollectionMode::NFT => {
- let call = match UniqueNFTCall::parse(method_id, &mut input)? {
- Some(v) => v,
- None => return Ok(None),
- };
- Ok(Some(<CollectionHandle<T> as UniqueNFT>::call(
- collection,
- Msg {
- call,
- caller,
- value,
- },
- )?))
- }
- _ => Err("erc calls only supported to fungible and nft collections for now".into()),
- }
-}*/
impl<T: Config> pallet_evm::OnMethodCall<T> for NftErcSupport<T> {
fn is_reserved(target: &H160) -> bool {
@@ -92,20 +27,26 @@
.unwrap_or(false)
}
fn get_code(target: &H160) -> Option<Vec<u8>> {
- map_eth_to_id(target)
- .and_then(<CollectionById<T>>::get)
- .map(|collection| {
+ if let Some(collection_id) = map_eth_to_id(target) {
+ let collection = <CollectionById<T>>::get(collection_id)?;
+ Some(
match collection.mode {
- CollectionMode::NFT => include_bytes!("stubs/UniqueNFT.raw") as &[u8],
- CollectionMode::Fungible(_) => {
- include_bytes!("stubs/UniqueFungible.raw") as &[u8]
- }
- CollectionMode::ReFungible => {
- include_bytes!("stubs/UniqueRefungible.raw") as &[u8]
- }
+ CollectionMode::NFT => <NonfungibleHandle<T>>::CODE,
+ CollectionMode::Fungible(_) => <FungibleHandle<T>>::CODE,
+ CollectionMode::ReFungible => <RefungibleHandle<T>>::CODE,
}
- .to_owned()
- })
+ .to_owned(),
+ )
+ } else if let Some((collection_id, _token_id)) = map_eth_to_token_id(target) {
+ let collection = <CollectionById<T>>::get(collection_id)?;
+ if collection.mode != CollectionMode::ReFungible {
+ return None;
+ }
+ // TODO: check token existence
+ Some(<RefungibleTokenHandle<T>>::CODE.to_owned())
+ } else {
+ None
+ }
}
fn call(
source: &H160,
@@ -114,17 +55,26 @@
input: &[u8],
value: U256,
) -> Option<PrecompileOutput> {
- let mut collection = map_eth_to_id(target)
- .and_then(|id| <CollectionHandle<T>>::get_with_gas_limit(id, gas_limit))?;
- let result = match collection.mode {
- CollectionMode::NFT => {
- call_internal::<UniqueNFTCall, _>(*source, &mut collection, value, input)
+ if let Some(collection_id) = map_eth_to_id(target) {
+ let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
+ let dispatched = Dispatched::dispatch(collection);
+
+ match dispatched {
+ Dispatched::Fungible(h) => h.call(source, input, value),
+ Dispatched::Nonfungible(h) => h.call(source, input, value),
+ Dispatched::Refungible(h) => h.call(source, input, value),
}
- CollectionMode::Fungible(_) => {
- call_internal::<UniqueFungibleCall, _>(*source, &mut collection, value, input)
+ } else if let Some((collection_id, token_id)) = map_eth_to_token_id(target) {
+ let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
+ if collection.mode != CollectionMode::ReFungible {
+ return None;
}
- _ => return None,
- };
- collection.recorder.evm_to_precompile_output(result)
+
+ let handle = RefungibleHandle::cast(collection);
+ // TODO: check token existence
+ RefungibleTokenHandle(handle, token_id).call(source, input, value)
+ } else {
+ None
+ }
}
}
pallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth--- a/pallets/nft/src/eth/sponsoring.rs
+++ b/pallets/nft/src/eth/sponsoring.rs
@@ -1,29 +1,30 @@
//! Implements EVM sponsoring logic via OnChargeEVMTransaction
-use crate::{
- Collection, CollectionById, Config, FungibleTransferBasket, NftTransferBasket,
- eth::{account::EvmBackwardsAddressMapping, map_eth_to_id},
-};
+use crate::{Collection, Config, FungibleTransferBasket, NftTransferBasket};
use evm_coder::{Call, abi::AbiReader};
use frame_support::{
- storage::{StorageMap, StorageDoubleMap},
+ storage::{StorageDoubleMap},
};
+use pallet_common::eth::map_eth_to_id;
use sp_core::H160;
use sp_std::prelude::*;
use up_sponsorship::SponsorshipHandler;
-use super::{
- account::CrossAccountId,
- erc::{UniqueFungibleCall, UniqueNFTCall, ERC721Call, ERC20Call, ERC721UniqueExtensionsCall},
+use core::marker::PhantomData;
+use core::convert::TryInto;
+use nft_data_structs::{CollectionId, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT};
+use pallet_common::{
+ CollectionById,
+ account::{CrossAccountId, EvmBackwardsAddressMapping},
};
-use core::convert::TryInto;
-use core::marker::PhantomData;
-use nft_data_structs::{NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT};
+use pallet_nonfungible::erc::{UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721Call};
+use pallet_fungible::erc::{UniqueFungibleCall, ERC20Call};
+
struct AnyError;
fn try_sponsor<T: Config>(
caller: &H160,
- collection_id: u32,
+ collection_id: CollectionId,
collection: &Collection<T>,
call: &[u8],
) -> Result<(), AnyError> {
@@ -34,9 +35,10 @@
.map_err(|_| AnyError)?
.ok_or(AnyError)?;
match call {
- UniqueNFTCall::ERC721UniqueExtensions(
- ERC721UniqueExtensionsCall::TransferNft { token_id, .. },
- )
+ UniqueNFTCall::ERC721UniqueExtensions(ERC721UniqueExtensionsCall::Transfer {
+ token_id,
+ ..
+ })
| UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, .. }) => {
let token_id: u32 = token_id.try_into().map_err(|_| AnyError)?;
let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
pallets/nft/src/eth/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/nft/src/eth/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/nft/src/eth/stubs/UniqueFungible.sol
+++ /dev/null
@@ -1,121 +0,0 @@
-// SPDX-License-Identifier: OTHER
-// This code is automatically generated
-
-pragma solidity >=0.8.0 <0.9.0;
-
-// Common stubs holder
-contract Dummy {
- uint8 dummy;
- string stub_error = "this contract is implemented in native";
-}
-
-// Inline
-contract ERC20Events {
- event Transfer(address indexed from, address indexed to, uint256 value);
- event Approval(
- address indexed owner,
- address indexed spender,
- uint256 value
- );
-}
-
-// Inline
-contract InlineNameSymbol is Dummy {
- // Selector: name() 06fdde03
- function name() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- // Selector: symbol() 95d89b41
- function symbol() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-}
-
-// Inline
-contract InlineTotalSupply is Dummy {
- // Selector: totalSupply() 18160ddd
- function totalSupply() public view returns (uint256) {
- require(false, stub_error);
- dummy;
- return 0;
- }
-}
-
-contract ERC165 is Dummy {
- // Selector: supportsInterface(bytes4) 01ffc9a7
- function supportsInterface(uint32 interfaceId) public view returns (bool) {
- require(false, stub_error);
- interfaceId;
- dummy;
- return false;
- }
-}
-
-contract ERC20 is Dummy, InlineNameSymbol, InlineTotalSupply, ERC20Events {
- // Selector: decimals() 313ce567
- function decimals() public view returns (uint8) {
- require(false, stub_error);
- dummy;
- return 0;
- }
-
- // Selector: balanceOf(address) 70a08231
- function balanceOf(address owner) public view returns (uint256) {
- require(false, stub_error);
- owner;
- dummy;
- return 0;
- }
-
- // Selector: transfer(address,uint256) a9059cbb
- function transfer(address to, uint256 amount) public returns (bool) {
- require(false, stub_error);
- to;
- amount;
- dummy = 0;
- return false;
- }
-
- // Selector: transferFrom(address,address,uint256) 23b872dd
- function transferFrom(
- address from,
- address to,
- uint256 amount
- ) public returns (bool) {
- require(false, stub_error);
- from;
- to;
- amount;
- dummy = 0;
- return false;
- }
-
- // Selector: approve(address,uint256) 095ea7b3
- function approve(address spender, uint256 amount) public returns (bool) {
- require(false, stub_error);
- spender;
- amount;
- dummy = 0;
- return false;
- }
-
- // Selector: allowance(address,address) dd62ed3e
- function allowance(address owner, address spender)
- public
- view
- returns (uint256)
- {
- require(false, stub_error);
- owner;
- spender;
- dummy;
- return 0;
- }
-}
-
-contract UniqueFungible is Dummy, ERC165, ERC20 {}
pallets/nft/src/eth/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nft/src/eth/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nft/src/eth/stubs/UniqueNFT.sol
+++ /dev/null
@@ -1,326 +0,0 @@
-// SPDX-License-Identifier: OTHER
-// This code is automatically generated
-
-pragma solidity >=0.8.0 <0.9.0;
-
-// Anonymous struct
-struct Tuple0 {
- uint256 field_0;
- string field_1;
-}
-
-// Common stubs holder
-contract Dummy {
- uint8 dummy;
- string stub_error = "this contract is implemented in native";
-}
-
-// Inline
-contract ERC721Events {
- event Transfer(
- address indexed from,
- address indexed to,
- uint256 indexed tokenId
- );
- event Approval(
- address indexed owner,
- address indexed approved,
- uint256 indexed tokenId
- );
- event ApprovalForAll(
- address indexed owner,
- address indexed operator,
- bool approved
- );
-}
-
-// Inline
-contract ERC721MintableEvents {
- event MintingFinished();
-}
-
-// Inline
-contract InlineNameSymbol is Dummy {
- // Selector: name() 06fdde03
- function name() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- // Selector: symbol() 95d89b41
- function symbol() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-}
-
-// Inline
-contract InlineTotalSupply is Dummy {
- // Selector: totalSupply() 18160ddd
- function totalSupply() public view returns (uint256) {
- require(false, stub_error);
- dummy;
- return 0;
- }
-}
-
-contract ERC165 is Dummy {
- // Selector: supportsInterface(bytes4) 01ffc9a7
- function supportsInterface(uint32 interfaceId) public view returns (bool) {
- require(false, stub_error);
- interfaceId;
- dummy;
- return false;
- }
-}
-
-contract ERC721 is Dummy, ERC165, ERC721Events {
- // Selector: balanceOf(address) 70a08231
- function balanceOf(address owner) public view returns (uint256) {
- require(false, stub_error);
- owner;
- dummy;
- return 0;
- }
-
- // Selector: ownerOf(uint256) 6352211e
- function ownerOf(uint256 tokenId) public view returns (address) {
- require(false, stub_error);
- tokenId;
- dummy;
- return 0x0000000000000000000000000000000000000000;
- }
-
- // Selector: safeTransferFromWithData(address,address,uint256,bytes) 60a11672
- function safeTransferFromWithData(
- address from,
- address to,
- uint256 tokenId,
- bytes memory data
- ) public {
- require(false, stub_error);
- from;
- to;
- tokenId;
- data;
- dummy = 0;
- }
-
- // Selector: safeTransferFrom(address,address,uint256) 42842e0e
- function safeTransferFrom(
- address from,
- address to,
- uint256 tokenId
- ) public {
- require(false, stub_error);
- from;
- to;
- tokenId;
- dummy = 0;
- }
-
- // Selector: transferFrom(address,address,uint256) 23b872dd
- function transferFrom(
- address from,
- address to,
- uint256 tokenId
- ) public {
- require(false, stub_error);
- from;
- to;
- tokenId;
- dummy = 0;
- }
-
- // Selector: approve(address,uint256) 095ea7b3
- function approve(address approved, uint256 tokenId) public {
- require(false, stub_error);
- approved;
- tokenId;
- dummy = 0;
- }
-
- // Selector: setApprovalForAll(address,bool) a22cb465
- function setApprovalForAll(address operator, bool approved) public {
- require(false, stub_error);
- operator;
- approved;
- dummy = 0;
- }
-
- // Selector: getApproved(uint256) 081812fc
- function getApproved(uint256 tokenId) public view returns (address) {
- require(false, stub_error);
- tokenId;
- dummy;
- return 0x0000000000000000000000000000000000000000;
- }
-
- // Selector: isApprovedForAll(address,address) e985e9c5
- function isApprovedForAll(address owner, address operator)
- public
- view
- returns (address)
- {
- require(false, stub_error);
- owner;
- operator;
- dummy;
- return 0x0000000000000000000000000000000000000000;
- }
-}
-
-contract ERC721Burnable is Dummy {
- // Selector: burn(uint256) 42966c68
- function burn(uint256 tokenId) public {
- require(false, stub_error);
- tokenId;
- dummy = 0;
- }
-}
-
-contract ERC721Enumerable is Dummy, InlineTotalSupply {
- // Selector: tokenByIndex(uint256) 4f6ccce7
- function tokenByIndex(uint256 index) public view returns (uint256) {
- require(false, stub_error);
- index;
- dummy;
- return 0;
- }
-
- // Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
- function tokenOfOwnerByIndex(address owner, uint256 index)
- public
- view
- returns (uint256)
- {
- require(false, stub_error);
- owner;
- index;
- dummy;
- return 0;
- }
-}
-
-contract ERC721Metadata is Dummy, InlineNameSymbol {
- // Selector: tokenURI(uint256) c87b56dd
- function tokenURI(uint256 tokenId) public view returns (string memory) {
- require(false, stub_error);
- tokenId;
- dummy;
- return "";
- }
-}
-
-contract ERC721Mintable is Dummy, ERC721MintableEvents {
- // Selector: mintingFinished() 05d2035b
- function mintingFinished() public view returns (bool) {
- require(false, stub_error);
- dummy;
- return false;
- }
-
- // Selector: mint(address,uint256) 40c10f19
- function mint(address to, uint256 tokenId) public returns (bool) {
- require(false, stub_error);
- to;
- tokenId;
- dummy = 0;
- return false;
- }
-
- // Selector: mintWithTokenURI(address,uint256,string) 50bb4e7f
- function mintWithTokenURI(
- address to,
- uint256 tokenId,
- string memory tokenUri
- ) public returns (bool) {
- require(false, stub_error);
- to;
- tokenId;
- tokenUri;
- dummy = 0;
- return false;
- }
-
- // Selector: finishMinting() 7d64bcb4
- function finishMinting() public returns (bool) {
- require(false, stub_error);
- dummy = 0;
- return false;
- }
-}
-
-contract ERC721UniqueExtensions is Dummy {
- // Selector: transfer(address,uint256) a9059cbb
- function transfer(address to, uint256 tokenId) public {
- require(false, stub_error);
- to;
- tokenId;
- dummy = 0;
- }
-
- // Selector: nextTokenId() 75794a3c
- function nextTokenId() public view returns (uint256) {
- require(false, stub_error);
- dummy;
- return 0;
- }
-
- // Selector: setVariableMetadata(uint256,bytes) d4eac26d
- function setVariableMetadata(uint256 tokenId, bytes memory data) public {
- require(false, stub_error);
- tokenId;
- data;
- dummy = 0;
- }
-
- // Selector: getVariableMetadata(uint256) e6c5ce6f
- function getVariableMetadata(uint256 tokenId)
- public
- view
- returns (bytes memory)
- {
- require(false, stub_error);
- tokenId;
- dummy;
- return hex"";
- }
-
- // Selector: mintBulk(address,uint256[]) 44a9945e
- function mintBulk(address to, uint256[] memory tokenIds)
- public
- returns (bool)
- {
- require(false, stub_error);
- to;
- tokenIds;
- dummy = 0;
- return false;
- }
-
- // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
- function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
- public
- returns (bool)
- {
- require(false, stub_error);
- to;
- tokens;
- dummy = 0;
- return false;
- }
-}
-
-contract UniqueNFT is
- Dummy,
- ERC165,
- ERC721,
- ERC721Metadata,
- ERC721Enumerable,
- ERC721UniqueExtensions,
- ERC721Mintable,
- ERC721Burnable
-{}
pallets/nft/src/eth/stubs/UniqueRefungible.rawdiffbeforeafterboth--- a/pallets/nft/src/eth/stubs/UniqueRefungible.raw
+++ /dev/null
@@ -1 +0,0 @@
-TODO
\ No newline at end of file
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -16,12 +16,12 @@
pub use serde::{Serialize, Deserialize};
pub use frame_support::{
- construct_runtime, decl_event, decl_module, decl_storage, decl_error,
+ construct_runtime, decl_module, decl_storage, decl_error,
dispatch::DispatchResult,
ensure, fail, parameter_types,
traits::{
- Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,
- Randomness, IsSubType, WithdrawReasons,
+ ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced, Randomness,
+ IsSubType, WithdrawReasons,
},
weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -29,22 +29,24 @@
WeightToFeePolynomial, DispatchClass,
},
StorageValue, transactional,
+ pallet_prelude::DispatchResultWithPostInfo,
};
use scale_info::TypeInfo;
use frame_system::{self as system, ensure_signed};
-use sp_core::H160;
-use sp_std::vec;
-use sp_runtime::{DispatchError, sp_std::prelude::Vec};
-use core::ops::{Deref, DerefMut};
+use sp_runtime::{sp_std::prelude::Vec};
use nft_data_structs::{
- MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_REFUNGIBLE_PIECES,
- CUSTOM_DATA_LIMIT, COLLECTION_NUMBER_LIMIT, ACCOUNT_TOKEN_OWNERSHIP_LIMIT,
+ MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, CUSTOM_DATA_LIMIT,
VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, COLLECTION_ADMINS_LIMIT,
- OFFCHAIN_SCHEMA_LIMIT, MAX_TOKEN_PREFIX_LENGTH, MAX_COLLECTION_NAME_LENGTH,
- MAX_COLLECTION_DESCRIPTION_LENGTH, AccessMode, Collection, CreateItemData, CollectionLimits,
- CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, Ownership, NftItemType,
- MetaUpdatePermission, FungibleItemType, ReFungibleItemType,
+ OFFCHAIN_SCHEMA_LIMIT, AccessMode, Collection, CreateItemData, CollectionLimits, CollectionId,
+ CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
+};
+use pallet_common::{
+ account::CrossAccountId, CollectionHandle, IsAdmin, Pallet as PalletCommon,
+ Error as CommonError, CommonWeightInfo, Allowlist,
};
+use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};
+use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
+use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};
#[cfg(test)]
mod mock;
@@ -58,9 +60,12 @@
pub use eth::sponsoring::NftEthSponsorshipHandler;
pub use eth::NftErcSupport;
-pub use eth::account::*;
-use eth::erc::{ERC20Events, ERC721Events};
+pub mod common;
+use common::CommonWeights;
+pub mod dispatch;
+use dispatch::dispatch_call;
+
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pub mod weights;
@@ -69,204 +74,34 @@
decl_error! {
/// Error for non-fungible-token module.
pub enum Error for Module<T: Config> {
- /// Total collections bound exceeded.
- TotalCollectionsLimitExceeded,
/// Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.
CollectionDecimalPointLimitExceeded,
- /// Collection name can not be longer than 63 char.
- CollectionNameLimitExceeded,
- /// Collection description can not be longer than 255 char.
- CollectionDescriptionLimitExceeded,
- /// Token prefix can not be longer than 15 char.
- CollectionTokenPrefixLimitExceeded,
- /// This collection does not exist.
- CollectionNotFound,
- /// Item not exists.
- TokenNotFound,
- /// Admin not found
- AdminNotFound,
- /// Arithmetic calculation overflow.
- NumOverflow,
- /// Account already has admin role.
- AlreadyAdmin,
- /// You do not own this collection.
- NoPermission,
/// This address is not set as sponsor, use setCollectionSponsor first.
ConfirmUnsetSponsorFail,
- /// Collection is not in mint mode.
- PublicMintingNotAllowed,
- /// Sender parameter and item owner must be equal.
- MustBeTokenOwner,
- /// Item balance not enough.
- TokenValueTooLow,
- /// Size of item is too large.
- NftSizeLimitExceeded,
- /// No approve found
- ApproveNotFound,
- /// Requested value more than approved.
- TokenValueNotEnough,
- /// Only approved addresses can call this method.
- ApproveRequired,
- /// Address is not in white list.
- AddresNotInWhiteList,
- /// Number of collection admins bound exceeded.
- CollectionAdminsLimitExceeded,
- /// Owned tokens by a single address bound exceeded.
- AddressOwnershipLimitExceeded,
/// Length of items properties must be greater than 0.
EmptyArgument,
- /// const_data exceeded data limit.
- TokenConstDataLimitExceeded,
- /// variable_data exceeded data limit.
- TokenVariableDataLimitExceeded,
- /// Not NFT item data used to mint in NFT collection.
- NotNftDataUsedToMintNftCollectionToken,
- /// Not Fungible item data used to mint in Fungible collection.
- NotFungibleDataUsedToMintFungibleCollectionToken,
- /// Not Re Fungible item data used to mint in Re Fungible collection.
- NotReFungibleDataUsedToMintReFungibleCollectionToken,
- /// Unexpected collection type.
- UnexpectedCollectionType,
- /// Can't store metadata in fungible tokens.
- CantStoreMetadataInFungibleTokens,
- /// Collection token limit exceeded
- CollectionTokenLimitExceeded,
- /// Account token limit exceeded per collection
- AccountTokenLimitExceeded,
/// Collection limit bounds per collection exceeded
CollectionLimitBoundsExceeded,
/// Tried to enable permissions which are only permitted to be disabled
OwnerPermissionsCantBeReverted,
- /// Schema data size limit bound exceeded
- SchemaDataLimitExceeded,
- /// Maximum refungibility exceeded
- WrongRefungiblePieces,
- /// createRefungible should be called with one owner
- BadCreateRefungibleCall,
- /// Gas limit exceeded
- OutOfGas,
- /// Metadata update denied by collection settings
- MetadataUpdateDenied,
- /// Metadata update flag become unmutable with None option
- MetadataFlagFrozen,
- /// Collection settings not allowing items transferring
- TransferNotAllowed,
- /// Can't transfer tokens to ethereum zero address
- AddressIsZero,
}
}
-
-#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]
-pub struct CollectionHandle<T: Config> {
- pub id: CollectionId,
- collection: Collection<T>,
- recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,
-}
-impl<T: Config> CollectionHandle<T> {
- pub fn get_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {
- <CollectionById<T>>::get(id).map(|collection| Self {
- id,
- collection,
- recorder: pallet_evm_coder_substrate::SubstrateRecorder::new(
- eth::collection_id_to_address(id),
- gas_limit,
- ),
- })
- }
- pub fn get(id: CollectionId) -> Option<Self> {
- Self::get_with_gas_limit(id, u64::MAX)
- }
- pub fn log(&self, log: impl evm_coder::ToLog) -> DispatchResult {
- self.recorder.log_sub(log)
- }
- #[allow(dead_code)]
- fn consume_gas(&self, gas: u64) -> DispatchResult {
- self.recorder.consume_gas_sub(gas)
- }
- fn consume_sload(&self) -> DispatchResult {
- self.recorder.consume_sload_sub()
- }
- fn consume_sstore(&self) -> DispatchResult {
- self.recorder.consume_sstore_sub()
- }
- pub fn submit_logs(self) -> DispatchResult {
- self.recorder.submit_logs()
- }
- pub fn save(self) -> DispatchResult {
- self.recorder.submit_logs()?;
- <CollectionById<T>>::insert(self.id, self.collection);
- Ok(())
- }
-}
-impl<T: Config> Deref for CollectionHandle<T> {
- type Target = Collection<T>;
-
- fn deref(&self) -> &Self::Target {
- &self.collection
- }
-}
-
-impl<T: Config> DerefMut for CollectionHandle<T> {
- fn deref_mut(&mut self) -> &mut Self::Target {
- &mut self.collection
- }
-}
-
-pub trait Config: system::Config + pallet_evm_coder_substrate::Config + Sized + TypeInfo {
- type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;
-
+pub trait Config:
+ system::Config
+ + pallet_evm_coder_substrate::Config
+ + pallet_common::Config
+ + pallet_nonfungible::Config
+ + pallet_refungible::Config
+ + pallet_fungible::Config
+ + Sized
+ + TypeInfo
+{
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
-
- type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;
- type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;
-
- type CrossAccountId: CrossAccountId<Self::AccountId>;
- type Currency: Currency<Self::AccountId>;
- type CollectionCreationPrice: Get<
- <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,
- >;
- type TreasuryAccountId: Get<Self::AccountId>;
}
type SelfWeightOf<T> = <T as Config>::WeightInfo;
-trait WeightInfoHelpers: WeightInfo {
- fn transfer() -> Weight {
- Self::transfer_nft()
- .max(Self::transfer_fungible())
- .max(Self::transfer_refungible())
- }
- fn transfer_from() -> Weight {
- Self::transfer_from_nft()
- .max(Self::transfer_from_fungible())
- .max(Self::transfer_from_refungible())
- }
- fn approve() -> Weight {
- // TODO: refungible, fungible
- Self::approve_nft()
- }
- fn set_variable_meta_data(data: u32) -> Weight {
- // TODO: refungible
- Self::set_variable_meta_data_nft(data)
- }
- fn create_item(data: u32) -> Weight {
- Self::create_item_nft(data)
- .max(Self::create_item_fungible())
- .max(Self::create_item_refungible(data))
- }
- fn create_multiple_items(amount: u32) -> Weight {
- Self::create_multiple_items_nft(amount)
- .max(Self::create_multiple_items_fungible(amount))
- .max(Self::create_multiple_items_refungible(amount))
- }
- fn burn_item() -> Weight {
- // TODO: refungible, fungible
- Self::burn_item_nft()
- }
-}
-impl<T: WeightInfo> WeightInfoHelpers for T {}
-
// # Used definitions
//
// ## User control levels
@@ -293,56 +128,10 @@
trait Store for Module<T: Config> as Nft {
//#region Private members
- /// Id of next collection
- CreatedCollectionCount: u32;
/// Used for migrations
ChainVersion: u64;
- /// Id of last collection token
- /// Collection id (controlled?1)
- ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;
- //#endregion
-
- //#region Bound counters
- /// Amount of collections destroyed, used for total amount tracking with
- /// CreatedCollectionCount
- DestroyedCollectionCount: u32;
//#endregion
- //#region Basic collections
- /// Collection info
- /// Collection id (controlled?1)
- pub CollectionById get(fn collection_id) config(): map hasher(blake2_128_concat) CollectionId => Option<Collection<T>> = None;
- /// List of collection admins
- /// Collection id (controlled?2)
- pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::CrossAccountId>;
- /// Whitelisted collection users
- /// Collection id (controlled?2), user id (controlled?3)
- pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;
- //#endregion
-
- /// How many of collection items user have
- /// Collection id (controlled?2), account id (real)
- pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;
-
- /// Amount of items which spender can transfer out of owners account (via transferFrom)
- /// Collection id (controlled?2), (token id (controlled ?2) + owner account id (real) + spender account id (controlled?3))
- /// TODO: Off chain worker should remove from this map when token gets removed
- pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;
-
- //#region Item collections
- /// Collection id (controlled?2), token id (controlled?1)
- pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<NftItemType<T::CrossAccountId>>;
- /// Collection id (controlled?2), owner (controlled?2)
- pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;
- /// Collection id (controlled?2), token id (controlled?1)
- pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<ReFungibleItemType<T::CrossAccountId>>;
- //#endregion
-
- //#region Index list
- /// Collection id (controlled?2), tokens owner (controlled?2)
- pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;
- //#endregion
-
//#region Tokens transfer rate limit baskets
/// (Collection id (controlled?2), who created (real))
/// TODO: Off chain worker should remove from this map when collection gets removed
@@ -359,97 +148,13 @@
/// Collection id (controlled?2), token id (controlled?2)
pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;
}
- add_extra_genesis {
- build(|config: &GenesisConfig<T>| {
- // Modification of storage
- for (_num, _c) in &config.collection_id {
- <Module<T>>::init_collection(_c);
- }
-
- for (_num, _c, _i) in &config.nft_item_id {
- <Module<T>>::init_nft_token(*_c, _i);
- }
-
- for (collection_id, account_id, fungible_item) in &config.fungible_item_id {
- <Module<T>>::init_fungible_token(*collection_id, &T::CrossAccountId::from_sub(account_id.clone()), fungible_item);
- }
-
- for (_num, _c, _i) in &config.refungible_item_id {
- <Module<T>>::init_refungible_token(*_c, _i);
- }
- })
- }
}
-decl_event!(
- pub enum Event<T>
- where
- AccountId = <T as frame_system::Config>::AccountId,
- CrossAccountId = <T as Config>::CrossAccountId,
- {
- /// New collection was created
- ///
- /// # Arguments
- ///
- /// * collection_id: Globally unique identifier of newly created collection.
- ///
- /// * mode: [CollectionMode] converted into u8.
- ///
- /// * account_id: Collection owner.
- CollectionCreated(CollectionId, u8, AccountId),
-
- /// New item was created.
- ///
- /// # Arguments
- ///
- /// * collection_id: Id of the collection where item was created.
- ///
- /// * item_id: Id of an item. Unique within the collection.
- ///
- /// * recipient: Owner of newly created item
- ItemCreated(CollectionId, TokenId, CrossAccountId),
-
- /// Collection item was burned.
- ///
- /// # Arguments
- ///
- /// collection_id.
- ///
- /// item_id: Identifier of burned NFT.
- ItemDestroyed(CollectionId, TokenId),
-
- /// Item was transferred
- ///
- /// * collection_id: Id of collection to which item is belong
- ///
- /// * item_id: Id of an item
- ///
- /// * sender: Original owner of item
- ///
- /// * recipient: New owner of item
- ///
- /// * amount: Always 1 for NFT
- Transfer(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),
-
- /// * collection_id
- ///
- /// * item_id
- ///
- /// * sender
- ///
- /// * spender
- ///
- /// * amount
- Approved(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),
- }
-);
-
decl_module! {
pub struct Module<T: Config> for enum Call
where
origin: T::Origin
{
- fn deposit_event() = default;
const CollectionAdminsLimit: u64 = COLLECTION_ADMINS_LIMIT;
type Error = Error<T>;
@@ -484,57 +189,19 @@
// Anyone can create a collection
let who = ensure_signed(origin)?;
- // Take a (non-refundable) deposit of collection creation
- let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();
- imbalance.subsume(<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(
- &T::TreasuryAccountId::get(),
- T::CollectionCreationPrice::get(),
- ));
- <T as Config>::Currency::settle(
- &who,
- imbalance,
- WithdrawReasons::TRANSFER,
- ExistenceRequirement::KeepAlive,
- ).map_err(|_| Error::<T>::NoPermission)?;
-
- let decimal_points = match mode {
- CollectionMode::Fungible(points) => points,
- _ => 0
- };
-
- let created_count = CreatedCollectionCount::get();
- let destroyed_count = DestroyedCollectionCount::get();
-
- // bound Total number of collections
- ensure!(created_count - destroyed_count < COLLECTION_NUMBER_LIMIT, Error::<T>::TotalCollectionsLimitExceeded);
-
- // check params
- ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
- ensure!(collection_name.len() <= MAX_COLLECTION_NAME_LENGTH, Error::<T>::CollectionNameLimitExceeded);
- ensure!(collection_description.len() <= MAX_COLLECTION_DESCRIPTION_LENGTH, Error::<T>::CollectionDescriptionLimitExceeded);
- ensure!(token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH, Error::<T>::CollectionTokenPrefixLimitExceeded);
-
- // Generate next collection ID
- let next_id = created_count
- .checked_add(1)
- .ok_or(Error::<T>::NumOverflow)?;
-
- CreatedCollectionCount::put(next_id);
-
- let limits = CollectionLimits {
+ let limits = CollectionLimits::<T::BlockNumber> {
sponsored_data_size: CUSTOM_DATA_LIMIT,
..Default::default()
};
// Create new collection
- let new_collection = Collection {
+ let new_collection = Collection::<T> {
owner: who.clone(),
name: collection_name,
mode: mode.clone(),
mint_mode: false,
access: AccessMode::Normal,
description: collection_description,
- decimal_points,
token_prefix,
offchain_schema: Vec::new(),
schema_version: SchemaVersion::ImageURL,
@@ -542,15 +209,21 @@
variable_on_chain_schema: Vec::new(),
const_on_chain_schema: Vec::new(),
limits,
- meta_update_permission: MetaUpdatePermission::default(),
transfers_enabled: true,
+ meta_update_permission: Default::default(),
};
- // Add new collection to map
- <CollectionById<T>>::insert(next_id, new_collection);
-
- // call event
- Self::deposit_event(RawEvent::CollectionCreated(next_id, mode.id(), who));
+ let _id = match mode {
+ CollectionMode::NFT => {PalletNonfungible::init_collection(new_collection)?},
+ CollectionMode::Fungible(decimal_points) => {
+ // check params
+ ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
+ PalletFungible::init_collection(new_collection)?
+ }
+ CollectionMode::ReFungible => {
+ PalletRefungible::init_collection(new_collection)?
+ }
+ };
Ok(())
}
@@ -567,35 +240,24 @@
#[weight = <SelfWeightOf<T>>::destroy_collection()]
#[transactional]
pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let sender = ensure_signed(origin)?;
- let collection = Self::get_collection(collection_id)?;
- Self::check_owner_permissions(&collection, &sender)?;
- if !collection.limits.owner_can_destroy {
- fail!(Error::<T>::NoPermission);
- }
+ let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ collection.check_is_owner(&sender)?;
- <AddressTokens<T>>::remove_prefix(collection_id, None);
- <Allowances<T>>::remove_prefix(collection_id, None);
- <Balance<T>>::remove_prefix(collection_id, None);
- <ItemListIndex>::remove(collection_id);
- <AdminList<T>>::remove(collection_id);
- <CollectionById<T>>::remove(collection_id);
- <WhiteList<T>>::remove_prefix(collection_id, None);
+ // =========
- <NftItemList<T>>::remove_prefix(collection_id, None);
- <FungibleItemList<T>>::remove_prefix(collection_id, None);
- <ReFungibleItemList<T>>::remove_prefix(collection_id, None);
+ match collection.mode {
+ CollectionMode::ReFungible => PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?,
+ CollectionMode::Fungible(_) => PalletFungible::destroy_collection(FungibleHandle::cast(collection), &sender)?,
+ CollectionMode::NFT => PalletNonfungible::destroy_collection(NonfungibleHandle::cast(collection), &sender)?,
+ }
<NftTransferBasket<T>>::remove_prefix(collection_id, None);
<FungibleTransferBasket<T>>::remove_prefix(collection_id, None);
<ReFungibleTransferBasket<T>>::remove_prefix(collection_id, None);
<VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);
-
- DestroyedCollectionCount::put(DestroyedCollectionCount::get()
- .checked_add(1)
- .ok_or(Error::<T>::NumOverflow)?);
Ok(())
}
@@ -617,11 +279,11 @@
pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = Self::get_collection(collection_id)?;
+ let collection = <CollectionHandle<T>>::try_get(collection_id)?;
- Self::toggle_white_list_internal(
+ <PalletCommon<T>>::toggle_allowlist(
+ &collection,
&sender,
- &collection,
&address,
true,
)?;
@@ -646,11 +308,11 @@
pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = Self::get_collection(collection_id)?;
+ let collection = <CollectionHandle<T>>::try_get(collection_id)?;
- Self::toggle_white_list_internal(
- &sender,
+ <PalletCommon<T>>::toggle_allowlist(
&collection,
+ &sender,
&address,
false,
)?;
@@ -673,10 +335,11 @@
#[transactional]
pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult
{
- let sender = ensure_signed(origin)?;
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner(&sender)?;
- let mut target_collection = Self::get_collection(collection_id)?;
- Self::check_owner_permissions(&target_collection, &sender)?;
target_collection.access = mode;
target_collection.save()
}
@@ -698,10 +361,11 @@
#[transactional]
pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult
{
- let sender = ensure_signed(origin)?;
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner(&sender)?;
- let mut target_collection = Self::get_collection(collection_id)?;
- Self::check_owner_permissions(&target_collection, &sender)?;
target_collection.mint_mode = mint_permission;
target_collection.save()
}
@@ -721,9 +385,11 @@
#[transactional]
pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {
- let sender = ensure_signed(origin)?;
- let mut target_collection = Self::get_collection(collection_id)?;
- Self::check_owner_permissions(&target_collection, &sender)?;
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner(&sender)?;
+
target_collection.owner = new_owner;
target_collection.save()
}
@@ -745,18 +411,11 @@
#[transactional]
pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = Self::get_collection(collection_id)?;
- Self::check_owner_or_admin_permissions(&collection, &sender)?;
- let mut admin_arr = <AdminList<T>>::get(collection_id);
- match admin_arr.binary_search(&new_admin_id) {
- Ok(_) => {},
- Err(idx) => {
- ensure!(admin_arr.len() < COLLECTION_ADMINS_LIMIT as usize, Error::<T>::CollectionAdminsLimitExceeded);
- admin_arr.insert(idx, new_admin_id);
- <AdminList<T>>::insert(collection_id, admin_arr);
- }
- }
+ let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ collection.check_is_owner_or_admin(&sender)?;
+
+ <IsAdmin<T>>::insert((collection_id, new_admin_id.as_sub()), true);
Ok(())
}
@@ -776,14 +435,11 @@
#[transactional]
pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = Self::get_collection(collection_id)?;
- Self::check_owner_or_admin_permissions(&collection, &sender)?;
- let mut admin_arr = <AdminList<T>>::get(collection_id);
- if let Ok(idx) = admin_arr.binary_search(&account_id) {
- admin_arr.remove(idx);
- <AdminList<T>>::insert(collection_id, admin_arr);
- }
+ let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ collection.check_is_owner_or_admin(&sender)?;
+
+ <IsAdmin<T>>::remove((collection_id, account_id.as_sub()));
Ok(())
}
@@ -799,9 +455,10 @@
#[weight = <SelfWeightOf<T>>::set_collection_sponsor()]
#[transactional]
pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {
- let sender = ensure_signed(origin)?;
- let mut target_collection = Self::get_collection(collection_id)?;
- Self::check_owner_permissions(&target_collection, &sender)?;
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner_or_admin(&sender)?;
target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);
target_collection.save()
@@ -819,7 +476,7 @@
pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {
let sender = ensure_signed(origin)?;
- let mut target_collection = Self::get_collection(collection_id)?;
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
ensure!(
target_collection.sponsorship.pending_sponsor() == Some(&sender),
Error::<T>::ConfirmUnsetSponsorFail
@@ -841,10 +498,10 @@
#[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]
#[transactional]
pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {
- let sender = ensure_signed(origin)?;
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let mut target_collection = Self::get_collection(collection_id)?;
- Self::check_owner_permissions(&target_collection, &sender)?;
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner(&sender)?;
target_collection.sponsorship = SponsorshipState::Disabled;
target_collection.save()
@@ -868,21 +525,12 @@
/// * owner: Address, initial owner of the NFT.
///
/// * data: Token data to store on chain.
- // #[weight =
- // (130_000_000 as Weight)
- // .saturating_add((2135 as Weight).saturating_mul((properties.len() as u64) as Weight))
- // .saturating_add(RocksDbWeight::get().reads(10 as Weight))
- // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]
-
- #[weight = <SelfWeightOf<T>>::create_item(data.data_size() as u32)]
+ #[weight = <CommonWeights<T>>::create_item()]
#[transactional]
- pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResult {
+ pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = Self::get_collection(collection_id)?;
-
- Self::create_item_internal(&sender, &collection, &owner, data)?;
- collection.submit_logs()
+ dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data))
}
/// This method creates multiple items in a collection created with CreateCollection method.
@@ -903,17 +551,13 @@
/// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].
///
/// * owner: Address, initial owner of the NFT.
- #[weight = <SelfWeightOf<T>>::create_multiple_items(items_data.len() as u32)]
+ #[weight = <CommonWeights<T>>::create_multiple_items(items_data.len() as u32)]
#[transactional]
- pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResult {
-
+ pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {
ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = Self::get_collection(collection_id)?;
- Self::create_multiple_items_internal(&sender, &collection, &owner, items_data)?;
-
- collection.submit_logs()
+ dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data))
}
// TODO! transaction weight
@@ -932,46 +576,16 @@
#[weight = <SelfWeightOf<T>>::set_transfers_enabled_flag()]
#[transactional]
pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {
-
- let sender = ensure_signed(origin)?;
- let mut target_collection = Self::get_collection(collection_id)?;
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner(&sender)?;
- Self::check_owner_permissions(&target_collection, &sender)?;
+ // =========
target_collection.transfers_enabled = value;
target_collection.save()
}
- // TODO! transaction weight
- /// Set meta_update_permission value for particular collection
- ///
- /// # Permissions
- ///
- /// * Collection Owner.
- ///
- /// # Arguments
- ///
- /// * collection_id: ID of the collection.
- ///
- /// * value: New flag value.
- #[weight = <T as Config>::WeightInfo::burn_item()]
- #[transactional]
- pub fn set_meta_update_permission_flag(origin, collection_id: CollectionId, value: MetaUpdatePermission) -> DispatchResult {
-
- let sender = ensure_signed(origin)?;
- let mut target_collection = Self::get_collection(collection_id)?;
-
- ensure!(
- target_collection.meta_update_permission != MetaUpdatePermission::None,
- Error::<T>::MetadataFlagFrozen
- );
- Self::check_owner_permissions(&target_collection, &sender)?;
-
- target_collection.meta_update_permission = value;
-
- target_collection.save()
- }
-
/// Destroys a concrete instance of NFT.
///
/// # Permissions
@@ -985,16 +599,12 @@
/// * collection_id: ID of the collection.
///
/// * item_id: ID of NFT to burn.
- #[weight = <SelfWeightOf<T>>::burn_item()]
+ #[weight = <CommonWeights<T>>::burn_item()]
#[transactional]
- pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {
-
+ pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let target_collection = Self::get_collection(collection_id)?;
- Self::burn_item_internal(&sender, &target_collection, item_id, value, true)?;
-
- target_collection.submit_logs()
+ dispatch_call::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))
}
/// Destroys a concrete instance of NFT on behalf of the owner
@@ -1013,16 +623,12 @@
/// * item_id: ID of NFT to burn.
///
/// * from: owner of item
- #[weight = <SelfWeightOf<T>>::burn_item()]
+ #[weight = <CommonWeights<T>>::burn_from()]
#[transactional]
- pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResult {
-
+ pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let target_collection = Self::get_collection(collection_id)?;
- Self::burn_from_internal(&sender, &target_collection, &from, item_id, value)?;
-
- target_collection.submit_logs()
+ dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value))
}
/// Change ownership of the token.
@@ -1048,15 +654,12 @@
/// * Non-Fungible Mode: Ignored
/// * Fungible Mode: Must specify transferred amount
/// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)
- #[weight = <SelfWeightOf<T>>::transfer()]
+ #[weight = <CommonWeights<T>>::transfer()]
#[transactional]
- pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {
+ pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = Self::get_collection(collection_id)?;
- Self::transfer_internal(&sender, &recipient, &collection, item_id, value)?;
-
- collection.submit_logs()
+ dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value))
}
/// Set, change, or remove approved address to transfer the ownership of the NFT.
@@ -1074,15 +677,12 @@
/// * collection_id.
///
/// * item_id: ID of the item.
- #[weight = <SelfWeightOf<T>>::approve()]
+ #[weight = <CommonWeights<T>>::approve()]
#[transactional]
- pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {
+ pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = Self::get_collection(collection_id)?;
-
- Self::approve_internal(&sender, &spender, &collection, item_id, amount)?;
- collection.submit_logs()
+ dispatch_call::<T, _>(collection_id, |d| d.approve(sender, spender, item_id, amount))
}
/// 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,29 +704,14 @@
/// * item_id: ID of the item.
///
/// * value: Amount to transfer.
- #[weight = <SelfWeightOf<T>>::transfer_from()]
+ #[weight = <CommonWeights<T>>::transfer_from()]
#[transactional]
- pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {
+ pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = Self::get_collection(collection_id)?;
- Self::transfer_from_internal(&sender, &from, &recipient, &collection, item_id, value)?;
-
- collection.submit_logs()
+ dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value))
}
- // #[weight = 0]
- // // let no_perm_mes = "You do not have permissions to modify this collection";
- // // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);
- // // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));
- // // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);
- // // // on_nft_received call
-
- // // Self::transfer(origin, collection_id, item_id, new_owner)?;
-
- // Ok(())
- // }
-
/// Set off-chain data schema.
///
/// # Permissions
@@ -1139,22 +724,45 @@
/// * collection_id.
///
/// * schema: String representing the offchain data schema.
- #[weight = <SelfWeightOf<T>>::set_variable_meta_data(data.len() as u32)]
+ #[weight = <CommonWeights<T>>::set_variable_metadata(data.len() as u32)]
#[transactional]
pub fn set_variable_meta_data (
origin,
collection_id: CollectionId,
item_id: TokenId,
data: Vec<u8>
- ) -> DispatchResult {
+ ) -> DispatchResultWithPostInfo {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let collection = Self::get_collection(collection_id)?;
- Self::meta_update_check(&sender, &collection, item_id)?;
+ dispatch_call::<T, _>(collection_id, |d| d.set_variable_metadata(sender, item_id, data))
+ }
- Self::set_variable_meta_data_internal(&sender, &collection, item_id, data)?;
+ /// Set meta_update_permission value for particular collection
+ ///
+ /// # Permissions
+ ///
+ /// * Collection Owner.
+ ///
+ /// # Arguments
+ ///
+ /// * collection_id: ID of the collection.
+ ///
+ /// * value: New flag value.
+ #[weight = <SelfWeightOf<T>>::set_meta_update_permission_flag()]
+ #[transactional]
+ pub fn set_meta_update_permission_flag(origin, collection_id: CollectionId, value: MetaUpdatePermission) -> DispatchResult {
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
- Ok(())
+ ensure!(
+ target_collection.meta_update_permission != MetaUpdatePermission::None,
+ <CommonError<T>>::MetadataFlagFrozen,
+ );
+ target_collection.check_is_owner(&sender)?;
+
+ target_collection.meta_update_permission = value;
+
+ target_collection.save()
}
/// Set schema standard
@@ -1179,8 +787,8 @@
version: SchemaVersion
) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let mut target_collection = Self::get_collection(collection_id)?;
- Self::check_owner_or_admin_permissions(&target_collection, &sender)?;
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner_or_admin(&sender)?;
target_collection.schema_version = version;
target_collection.save()
}
@@ -1205,8 +813,8 @@
schema: Vec<u8>
) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let mut target_collection = Self::get_collection(collection_id)?;
- Self::check_owner_or_admin_permissions(&target_collection, &sender)?;
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner_or_admin(&sender)?;
// check schema limit
ensure!(schema.len() as u32 <= OFFCHAIN_SCHEMA_LIMIT, "");
@@ -1235,8 +843,8 @@
schema: Vec<u8>
) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let mut target_collection = Self::get_collection(collection_id)?;
- Self::check_owner_or_admin_permissions(&target_collection, &sender)?;
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner_or_admin(&sender)?;
// check schema limit
ensure!(schema.len() as u32 <= CONST_ON_CHAIN_SCHEMA_LIMIT, "");
@@ -1265,8 +873,8 @@
schema: Vec<u8>
) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let mut target_collection = Self::get_collection(collection_id)?;
- Self::check_owner_or_admin_permissions(&target_collection, &sender)?;
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner_or_admin(&sender)?;
// check schema limit
ensure!(schema.len() as u32 <= VARIABLE_ON_CHAIN_SCHEMA_LIMIT, "");
@@ -1279,23 +887,23 @@
#[transactional]
pub fn set_collection_limits(
origin,
- collection_id: u32,
+ collection_id: CollectionId,
new_limits: CollectionLimits<T::BlockNumber>,
) -> DispatchResult {
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
- let mut target_collection = Self::get_collection(collection_id)?;
- Self::check_owner_permissions(&target_collection, sender.as_sub())?;
+ let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
+ target_collection.check_is_owner(&sender)?;
let old_limits = &target_collection.limits;
// collection bounds
ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&
- new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP &&
+ new_limits.account_token_ownership_limit.unwrap_or(0) <= MAX_TOKEN_OWNERSHIP &&
new_limits.sponsored_data_size <= CUSTOM_DATA_LIMIT,
Error::<T>::CollectionLimitBoundsExceeded);
// token_limit check prev
- ensure!(old_limits.token_limit >= new_limits.token_limit, Error::<T>::CollectionTokenLimitExceeded);
- ensure!(new_limits.token_limit > 0, Error::<T>::CollectionTokenLimitExceeded);
+ ensure!(old_limits.token_limit >= new_limits.token_limit, <CommonError<T>>::CollectionTokenLimitExceeded);
+ ensure!(new_limits.token_limit > 0, <CommonError<T>>::CollectionTokenLimitExceeded);
ensure!(
(old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&
@@ -1310,1294 +918,16 @@
}
}
-impl<T: Config> Module<T> {
- pub fn create_item_internal(
- sender: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- owner: &T::CrossAccountId,
- data: CreateItemData,
- ) -> DispatchResult {
- ensure!(
- owner != &T::CrossAccountId::from_eth(H160([0; 20])),
- Error::<T>::AddressIsZero
- );
-
- Self::can_create_items_in_collection(collection, sender, owner, 1)?;
- Self::validate_create_item_args(collection, &data)?;
- Self::create_item_no_validation(collection, owner, data)?;
-
- Ok(())
+// TODO: limit returned entries?
+impl<T: Config> Pallet<T> {
+ pub fn adminlist(collection: CollectionId) -> Vec<T::AccountId> {
+ <IsAdmin<T>>::iter_prefix((collection,))
+ .map(|(a, _)| a)
+ .collect()
}
-
- pub fn transfer_internal(
- sender: &T::CrossAccountId,
- recipient: &T::CrossAccountId,
- target_collection: &CollectionHandle<T>,
- item_id: TokenId,
- value: u128,
- ) -> DispatchResult {
- ensure!(
- recipient != &T::CrossAccountId::from_eth(H160([0; 20])),
- Error::<T>::AddressIsZero
- );
-
- // Limits check
- Self::is_correct_transfer(target_collection, recipient)?;
-
- // Transfer permissions check
- ensure!(
- Self::is_item_owner(sender, target_collection, item_id)?
- || Self::is_owner_or_admin_permissions(target_collection, sender)?,
- Error::<T>::NoPermission
- );
-
- if target_collection.access == AccessMode::WhiteList {
- Self::check_white_list(target_collection, sender)?;
- Self::check_white_list(target_collection, recipient)?;
- }
-
- match target_collection.mode {
- CollectionMode::NFT => Self::transfer_nft(
- target_collection,
- item_id,
- sender.clone(),
- recipient.clone(),
- )?,
- CollectionMode::Fungible(_) => {
- Self::transfer_fungible(target_collection, value, sender, recipient)?
- }
- CollectionMode::ReFungible => Self::transfer_refungible(
- target_collection,
- item_id,
- value,
- sender.clone(),
- recipient.clone(),
- )?,
- };
-
- Self::deposit_event(RawEvent::Transfer(
- target_collection.id,
- item_id,
- sender.clone(),
- recipient.clone(),
- value,
- ));
-
- Ok(())
- }
-
- pub fn approve_internal(
- sender: &T::CrossAccountId,
- spender: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- amount: u128,
- ) -> DispatchResult {
- Self::token_exists(collection, item_id)?;
-
- // Transfer permissions check
- let bypasses_limits = collection.limits.owner_can_transfer
- && Self::is_owner_or_admin_permissions(collection, sender)?;
-
- let allowance_limit = if bypasses_limits {
- None
- } else if let Some(amount) = Self::owned_amount(sender, collection, item_id)? {
- Some(amount)
- } else {
- fail!(Error::<T>::NoPermission);
- };
-
- if collection.access == AccessMode::WhiteList {
- Self::check_white_list(collection, sender)?;
- Self::check_white_list(collection, spender)?;
- }
-
- collection.consume_sload()?;
- let allowance: u128 = amount
- .checked_add(<Allowances<T>>::get(
- collection.id,
- (item_id, sender.as_sub(), spender.as_sub()),
- ))
- .ok_or(Error::<T>::NumOverflow)?;
- if let Some(limit) = allowance_limit {
- ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);
- }
- collection.consume_sstore()?;
- <Allowances<T>>::insert(
- collection.id,
- (item_id, sender.as_sub(), spender.as_sub()),
- allowance,
- );
-
- if matches!(collection.mode, CollectionMode::NFT) {
- // TODO: NFT: only one owner may exist for token in ERC721
- collection.log(ERC721Events::Approval {
- owner: *sender.as_eth(),
- approved: *spender.as_eth(),
- token_id: item_id.into(),
- })?;
- }
-
- if matches!(collection.mode, CollectionMode::Fungible(_)) {
- // TODO: NFT: only one owner may exist for token in ERC20
- collection.log(ERC20Events::Approval {
- owner: *sender.as_eth(),
- spender: *spender.as_eth(),
- value: allowance.into(),
- })?;
- }
-
- Self::deposit_event(RawEvent::Approved(
- collection.id,
- item_id,
- sender.clone(),
- spender.clone(),
- allowance,
- ));
- Ok(())
- }
-
- pub fn transfer_from_internal(
- sender: &T::CrossAccountId,
- from: &T::CrossAccountId,
- recipient: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- amount: u128,
- ) -> DispatchResult {
- if sender == from {
- // Transfer by `from`, because it is either equal to sender, or derived from him
- return Self::transfer_internal(from, recipient, collection, item_id, amount);
- }
-
- // Check approval
- collection.consume_sload()?;
- let approval: u128 =
- <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));
-
- // Limits check
- Self::is_correct_transfer(collection, recipient)?;
-
- // Transfer permissions check
- ensure!(
- approval >= amount
- || (collection.limits.owner_can_transfer
- && Self::is_owner_or_admin_permissions(collection, sender)?),
- Error::<T>::NoPermission
- );
-
- if collection.access == AccessMode::WhiteList {
- Self::check_white_list(collection, sender)?;
- Self::check_white_list(collection, recipient)?;
- }
-
- // Reduce approval by transferred amount or remove if remaining approval drops to 0
- let allowance = approval.saturating_sub(amount);
- collection.consume_sstore()?;
- if allowance > 0 {
- <Allowances<T>>::insert(
- collection.id,
- (item_id, from.as_sub(), sender.as_sub()),
- allowance,
- );
- } else {
- <Allowances<T>>::remove(collection.id, (item_id, from.as_sub(), sender.as_sub()));
- }
-
- match collection.mode {
- CollectionMode::NFT => {
- Self::transfer_nft(collection, item_id, from.clone(), recipient.clone())?
- }
- CollectionMode::Fungible(_) => {
- Self::transfer_fungible(collection, amount, from, recipient)?
- }
- CollectionMode::ReFungible => Self::transfer_refungible(
- collection,
- item_id,
- amount,
- from.clone(),
- recipient.clone(),
- )?,
- };
-
- if matches!(collection.mode, CollectionMode::Fungible(_)) {
- collection.log(ERC20Events::Approval {
- owner: *from.as_eth(),
- spender: *sender.as_eth(),
- value: allowance.into(),
- })?;
- }
-
- Ok(())
- }
-
- pub fn set_variable_meta_data_internal(
- sender: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- data: Vec<u8>,
- ) -> DispatchResult {
- Self::token_exists(collection, item_id)?;
-
- ensure!(
- CUSTOM_DATA_LIMIT >= data.len() as u32,
- Error::<T>::TokenVariableDataLimitExceeded
- );
-
- ensure!(
- (Self::is_item_owner(sender, collection, item_id)?
- && collection.meta_update_permission == MetaUpdatePermission::ItemOwner)
- || (Self::is_owner_or_admin_permissions(collection, sender)?
- && collection.meta_update_permission == MetaUpdatePermission::Admin),
- Error::<T>::NoPermission
- );
-
- match collection.mode {
- CollectionMode::NFT => Self::set_nft_variable_data(collection, item_id, data)?,
- CollectionMode::ReFungible => {
- Self::set_re_fungible_variable_data(collection, item_id, data)?
- }
- CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),
- };
-
- Ok(())
- }
-
- pub fn meta_update_check(
- sender: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- ) -> DispatchResult {
- match collection.meta_update_permission {
- MetaUpdatePermission::ItemOwner => ensure!(
- Self::is_item_owner(sender, collection, item_id)?,
- Error::<T>::NoPermission
- ),
- MetaUpdatePermission::Admin => ensure!(
- Self::is_owner_or_admin_permissions(collection, sender)?,
- Error::<T>::NoPermission
- ),
- MetaUpdatePermission::None => fail!(Error::<T>::MetadataUpdateDenied),
- }
-
- Ok(())
- }
-
- pub fn get_variable_metadata(
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- ) -> Result<Vec<u8>, DispatchError> {
- Ok(match collection.mode {
- CollectionMode::NFT => {
- <NftItemList<T>>::get(collection.id, item_id)
- .ok_or(Error::<T>::TokenNotFound)?
- .variable_data
- }
- CollectionMode::ReFungible => {
- <ReFungibleItemList<T>>::get(collection.id, item_id)
- .ok_or(Error::<T>::TokenNotFound)?
- .variable_data
- }
- _ => fail!(Error::<T>::UnexpectedCollectionType),
- })
- }
-
- pub fn create_multiple_items_internal(
- sender: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- owner: &T::CrossAccountId,
- items_data: Vec<CreateItemData>,
- ) -> DispatchResult {
- Self::can_create_items_in_collection(collection, sender, owner, items_data.len() as u32)?;
-
- for data in &items_data {
- Self::validate_create_item_args(collection, data)?;
- }
- for data in &items_data {
- Self::create_item_no_validation(collection, owner, data.clone())?;
- }
-
- Ok(())
- }
-
- pub fn burn_item_internal(
- owner: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- value: u128,
- allow_escalation: bool,
- ) -> DispatchResult {
- ensure!(
- Self::is_item_owner(owner, collection, item_id)?
- || (allow_escalation
- && collection.limits.owner_can_transfer
- && Self::is_owner_or_admin_permissions(collection, owner)?),
- Error::<T>::NoPermission
- );
-
- if collection.access == AccessMode::WhiteList {
- Self::check_white_list(collection, owner)?;
- }
-
- match collection.mode {
- CollectionMode::NFT => match value {
- 1 => Self::burn_nft_item(collection, item_id)?,
- 0 => (),
- _ => fail!(<Error<T>>::TokenValueTooLow),
- },
- CollectionMode::Fungible(_) => Self::burn_fungible_item(collection, owner, value)?,
- CollectionMode::ReFungible => {
- Self::burn_refungible_item(collection, item_id, owner, value)?
- }
- _ => (),
- };
-
- Ok(())
- }
-
- pub fn burn_from_internal(
- sender: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- from: &T::CrossAccountId,
- item_id: TokenId,
- amount: u128,
- ) -> DispatchResult {
- if sender == from {
- // Transfer by `from`, because it is either equal to sender, or derived from him
- return Self::burn_item_internal(from, collection, item_id, amount, true);
- }
-
- // Check approval
- collection.consume_sload()?;
- let approval: u128 =
- <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));
-
- // Transfer permissions check
- ensure!(
- approval >= amount
- || (collection.limits.owner_can_transfer
- && Self::is_owner_or_admin_permissions(collection, sender)?),
- Error::<T>::NoPermission
- );
-
- if collection.access == AccessMode::WhiteList {
- Self::check_white_list(collection, sender)?;
- }
-
- // Reduce approval by transferred amount or remove if remaining approval drops to 0
- let allowance = approval.saturating_sub(amount);
- collection.consume_sstore()?;
- if allowance > 0 {
- <Allowances<T>>::insert(
- collection.id,
- (item_id, from.as_sub(), sender.as_sub()),
- allowance,
- );
- } else {
- <Allowances<T>>::remove(collection.id, (item_id, from.as_sub(), sender.as_sub()));
- }
-
- // Escalation is disallowed here, because we need to be sure that passed owner is real
- Self::burn_item_internal(from, collection, item_id, amount, false)?;
-
- if matches!(collection.mode, CollectionMode::Fungible(_)) {
- collection.log(ERC20Events::Approval {
- owner: *from.as_eth(),
- spender: *sender.as_eth(),
- value: allowance.into(),
- })?;
- }
-
- Ok(())
- }
-
- pub fn toggle_white_list_internal(
- sender: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- address: &T::CrossAccountId,
- whitelisted: bool,
- ) -> DispatchResult {
- Self::check_owner_or_admin_permissions(collection, sender)?;
-
- if whitelisted {
- <WhiteList<T>>::insert(collection.id, address.as_sub(), true);
- } else {
- <WhiteList<T>>::remove(collection.id, address.as_sub());
- }
-
- Ok(())
- }
-
- fn is_correct_transfer(
- collection: &CollectionHandle<T>,
- recipient: &T::CrossAccountId,
- ) -> DispatchResult {
- let collection_id = collection.id;
-
- // check token limit and account token limit
- collection.consume_sload()?;
- let account_items: u32 =
- <AddressTokens<T>>::get(collection_id, recipient.as_sub()).len() as u32;
-
- // zero limit means collection limit is disabled
- // otherwise get lower value
- let limit = if collection.limits.account_token_ownership_limit == 0
- || collection.limits.account_token_ownership_limit > ACCOUNT_TOKEN_OWNERSHIP_LIMIT
- {
- ACCOUNT_TOKEN_OWNERSHIP_LIMIT
- } else {
- collection.limits.account_token_ownership_limit
- };
-
- ensure!(limit > account_items, Error::<T>::AccountTokenLimitExceeded);
-
- // preliminary transfer check
- ensure!(collection.transfers_enabled, Error::<T>::TransferNotAllowed);
-
- Ok(())
- }
-
- fn can_create_items_in_collection(
- collection: &CollectionHandle<T>,
- sender: &T::CrossAccountId,
- owner: &T::CrossAccountId,
- amount: u32,
- ) -> DispatchResult {
- let collection_id = collection.id;
-
- // check token limit and account token limit
- let total_items: u32 = ItemListIndex::get(collection_id)
- .checked_add(amount)
- .ok_or(Error::<T>::CollectionTokenLimitExceeded)?;
- let account_items: u32 = (<AddressTokens<T>>::get(collection_id, owner.as_sub()).len()
- as u32)
- .checked_add(amount)
- .ok_or(Error::<T>::AccountTokenLimitExceeded)?;
-
- // zero limit means collection limit is disabled
- // otherwise get lower value
- let account_token_limit = if collection.limits.account_token_ownership_limit == 0
- || collection.limits.account_token_ownership_limit > ACCOUNT_TOKEN_OWNERSHIP_LIMIT
- {
- ACCOUNT_TOKEN_OWNERSHIP_LIMIT
- } else {
- collection.limits.account_token_ownership_limit
- };
-
- ensure!(
- collection.limits.token_limit >= total_items,
- Error::<T>::CollectionTokenLimitExceeded
- );
- ensure!(
- account_token_limit >= account_items,
- Error::<T>::AccountTokenLimitExceeded
- );
-
- if !Self::is_owner_or_admin_permissions(collection, sender)? {
- ensure!(collection.mint_mode, Error::<T>::PublicMintingNotAllowed);
- Self::check_white_list(collection, owner)?;
- Self::check_white_list(collection, sender)?;
- }
-
- Ok(())
- }
-
- fn validate_create_item_args(
- target_collection: &CollectionHandle<T>,
- data: &CreateItemData,
- ) -> DispatchResult {
- match target_collection.mode {
- CollectionMode::NFT => {
- if !matches!(data, CreateItemData::NFT(_)) {
- fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);
- }
- }
- CollectionMode::Fungible(_) => {
- if !matches!(data, CreateItemData::Fungible(_)) {
- fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);
- }
- }
- CollectionMode::ReFungible => {
- if let CreateItemData::ReFungible(data) = data {
- // Check refungibility limits
- ensure!(
- data.pieces <= MAX_REFUNGIBLE_PIECES,
- Error::<T>::WrongRefungiblePieces
- );
- ensure!(data.pieces > 0, Error::<T>::WrongRefungiblePieces);
- } else {
- fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);
- }
- }
- };
-
- Ok(())
- }
-
- fn create_item_no_validation(
- collection: &CollectionHandle<T>,
- owner: &T::CrossAccountId,
- data: CreateItemData,
- ) -> DispatchResult {
- match data {
- CreateItemData::NFT(data) => {
- let item = NftItemType {
- owner: owner.clone(),
- const_data: data.const_data.into_inner(),
- variable_data: data.variable_data.into_inner(),
- };
-
- Self::add_nft_item(collection, item)?;
- }
- CreateItemData::Fungible(data) => {
- Self::add_fungible_item(collection, owner, data.value)?;
- }
- CreateItemData::ReFungible(data) => {
- let owner_list = vec![Ownership {
- owner: owner.clone(),
- fraction: data.pieces,
- }];
-
- let item = ReFungibleItemType {
- owner: owner_list,
- const_data: data.const_data.into_inner(),
- variable_data: data.variable_data.into_inner(),
- };
-
- Self::add_refungible_item(collection, item)?;
- }
- };
-
- Ok(())
- }
-
- fn add_fungible_item(
- collection: &CollectionHandle<T>,
- owner: &T::CrossAccountId,
- value: u128,
- ) -> DispatchResult {
- let collection_id = collection.id;
-
- // Does new owner already have an account?
- collection.consume_sload()?;
- let balance: u128 = <FungibleItemList<T>>::get(collection_id, owner.as_sub()).value;
-
- // Mint
- let item = FungibleItemType {
- value: balance.checked_add(value).ok_or(Error::<T>::NumOverflow)?,
- };
- collection.consume_sstore()?;
- <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), item);
-
- // Update balance
- collection.consume_sload()?;
- let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())
- .checked_add(value)
- .ok_or(Error::<T>::NumOverflow)?;
- collection.consume_sstore()?;
- <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);
-
- collection.log(ERC20Events::Transfer {
- from: H160::default(),
- to: *owner.as_eth(),
- value: value.into(),
- })?;
- Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));
- Ok(())
- }
-
- fn add_refungible_item(
- collection: &CollectionHandle<T>,
- item: ReFungibleItemType<T::CrossAccountId>,
- ) -> DispatchResult {
- let collection_id = collection.id;
-
- let current_index = <ItemListIndex>::get(collection_id)
- .checked_add(1)
- .ok_or(Error::<T>::NumOverflow)?;
- let itemcopy = item.clone();
-
- ensure!(item.owner.len() == 1, Error::<T>::BadCreateRefungibleCall,);
- let item_owner = item.owner.first().expect("only one owner is defined");
-
- let value = item_owner.fraction;
- let owner = item_owner.owner.clone();
-
- Self::add_token_index(collection, current_index, &owner)?;
-
- <ItemListIndex>::insert(collection_id, current_index);
- <ReFungibleItemList<T>>::insert(collection_id, current_index, itemcopy);
-
- // Update balance
- let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())
- .checked_add(value)
- .ok_or(Error::<T>::NumOverflow)?;
- <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);
-
- Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));
- Ok(())
- }
-
- fn add_nft_item(
- collection: &CollectionHandle<T>,
- item: NftItemType<T::CrossAccountId>,
- ) -> DispatchResult {
- let collection_id = collection.id;
-
- let current_index = <ItemListIndex>::get(collection_id)
- .checked_add(1)
- .ok_or(Error::<T>::NumOverflow)?;
-
- let item_owner = item.owner.clone();
- Self::add_token_index(collection, current_index, &item.owner)?;
-
- <ItemListIndex>::insert(collection_id, current_index);
- <NftItemList<T>>::insert(collection_id, current_index, item);
-
- // Update balance
- let new_balance = <Balance<T>>::get(collection_id, item_owner.as_sub())
- .checked_add(1)
- .ok_or(Error::<T>::NumOverflow)?;
- <Balance<T>>::insert(collection_id, item_owner.as_sub(), new_balance);
-
- collection.log(ERC721Events::Transfer {
- from: H160::default(),
- to: *item_owner.as_eth(),
- token_id: current_index.into(),
- })?;
- Self::deposit_event(RawEvent::ItemCreated(
- collection_id,
- current_index,
- item_owner,
- ));
- Ok(())
- }
-
- fn burn_refungible_item(
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- owner: &T::CrossAccountId,
- value: u128,
- ) -> DispatchResult {
- let collection_id = collection.id;
-
- let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id)
- .ok_or(Error::<T>::TokenNotFound)?;
- let mut rft_balance = token
- .owner
- .iter()
- .find(|&i| i.owner == *owner)
- .ok_or(Error::<T>::TokenNotFound)?
- .clone();
- Self::remove_token_index(collection, item_id, owner)?;
-
- // update balance
- let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.as_sub())
- .checked_sub(value)
- .ok_or(Error::<T>::NumOverflow)?;
- <Balance<T>>::insert(collection_id, rft_balance.owner.as_sub(), new_balance);
-
- rft_balance.fraction = (rft_balance.fraction)
- .checked_sub(value)
- .ok_or(Error::<T>::NumOverflow)?;
-
- let index = token
- .owner
- .iter()
- .position(|i| i.owner == *owner)
- .expect("owned item is exists");
- if rft_balance.fraction == 0 {
- // Re-create owners list with sender removed
- token.owner.remove(index);
- } else {
- token.owner[index] = rft_balance;
- }
-
- let owner_count = token.owner.len();
-
- // Burn the token completely if this was the last (only) owner
- if owner_count == 0 {
- <ReFungibleItemList<T>>::remove(collection_id, item_id);
- <VariableMetaDataBasket<T>>::remove(collection_id, item_id);
- } else {
- <ReFungibleItemList<T>>::insert(collection_id, item_id, token);
- }
-
- Ok(())
- }
-
- fn burn_nft_item(collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {
- let collection_id = collection.id;
-
- let item =
- <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;
- Self::remove_token_index(collection, item_id, &item.owner)?;
-
- // update balance
- let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())
- .checked_sub(1)
- .ok_or(Error::<T>::NumOverflow)?;
- <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);
- <NftItemList<T>>::remove(collection_id, item_id);
- <VariableMetaDataBasket<T>>::remove(collection_id, item_id);
-
- collection.log(ERC721Events::Transfer {
- from: *item.owner.as_eth(),
- to: H160::default(),
- token_id: item_id.into(),
- })?;
- Self::deposit_event(RawEvent::ItemDestroyed(collection.id, item_id));
- Ok(())
- }
-
- fn burn_fungible_item(
- collection: &CollectionHandle<T>,
- owner: &T::CrossAccountId,
- value: u128,
- ) -> DispatchResult {
- let collection_id = collection.id;
-
- let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());
- ensure!(balance.value >= value, Error::<T>::TokenValueNotEnough);
-
- // update balance
- let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())
- .checked_sub(value)
- .ok_or(Error::<T>::NumOverflow)?;
- <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);
-
- if balance.value - value > 0 {
- balance.value -= value;
- <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);
- } else {
- <FungibleItemList<T>>::remove(collection_id, owner.as_sub());
- }
-
- collection.log(ERC20Events::Transfer {
- from: *owner.as_eth(),
- to: H160::default(),
- value: value.into(),
- })?;
- Ok(())
- }
-
- pub fn get_collection(
- collection_id: CollectionId,
- ) -> Result<CollectionHandle<T>, sp_runtime::DispatchError> {
- Ok(<CollectionHandle<T>>::get(collection_id).ok_or(Error::<T>::CollectionNotFound)?)
- }
-
- fn check_owner_permissions(
- target_collection: &CollectionHandle<T>,
- subject: &T::AccountId,
- ) -> DispatchResult {
- ensure!(
- *subject == target_collection.owner,
- Error::<T>::NoPermission
- );
-
- Ok(())
- }
-
- fn is_owner_or_admin_permissions(
- collection: &CollectionHandle<T>,
- subject: &T::CrossAccountId,
- ) -> Result<bool, DispatchError> {
- collection.consume_sload()?;
- Ok(*subject.as_sub() == collection.owner
- || <AdminList<T>>::get(collection.id).contains(subject))
- }
-
- fn check_owner_or_admin_permissions(
- collection: &CollectionHandle<T>,
- subject: &T::CrossAccountId,
- ) -> DispatchResult {
- ensure!(
- Self::is_owner_or_admin_permissions(collection, subject)?,
- Error::<T>::NoPermission
- );
-
- Ok(())
- }
-
- fn owned_amount(
- subject: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- ) -> Result<Option<u128>, DispatchError> {
- collection.consume_sload()?;
- Ok(Self::owned_amount_unchecked(subject, collection, item_id))
- }
-
- fn owned_amount_unchecked(
- subject: &T::CrossAccountId,
- target_collection: &CollectionHandle<T>,
- item_id: TokenId,
- ) -> Option<u128> {
- let collection_id = target_collection.id;
-
- match target_collection.mode {
- CollectionMode::NFT => {
- (<NftItemList<T>>::get(collection_id, item_id)?.owner == *subject).then(|| 1)
- }
- CollectionMode::Fungible(_) => {
- Some(<FungibleItemList<T>>::get(collection_id, &subject.as_sub()).value)
- }
- CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)?
- .owner
- .iter()
- .find(|i| i.owner == *subject)
- .map(|i| i.fraction),
- }
- }
-
- fn is_item_owner(
- subject: &T::CrossAccountId,
- target_collection: &CollectionHandle<T>,
- item_id: TokenId,
- ) -> Result<bool, DispatchError> {
- Ok(match target_collection.mode {
- CollectionMode::Fungible(_) => true,
- _ => Self::owned_amount(subject, target_collection, item_id)?.is_some(),
- })
- }
-
- fn check_white_list(
- collection: &CollectionHandle<T>,
- address: &T::CrossAccountId,
- ) -> DispatchResult {
- collection.consume_sload()?;
- ensure!(
- <WhiteList<T>>::contains_key(collection.id, address.as_sub()),
- Error::<T>::AddresNotInWhiteList,
- );
- Ok(())
- }
-
- /// Check if token exists. In case of Fungible, check if there is an entry for
- /// the owner in fungible balances double map
- fn token_exists(target_collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {
- let collection_id = target_collection.id;
- let exists = match target_collection.mode {
- CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),
- CollectionMode::Fungible(_) => true,
- CollectionMode::ReFungible => {
- <ReFungibleItemList<T>>::contains_key(collection_id, item_id)
- }
- };
-
- ensure!(exists, Error::<T>::TokenNotFound);
- Ok(())
- }
-
- fn transfer_fungible(
- collection: &CollectionHandle<T>,
- value: u128,
- owner: &T::CrossAccountId,
- recipient: &T::CrossAccountId,
- ) -> DispatchResult {
- let collection_id = collection.id;
-
- collection.consume_sload()?;
- collection.consume_sload()?;
- let mut recipient_balance = <FungibleItemList<T>>::get(collection_id, recipient.as_sub());
- let mut balance = <FungibleItemList<T>>::get(collection_id, owner.as_sub());
-
- recipient_balance.value = recipient_balance
- .value
- .checked_add(value)
- .ok_or(Error::<T>::NumOverflow)?;
- balance.value = balance
- .value
- .checked_sub(value)
- .ok_or(Error::<T>::TokenValueTooLow)?;
-
- // update balanceOf
- collection.consume_sstore()?;
- collection.consume_sstore()?;
- if balance.value != 0 {
- <Balance<T>>::insert(collection_id, owner.as_sub(), balance.value);
- } else {
- <Balance<T>>::remove(collection_id, owner.as_sub());
- }
- <Balance<T>>::insert(collection_id, recipient.as_sub(), recipient_balance.value);
-
- // Reduce or remove sender
- collection.consume_sstore()?;
- collection.consume_sstore()?;
- if balance.value != 0 {
- <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);
- } else {
- <FungibleItemList<T>>::remove(collection_id, owner.as_sub());
- }
- <FungibleItemList<T>>::insert(collection_id, recipient.as_sub(), recipient_balance);
-
- collection.log(ERC20Events::Transfer {
- from: *owner.as_eth(),
- to: *recipient.as_eth(),
- value: value.into(),
- })?;
- Self::deposit_event(RawEvent::Transfer(
- collection.id,
- 1,
- owner.clone(),
- recipient.clone(),
- value,
- ));
-
- Ok(())
- }
-
- fn transfer_refungible(
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- value: u128,
- owner: T::CrossAccountId,
- new_owner: T::CrossAccountId,
- ) -> DispatchResult {
- let collection_id = collection.id;
- collection.consume_sload()?;
- let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id)
- .ok_or(Error::<T>::TokenNotFound)?;
-
- let item = full_item
- .owner
- .iter()
- .find(|i| i.owner == owner)
- .ok_or(Error::<T>::TokenNotFound)?;
- let amount = item.fraction;
-
- ensure!(amount >= value, Error::<T>::TokenValueTooLow);
-
- collection.consume_sload()?;
- // update balance
- let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())
- .checked_sub(value)
- .ok_or(Error::<T>::NumOverflow)?;
- collection.consume_sstore()?;
- <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);
-
- collection.consume_sload()?;
- let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())
- .checked_add(value)
- .ok_or(Error::<T>::NumOverflow)?;
- collection.consume_sstore()?;
- <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);
-
- let old_owner = item.owner.clone();
- let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);
-
- let mut new_full_item = full_item.clone();
- // transfer
- if amount == value && !new_owner_has_account {
- // change owner
- // new owner do not have account
- new_full_item
- .owner
- .iter_mut()
- .find(|i| i.owner == owner)
- .expect("old owner does present in refungible")
- .owner = new_owner.clone();
- collection.consume_sstore()?;
- <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);
-
- // update index collection
- Self::move_token_index(collection, item_id, &old_owner, &new_owner)?;
- } else {
- new_full_item
- .owner
- .iter_mut()
- .find(|i| i.owner == owner)
- .expect("old owner does present in refungible")
- .fraction -= value;
-
- // separate amount
- if new_owner_has_account {
- // new owner has account
- new_full_item
- .owner
- .iter_mut()
- .find(|i| i.owner == new_owner)
- .expect("new owner has account")
- .fraction += value;
- } else {
- // new owner do not have account
- new_full_item.owner.push(Ownership {
- owner: new_owner.clone(),
- fraction: value,
- });
- Self::add_token_index(collection, item_id, &new_owner)?;
- }
-
- collection.consume_sstore()?;
- <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);
- }
-
- Self::deposit_event(RawEvent::Transfer(
- collection.id,
- item_id,
- owner,
- new_owner,
- amount,
- ));
-
- Ok(())
- }
-
- fn transfer_nft(
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- sender: T::CrossAccountId,
- new_owner: T::CrossAccountId,
- ) -> DispatchResult {
- let collection_id = collection.id;
- collection.consume_sload()?;
- let mut item =
- <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;
-
- ensure!(sender == item.owner, Error::<T>::MustBeTokenOwner);
-
- collection.consume_sload()?;
- // update balance
- let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.as_sub())
- .checked_sub(1)
- .ok_or(Error::<T>::NumOverflow)?;
- collection.consume_sstore()?;
- <Balance<T>>::insert(collection_id, item.owner.as_sub(), balance_old_owner);
-
- collection.consume_sload()?;
- let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.as_sub())
- .checked_add(1)
- .ok_or(Error::<T>::NumOverflow)?;
- collection.consume_sstore()?;
- <Balance<T>>::insert(collection_id, new_owner.as_sub(), balance_new_owner);
-
- // change owner
- let old_owner = item.owner.clone();
- item.owner = new_owner.clone();
- collection.consume_sstore()?;
- <NftItemList<T>>::insert(collection_id, item_id, item);
-
- // update index collection
- Self::move_token_index(collection, item_id, &old_owner, &new_owner)?;
-
- collection.log(ERC721Events::Transfer {
- from: *sender.as_eth(),
- to: *new_owner.as_eth(),
- token_id: item_id.into(),
- })?;
- Self::deposit_event(RawEvent::Transfer(
- collection.id,
- item_id,
- sender,
- new_owner,
- 1,
- ));
-
- Ok(())
- }
-
- fn set_re_fungible_variable_data(
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- data: Vec<u8>,
- ) -> DispatchResult {
- let collection_id = collection.id;
- let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id)
- .ok_or(Error::<T>::TokenNotFound)?;
-
- item.variable_data = data;
-
- <ReFungibleItemList<T>>::insert(collection_id, item_id, item);
-
- Ok(())
- }
-
- fn set_nft_variable_data(
- collection: &CollectionHandle<T>,
- item_id: TokenId,
- data: Vec<u8>,
- ) -> DispatchResult {
- let collection_id = collection.id;
- let mut item =
- <NftItemList<T>>::get(collection_id, item_id).ok_or(Error::<T>::TokenNotFound)?;
-
- item.variable_data = data;
-
- <NftItemList<T>>::insert(collection_id, item_id, item);
-
- Ok(())
- }
-
- #[allow(dead_code)]
- fn init_collection(item: &Collection<T>) {
- // check params
- assert!(
- item.decimal_points <= MAX_DECIMAL_POINTS,
- "decimal_points parameter must be lower than MAX_DECIMAL_POINTS"
- );
- assert!(
- item.name.len() <= 64,
- "Collection name can not be longer than 63 char"
- );
- assert!(
- item.name.len() <= 256,
- "Collection description can not be longer than 255 char"
- );
- assert!(
- item.token_prefix.len() <= 16,
- "Token prefix can not be longer than 15 char"
- );
-
- // Generate next collection ID
- let next_id = CreatedCollectionCount::get().checked_add(1).unwrap();
-
- CreatedCollectionCount::put(next_id);
- }
-
- #[allow(dead_code)]
- fn init_nft_token(collection_id: CollectionId, item: &NftItemType<T::CrossAccountId>) {
- let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();
-
- Self::add_token_index(
- &CollectionHandle::get(collection_id).unwrap(),
- current_index,
- &item.owner,
- )
- .unwrap();
-
- <ItemListIndex>::insert(collection_id, current_index);
-
- // Update balance
- let new_balance = <Balance<T>>::get(collection_id, item.owner.as_sub())
- .checked_add(1)
- .unwrap();
- <Balance<T>>::insert(collection_id, item.owner.as_sub(), new_balance);
- }
-
- #[allow(dead_code)]
- fn init_fungible_token(
- collection_id: CollectionId,
- owner: &T::CrossAccountId,
- item: &FungibleItemType,
- ) {
- let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();
-
- Self::add_token_index(
- &CollectionHandle::get(collection_id).unwrap(),
- current_index,
- owner,
- )
- .unwrap();
-
- <ItemListIndex>::insert(collection_id, current_index);
-
- // Update balance
- let new_balance = <Balance<T>>::get(collection_id, owner.as_sub())
- .checked_add(item.value)
- .unwrap();
- <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);
- }
-
- #[allow(dead_code)]
- fn init_refungible_token(
- collection_id: CollectionId,
- item: &ReFungibleItemType<T::CrossAccountId>,
- ) {
- let current_index = <ItemListIndex>::get(collection_id).checked_add(1).unwrap();
-
- let value = item.owner.first().unwrap().fraction;
- let owner = item.owner.first().unwrap().owner.clone();
-
- Self::add_token_index(
- &CollectionHandle::get(collection_id).unwrap(),
- current_index,
- &owner,
- )
- .unwrap();
-
- <ItemListIndex>::insert(collection_id, current_index);
-
- // Update balance
- let new_balance = <Balance<T>>::get(collection_id, &owner.as_sub())
- .checked_add(value)
- .unwrap();
- <Balance<T>>::insert(collection_id, owner.as_sub(), new_balance);
- }
-
- fn add_token_index(
- collection: &CollectionHandle<T>,
- item_index: TokenId,
- owner: &T::CrossAccountId,
- ) -> DispatchResult {
- collection.consume_sload()?;
- let list_exists = <AddressTokens<T>>::contains_key(collection.id, owner.as_sub());
- if list_exists {
- collection.consume_sload()?;
- let mut list = <AddressTokens<T>>::get(collection.id, owner.as_sub());
-
- // bound Owned tokens by a single address in collection
- let account_items: u32 = list.len() as u32;
- ensure!(
- account_items < ACCOUNT_TOKEN_OWNERSHIP_LIMIT,
- Error::<T>::AddressOwnershipLimitExceeded
- );
-
- let item_contains = list.contains(&item_index.clone());
-
- if !item_contains {
- list.push(item_index);
- }
-
- collection.consume_sstore()?;
- <AddressTokens<T>>::insert(collection.id, owner.as_sub(), list);
- } else {
- let itm = vec![item_index];
- collection.consume_sstore()?;
- <AddressTokens<T>>::insert(collection.id, owner.as_sub(), itm);
- }
-
- Ok(())
- }
-
- fn remove_token_index(
- collection: &CollectionHandle<T>,
- item_index: TokenId,
- owner: &T::CrossAccountId,
- ) -> DispatchResult {
- collection.consume_sload()?;
- let list_exists = <AddressTokens<T>>::contains_key(collection.id, owner.as_sub());
- if list_exists {
- collection.consume_sload()?;
- let mut list = <AddressTokens<T>>::get(collection.id, owner.as_sub());
- let item_contains = list.contains(&item_index.clone());
-
- if item_contains {
- list.retain(|&item| item != item_index);
- collection.consume_sstore()?;
- <AddressTokens<T>>::insert(collection.id, owner.as_sub(), list);
- }
- }
-
- Ok(())
- }
-
- fn move_token_index(
- collection: &CollectionHandle<T>,
- item_index: TokenId,
- old_owner: &T::CrossAccountId,
- new_owner: &T::CrossAccountId,
- ) -> DispatchResult {
- Self::remove_token_index(collection, item_index, old_owner)?;
- Self::add_token_index(collection, item_index, new_owner)?;
-
- Ok(())
- }
-}
-
-sp_api::decl_runtime_apis! {
- pub trait NftApi {
- /// Used for ethereum integration
- fn eth_contract_code(account: H160) -> Option<Vec<u8>>;
+ pub fn allowlist(collection: CollectionId) -> Vec<T::AccountId> {
+ <Allowlist<T>>::iter_prefix((collection,))
+ .map(|(a, _)| a)
+ .collect()
}
}
pallets/nft/src/sponsorship.rsdiffbeforeafterboth--- a/pallets/nft/src/sponsorship.rs
+++ b/pallets/nft/src/sponsorship.rs
@@ -1,7 +1,6 @@
use crate::{
- Config, Call, CollectionById, CreateItemBasket, VariableMetaDataBasket,
- ReFungibleTransferBasket, FungibleTransferBasket, NftTransferBasket, CreateItemData,
- CollectionMode,
+ Config, Call, CreateItemBasket, VariableMetaDataBasket, ReFungibleTransferBasket,
+ FungibleTransferBasket, NftTransferBasket, CreateItemData, CollectionMode,
};
use core::marker::PhantomData;
use up_sponsorship::SponsorshipHandler;
@@ -13,6 +12,7 @@
TokenId, CollectionId, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
};
+use pallet_common::{CollectionById};
pub struct NftSponsorshipHandler<T>(PhantomData<T>);
impl<T: Config> NftSponsorshipHandler<T> {
@@ -61,15 +61,10 @@
sponsor_transfer = match collection_mode {
CollectionMode::NFT => {
// get correct limit
- let limit: u32 = if collection_limits.sponsor_transfer_timeout != 0 {
- if collection_limits.sponsor_transfer_timeout > NFT_SPONSOR_TRANSFER_TIMEOUT
- {
- collection_limits.sponsor_transfer_timeout
- } else {
- NFT_SPONSOR_TRANSFER_TIMEOUT
- }
+ let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
+ collection_limits.sponsor_transfer_timeout
} else {
- 0
+ NFT_SPONSOR_TRANSFER_TIMEOUT
};
let mut sponsored = true;
@@ -88,18 +83,13 @@
}
CollectionMode::Fungible(_) => {
// get correct limit
- let limit: u32 = if collection_limits.sponsor_transfer_timeout != 0 {
- if collection_limits.sponsor_transfer_timeout
- > FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
- {
- collection_limits.sponsor_transfer_timeout
- } else {
- FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
- }
+ let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
+ collection_limits.sponsor_transfer_timeout
} else {
- 0
+ FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
};
+ let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
let mut sponsored = true;
if FungibleTransferBasket::<T>::contains_key(collection_id, who) {
let last_tx_block = FungibleTransferBasket::<T>::get(collection_id, who);
@@ -116,16 +106,10 @@
}
CollectionMode::ReFungible => {
// get correct limit
- let limit: u32 = if collection_limits.sponsor_transfer_timeout != 0 {
- if collection_limits.sponsor_transfer_timeout
- > REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
- {
- collection_limits.sponsor_transfer_timeout
- } else {
- REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
- }
+ let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
+ collection_limits.sponsor_transfer_timeout
} else {
- 0
+ REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
};
let mut sponsored = true;
pallets/nft/src/weights.rsdiffbeforeafterboth--- a/pallets/nft/src/weights.rs
+++ b/pallets/nft/src/weights.rs
@@ -2,8 +2,8 @@
//! Autogenerated weights for pallet_nft
//!
-//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0
-//! DATE: 2021-08-31, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
+//! DATE: 2021-10-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 128
// Executed Command:
@@ -43,202 +43,141 @@
fn set_collection_sponsor() -> Weight;
fn confirm_sponsorship() -> Weight;
fn remove_collection_sponsor() -> Weight;
- fn create_item_nft(b: u32, ) -> Weight;
- fn create_multiple_items_nft(b: u32, ) -> Weight;
- fn create_item_fungible() -> Weight;
- fn create_multiple_items_fungible(b: u32, ) -> Weight;
- fn create_item_refungible(b: u32, ) -> Weight;
- fn create_multiple_items_refungible(b: u32, ) -> Weight;
- fn burn_item_nft() -> Weight;
- fn transfer_nft() -> Weight;
- fn transfer_fungible() -> Weight;
- fn transfer_refungible() -> Weight;
fn set_transfers_enabled_flag() -> Weight;
- fn approve_nft() -> Weight;
- fn transfer_from_nft() -> Weight;
- fn transfer_from_fungible() -> Weight;
- fn transfer_from_refungible() -> Weight;
fn set_offchain_schema(b: u32, ) -> Weight;
fn set_const_on_chain_schema(b: u32, ) -> Weight;
fn set_variable_on_chain_schema(b: u32, ) -> Weight;
- fn set_variable_meta_data_nft(b: u32, ) -> Weight;
fn set_schema_version() -> Weight;
fn set_collection_limits() -> Weight;
+ fn set_meta_update_permission_flag() -> Weight;
}
/// Weights for pallet_nft using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
+ // Storage: Common CreatedCollectionCount (r:1 w:1)
+ // Storage: Common DestroyedCollectionCount (r:1 w:0)
+ // Storage: System Account (r:2 w:2)
+ // Storage: Common CollectionById (r:0 w:1)
fn create_collection() -> Weight {
- (25_851_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(8 as Weight))
- .saturating_add(T::DbWeight::get().writes(6 as Weight))
+ (23_803_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(4 as Weight))
+ .saturating_add(T::DbWeight::get().writes(4 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
+ // Storage: Common DestroyedCollectionCount (r:1 w:1)
+ // Storage: Nonfungible TokensMinted (r:0 w:1)
+ // Storage: Nonfungible TokensBurnt (r:0 w:1)
fn destroy_collection() -> Weight {
- (28_737_000 as Weight)
+ (27_831_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:0)
+ // Storage: Common Allowlist (r:0 w:1)
fn add_to_white_list() -> Weight {
- (6_237_000 as Weight)
+ (6_629_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:0)
+ // Storage: Common Allowlist (r:0 w:1)
fn remove_from_white_list() -> Weight {
- (6_252_000 as Weight)
+ (6_596_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn set_public_access_mode() -> Weight {
- (6_691_000 as Weight)
+ (6_338_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn set_mint_permission() -> Weight {
- (6_630_000 as Weight)
+ (6_383_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn change_collection_owner() -> Weight {
- (6_521_000 as Weight)
+ (6_493_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:0)
+ // Storage: Common IsAdmin (r:0 w:1)
fn add_collection_admin() -> Weight {
- (8_057_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ (6_850_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:0)
+ // Storage: Common IsAdmin (r:0 w:1)
fn remove_collection_admin() -> Weight {
- (8_307_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ (6_615_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn set_collection_sponsor() -> Weight {
- (6_484_000 as Weight)
+ (6_430_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn confirm_sponsorship() -> Weight {
- (6_530_000 as Weight)
+ (6_125_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn remove_collection_sponsor() -> Weight {
- (6_733_000 as Weight)
+ (6_236_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
- fn create_item_nft(_b: u32, ) -> Weight {
- (167_909_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(11 as Weight))
- .saturating_add(T::DbWeight::get().writes(8 as Weight))
- }
- fn create_multiple_items_nft(b: u32, ) -> Weight {
- (336_830_000 as Weight)
- // Standard Error: 42_000
- .saturating_add((11_627_000 as Weight).saturating_mul(b as Weight))
- .saturating_add(T::DbWeight::get().reads(11 as Weight))
- .saturating_add(T::DbWeight::get().writes(7 as Weight))
- .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(b as Weight)))
- }
- fn create_item_fungible() -> Weight {
- (24_123_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(9 as Weight))
- .saturating_add(T::DbWeight::get().writes(4 as Weight))
- }
- fn create_multiple_items_fungible(b: u32, ) -> Weight {
- (48_227_000 as Weight)
- // Standard Error: 13_000
- .saturating_add((2_918_000 as Weight).saturating_mul(b as Weight))
- .saturating_add(T::DbWeight::get().reads(9 as Weight))
- .saturating_add(T::DbWeight::get().writes(4 as Weight))
- }
- fn create_item_refungible(_b: u32, ) -> Weight {
- (26_293_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(9 as Weight))
- .saturating_add(T::DbWeight::get().writes(7 as Weight))
- }
- fn create_multiple_items_refungible(b: u32, ) -> Weight {
- (0 as Weight)
- // Standard Error: 16_000
- .saturating_add((8_374_000 as Weight).saturating_mul(b as Weight))
- .saturating_add(T::DbWeight::get().reads(9 as Weight))
- .saturating_add(T::DbWeight::get().writes(6 as Weight))
- .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(b as Weight)))
- }
- fn burn_item_nft() -> Weight {
- (32_237_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(9 as Weight))
- .saturating_add(T::DbWeight::get().writes(7 as Weight))
- }
- fn transfer_nft() -> Weight {
- (192_578_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(14 as Weight))
- .saturating_add(T::DbWeight::get().writes(10 as Weight))
- }
- fn transfer_fungible() -> Weight {
- (170_749_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(11 as Weight))
- .saturating_add(T::DbWeight::get().writes(7 as Weight))
- }
- fn transfer_refungible() -> Weight {
- (35_949_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(10 as Weight))
- .saturating_add(T::DbWeight::get().writes(7 as Weight))
- }
+ // Storage: Common CollectionById (r:1 w:1)
fn set_transfers_enabled_flag() -> Weight {
- (6_376_000 as Weight)
+ (6_500_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
- fn approve_nft() -> Weight {
- (169_825_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(9 as Weight))
- .saturating_add(T::DbWeight::get().writes(4 as Weight))
- }
- fn transfer_from_nft() -> Weight {
- (197_912_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(15 as Weight))
- .saturating_add(T::DbWeight::get().writes(11 as Weight))
- }
- fn transfer_from_fungible() -> Weight {
- (183_789_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(12 as Weight))
- .saturating_add(T::DbWeight::get().writes(8 as Weight))
- }
- fn transfer_from_refungible() -> Weight {
- (37_149_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(11 as Weight))
- .saturating_add(T::DbWeight::get().writes(8 as Weight))
- }
+ // Storage: Common CollectionById (r:1 w:1)
fn set_offchain_schema(_b: u32, ) -> Weight {
- (6_435_000 as Weight)
+ (6_538_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn set_const_on_chain_schema(_b: u32, ) -> Weight {
- (6_646_000 as Weight)
+ (6_542_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
- fn set_variable_on_chain_schema(_b: u32, ) -> Weight {
- (6_542_000 as Weight)
+ // Storage: Common CollectionById (r:1 w:1)
+ fn set_variable_on_chain_schema(b: u32, ) -> Weight {
+ (6_092_000 as Weight)
+ // Standard Error: 0
+ .saturating_add((2_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
- fn set_variable_meta_data_nft(_b: u32, ) -> Weight {
- (14_697_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ // Storage: Common CollectionById (r:1 w:1)
+ fn set_schema_version() -> Weight {
+ (6_470_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
- fn set_schema_version() -> Weight {
- (6_566_000 as Weight)
+ // Storage: Common CollectionById (r:1 w:1)
+ fn set_collection_limits() -> Weight {
+ (6_841_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
- fn set_collection_limits() -> Weight {
- (6_349_000 as Weight)
+ // Storage: Common CollectionById (r:1 w:1)
+ fn set_meta_update_permission_flag() -> Weight {
+ (6_278_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
@@ -246,178 +185,129 @@
// For backwards compatibility and tests
impl WeightInfo for () {
+ // Storage: Common CreatedCollectionCount (r:1 w:1)
+ // Storage: Common DestroyedCollectionCount (r:1 w:0)
+ // Storage: System Account (r:2 w:2)
+ // Storage: Common CollectionById (r:0 w:1)
fn create_collection() -> Weight {
- (25_851_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(8 as Weight))
- .saturating_add(RocksDbWeight::get().writes(6 as Weight))
+ (23_803_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(4 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
+ // Storage: Common DestroyedCollectionCount (r:1 w:1)
+ // Storage: Nonfungible TokensMinted (r:0 w:1)
+ // Storage: Nonfungible TokensBurnt (r:0 w:1)
fn destroy_collection() -> Weight {
- (28_737_000 as Weight)
+ (27_831_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:0)
+ // Storage: Common Allowlist (r:0 w:1)
fn add_to_white_list() -> Weight {
- (6_237_000 as Weight)
+ (6_629_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:0)
+ // Storage: Common Allowlist (r:0 w:1)
fn remove_from_white_list() -> Weight {
- (6_252_000 as Weight)
+ (6_596_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn set_public_access_mode() -> Weight {
- (6_691_000 as Weight)
+ (6_338_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn set_mint_permission() -> Weight {
- (6_630_000 as Weight)
+ (6_383_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn change_collection_owner() -> Weight {
- (6_521_000 as Weight)
+ (6_493_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:0)
+ // Storage: Common IsAdmin (r:0 w:1)
fn add_collection_admin() -> Weight {
- (8_057_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ (6_850_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:0)
+ // Storage: Common IsAdmin (r:0 w:1)
fn remove_collection_admin() -> Weight {
- (8_307_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ (6_615_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn set_collection_sponsor() -> Weight {
- (6_484_000 as Weight)
+ (6_430_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn confirm_sponsorship() -> Weight {
- (6_530_000 as Weight)
+ (6_125_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn remove_collection_sponsor() -> Weight {
- (6_733_000 as Weight)
+ (6_236_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
- fn create_item_nft(b: u32, ) -> Weight {
- (167_180_000 as Weight)
- // Standard Error: 1_000
- .saturating_add((10_000 as Weight).saturating_mul(b as Weight))
- .saturating_add(RocksDbWeight::get().reads(11 as Weight))
- .saturating_add(RocksDbWeight::get().writes(8 as Weight))
- }
- fn create_multiple_items_nft(b: u32, ) -> Weight {
- (336_830_000 as Weight)
- // Standard Error: 42_000
- .saturating_add((11_627_000 as Weight).saturating_mul(b as Weight))
- .saturating_add(RocksDbWeight::get().reads(11 as Weight))
- .saturating_add(RocksDbWeight::get().writes(7 as Weight))
- .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(b as Weight)))
- }
- fn create_item_fungible() -> Weight {
- (24_123_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(9 as Weight))
- .saturating_add(RocksDbWeight::get().writes(4 as Weight))
- }
- fn create_multiple_items_fungible(b: u32, ) -> Weight {
- (13_217_000 as Weight)
- // Standard Error: 4_000
- .saturating_add((2_971_000 as Weight).saturating_mul(b as Weight))
- .saturating_add(RocksDbWeight::get().reads(9 as Weight))
- .saturating_add(RocksDbWeight::get().writes(4 as Weight))
- }
- fn create_item_refungible(_b: u32, ) -> Weight {
- (26_293_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(9 as Weight))
- .saturating_add(RocksDbWeight::get().writes(7 as Weight))
- }
- fn create_multiple_items_refungible(b: u32, ) -> Weight {
- (0 as Weight)
- // Standard Error: 16_000
- .saturating_add((8_374_000 as Weight).saturating_mul(b as Weight))
- .saturating_add(RocksDbWeight::get().reads(9 as Weight))
- .saturating_add(RocksDbWeight::get().writes(6 as Weight))
- .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(b as Weight)))
- }
- fn burn_item_nft() -> Weight {
- (32_237_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(9 as Weight))
- .saturating_add(RocksDbWeight::get().writes(7 as Weight))
- }
- fn transfer_nft() -> Weight {
- (192_578_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(14 as Weight))
- .saturating_add(RocksDbWeight::get().writes(10 as Weight))
- }
- fn transfer_fungible() -> Weight {
- (170_749_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(11 as Weight))
- .saturating_add(RocksDbWeight::get().writes(7 as Weight))
- }
- fn transfer_refungible() -> Weight {
- (35_949_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(10 as Weight))
- .saturating_add(RocksDbWeight::get().writes(7 as Weight))
- }
+ // Storage: Common CollectionById (r:1 w:1)
fn set_transfers_enabled_flag() -> Weight {
- (6_376_000 as Weight)
+ (6_500_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
- fn approve_nft() -> Weight {
- (169_825_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(9 as Weight))
- .saturating_add(RocksDbWeight::get().writes(4 as Weight))
- }
- fn transfer_from_nft() -> Weight {
- (197_912_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(15 as Weight))
- .saturating_add(RocksDbWeight::get().writes(11 as Weight))
- }
- fn transfer_from_fungible() -> Weight {
- (183_789_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(12 as Weight))
- .saturating_add(RocksDbWeight::get().writes(8 as Weight))
- }
- fn transfer_from_refungible() -> Weight {
- (37_149_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(11 as Weight))
- .saturating_add(RocksDbWeight::get().writes(8 as Weight))
- }
+ // Storage: Common CollectionById (r:1 w:1)
fn set_offchain_schema(_b: u32, ) -> Weight {
- (6_435_000 as Weight)
+ (6_538_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionById (r:1 w:1)
fn set_const_on_chain_schema(_b: u32, ) -> Weight {
- (6_646_000 as Weight)
+ (6_542_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
- fn set_variable_on_chain_schema(_b: u32, ) -> Weight {
- (6_542_000 as Weight)
+ // Storage: Common CollectionById (r:1 w:1)
+ fn set_variable_on_chain_schema(b: u32, ) -> Weight {
+ (6_092_000 as Weight)
+ // Standard Error: 0
+ .saturating_add((2_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
- fn set_variable_meta_data_nft(_b: u32, ) -> Weight {
- (14_697_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ // Storage: Common CollectionById (r:1 w:1)
+ fn set_schema_version() -> Weight {
+ (6_470_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
- fn set_schema_version() -> Weight {
- (6_566_000 as Weight)
+ // Storage: Common CollectionById (r:1 w:1)
+ fn set_collection_limits() -> Weight {
+ (6_841_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
- fn set_collection_limits() -> Weight {
- (6_349_000 as Weight)
+ // Storage: Common CollectionById (r:1 w:1)
+ fn set_meta_update_permission_flag() -> Weight {
+ (6_278_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/pallets/nonfungible/Cargo.toml
@@ -0,0 +1,46 @@
+[package]
+name = "pallet-nonfungible"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies.codec]
+default-features = false
+features = ['derive']
+package = 'parity-scale-codec'
+version = '2.0.0'
+
+[dependencies]
+frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+pallet-common = { default-features = false, path = '../common' }
+nft-data-structs = { default-features = false, path = '../../primitives/nft' }
+evm-coder = { default-features = false, path = '../../crates/evm-coder' }
+pallet-evm-coder-substrate = { default-features = false, path = '../evm-coder-substrate' }
+ethereum = { git = "https://github.com/purestake/ethereum", branch = "joshy-scale-info", default-features = false }
+frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+scale-info = { version = "1.0.0", default-features = false, features = [
+ "derive",
+] }
+
+[features]
+default = ["std"]
+std = [
+ "frame-support/std",
+ "frame-system/std",
+ "sp-runtime/std",
+ "sp-std/std",
+ "nft-data-structs/std",
+ "pallet-common/std",
+ "evm-coder/std",
+ "ethereum/std",
+ "pallet-evm-coder-substrate/std",
+ 'frame-benchmarking/std',
+]
+runtime-benchmarks = [
+ 'frame-benchmarking',
+ 'frame-support/runtime-benchmarks',
+ 'frame-system/runtime-benchmarks',
+]
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -0,0 +1,101 @@
+use super::*;
+use crate::{Pallet, Config, NonfungibleHandle};
+
+use sp_std::prelude::*;
+use pallet_common::benchmarking::{create_collection_raw, create_data};
+use frame_benchmarking::{benchmarks, account};
+use nft_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH};
+use pallet_common::bench_init;
+use core::convert::TryInto;
+
+const SEED: u32 = 1;
+
+fn create_max_item_data<T: Config>(owner: T::CrossAccountId) -> CreateItemData<T> {
+ let const_data = create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap();
+ let variable_data = create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap();
+ CreateItemData {
+ const_data,
+ variable_data,
+ owner,
+ }
+}
+fn create_max_item<T: Config>(
+ collection: &NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ owner: T::CrossAccountId,
+) -> Result<TokenId, DispatchError> {
+ <Pallet<T>>::create_item(&collection, sender, create_max_item_data(owner))?;
+ Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
+}
+
+fn create_collection<T: Config>(
+ owner: T::AccountId,
+) -> Result<NonfungibleHandle<T>, DispatchError> {
+ create_collection_raw(
+ owner,
+ CollectionMode::NFT,
+ <Pallet<T>>::init_collection,
+ NonfungibleHandle::cast,
+ )
+}
+
+benchmarks! {
+ create_item {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); to: cross_sub;
+ };
+ }: {create_max_item(&collection, &sender, to.clone())?}
+
+ create_multiple_items {
+ let b in 0..MAX_ITEMS_PER_BATCH;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); to: cross_sub;
+ };
+ let data = (0..b).map(|_| create_max_item_data(to.clone())).collect();
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+
+ burn_item {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); burner: cross_sub;
+ };
+ let item = create_max_item(&collection, &sender, burner.clone())?;
+ }: {<Pallet<T>>::burn(&collection, &burner, item)?}
+
+ transfer {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; receiver: cross_sub;
+ };
+ let item = create_max_item(&collection, &owner, sender.clone())?;
+ }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item)?}
+
+ approve {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+ };
+ let item = create_max_item(&collection, &owner, sender.clone())?;
+ }: {<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?}
+
+ transfer_from {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+ };
+ let item = create_max_item(&collection, &owner, sender.clone())?;
+ <Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?;
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item)?}
+
+ set_variable_metadata {
+ let b in 0..CUSTOM_DATA_LIMIT;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub;
+ };
+ let item = create_max_item(&collection, &owner, sender.clone())?;
+ let data = create_data(b as usize);
+ }: {<Pallet<T>>::set_variable_metadata(&collection, &sender, item, data)?}
+}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/nonfungible/src/common.rs
@@ -0,0 +1,268 @@
+use core::marker::PhantomData;
+
+use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
+use nft_data_structs::TokenId;
+use pallet_common::{
+ CommonCollectionOperations, CommonWeightInfo, account::CrossAccountId, with_weight,
+};
+use sp_runtime::DispatchError;
+use sp_std::vec::Vec;
+
+use crate::{
+ AccountBalance, Allowance, Config, CreateItemData, Error, NonfungibleHandle, Owned, Pallet,
+ SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,
+};
+
+pub struct CommonWeights<T: Config>(PhantomData<T>);
+impl<T: Config> CommonWeightInfo for CommonWeights<T> {
+ fn create_item() -> Weight {
+ <SelfWeightOf<T>>::create_item()
+ }
+
+ fn create_multiple_items(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::create_multiple_items(amount)
+ }
+
+ fn burn_item() -> Weight {
+ <SelfWeightOf<T>>::burn_item()
+ }
+
+ fn transfer() -> Weight {
+ <SelfWeightOf<T>>::transfer()
+ }
+
+ fn approve() -> Weight {
+ <SelfWeightOf<T>>::approve()
+ }
+
+ fn transfer_from() -> Weight {
+ <SelfWeightOf<T>>::transfer_from()
+ }
+
+ fn burn_from() -> Weight {
+ 0
+ }
+
+ fn set_variable_metadata(bytes: u32) -> Weight {
+ <SelfWeightOf<T>>::set_variable_metadata(bytes)
+ }
+}
+
+fn map_create_data<T: Config>(
+ data: nft_data_structs::CreateItemData,
+ to: &T::CrossAccountId,
+) -> Result<CreateItemData<T>, DispatchError> {
+ match data {
+ nft_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData {
+ const_data: data.const_data,
+ variable_data: data.variable_data,
+ owner: to.clone(),
+ }),
+ _ => fail!(<Error<T>>::NotNonfungibleDataUsedToMintFungibleCollectionToken),
+ }
+}
+
+impl<T: Config> CommonCollectionOperations<T> for NonfungibleHandle<T> {
+ fn create_item(
+ &self,
+ sender: T::CrossAccountId,
+ to: T::CrossAccountId,
+ data: nft_data_structs::CreateItemData,
+ ) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::create_item(self, &sender, map_create_data(data, &to)?),
+ <CommonWeights<T>>::create_item(),
+ )
+ }
+
+ fn create_multiple_items(
+ &self,
+ sender: T::CrossAccountId,
+ to: T::CrossAccountId,
+ data: Vec<nft_data_structs::CreateItemData>,
+ ) -> DispatchResultWithPostInfo {
+ let data = data
+ .into_iter()
+ .map(|d| map_create_data::<T>(d, &to))
+ .collect::<Result<Vec<_>, DispatchError>>()?;
+
+ let amount = data.len();
+ with_weight(
+ <Pallet<T>>::create_multiple_items(self, &sender, data),
+ <CommonWeights<T>>::create_multiple_items(amount as u32),
+ )
+ }
+
+ fn burn_item(
+ &self,
+ sender: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+ if amount == 1 {
+ with_weight(
+ <Pallet<T>>::burn(&self, &sender, token),
+ <CommonWeights<T>>::burn_item(),
+ )
+ } else {
+ Ok(().into())
+ }
+ }
+
+ fn transfer(
+ &self,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+ if amount == 1 {
+ with_weight(
+ <Pallet<T>>::transfer(&self, &from, &to, token),
+ <CommonWeights<T>>::transfer(),
+ )
+ } else {
+ Ok(().into())
+ }
+ }
+
+ fn approve(
+ &self,
+ sender: T::CrossAccountId,
+ spender: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+
+ with_weight(
+ if amount == 1 {
+ <Pallet<T>>::set_allowance(&self, &sender, token, Some(&spender))
+ } else {
+ <Pallet<T>>::set_allowance(&self, &sender, token, None)
+ },
+ <CommonWeights<T>>::approve(),
+ )
+ }
+
+ fn transfer_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+
+ if amount == 1 {
+ with_weight(
+ <Pallet<T>>::transfer_from(&self, &sender, &from, &to, token),
+ <CommonWeights<T>>::transfer_from(),
+ )
+ } else {
+ Ok(().into())
+ }
+ }
+
+ fn burn_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+
+ if amount == 1 {
+ with_weight(
+ <Pallet<T>>::burn_from(&self, &sender, &from, token),
+ <CommonWeights<T>>::burn_from(),
+ )
+ } else {
+ Ok(().into())
+ }
+ }
+
+ fn set_variable_metadata(
+ &self,
+ sender: T::CrossAccountId,
+ token: TokenId,
+ data: Vec<u8>,
+ ) -> DispatchResultWithPostInfo {
+ let len = data.len();
+ with_weight(
+ <Pallet<T>>::set_variable_metadata(&self, &sender, token, data),
+ <CommonWeights<T>>::set_variable_metadata(len as u32),
+ )
+ }
+
+ fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
+ <Owned<T>>::iter_prefix((self.id, account.as_sub()))
+ .map(|(id, _)| id)
+ .collect()
+ }
+
+ fn token_exists(&self, token: TokenId) -> bool {
+ <Pallet<T>>::token_exists(self, token)
+ }
+
+ fn last_token_id(&self) -> TokenId {
+ TokenId(<TokensMinted<T>>::get(self.id))
+ }
+
+ fn token_owner(&self, token: TokenId) -> T::CrossAccountId {
+ <TokenData<T>>::get((self.id, token))
+ .map(|t| t.owner)
+ .unwrap_or_default()
+ }
+ fn const_metadata(&self, token: TokenId) -> Vec<u8> {
+ <TokenData<T>>::get((self.id, token))
+ .map(|t| t.const_data.clone())
+ .unwrap_or_default()
+ }
+ fn variable_metadata(&self, token: TokenId) -> Vec<u8> {
+ <TokenData<T>>::get((self.id, token))
+ .map(|t| t.variable_data.clone())
+ .unwrap_or_default()
+ }
+
+ fn collection_tokens(&self) -> u32 {
+ <Pallet<T>>::total_supply(self)
+ }
+
+ fn account_balance(&self, account: T::CrossAccountId) -> u32 {
+ <AccountBalance<T>>::get((self.id, account.as_sub()))
+ }
+
+ fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {
+ if <TokenData<T>>::get((self.id, token))
+ .map(|a| a.owner == account)
+ .unwrap_or(false)
+ {
+ 1
+ } else {
+ 0
+ }
+ }
+
+ fn allowance(
+ &self,
+ sender: T::CrossAccountId,
+ spender: T::CrossAccountId,
+ token: TokenId,
+ ) -> u128 {
+ if <TokenData<T>>::get((self.id, token))
+ .map(|a| a.owner == sender)
+ .unwrap_or(false)
+ {
+ 0
+ } else if <Allowance<T>>::get((self.id, token)) == Some(spender) {
+ 1
+ } else {
+ 0
+ }
+ }
+}
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/nonfungible/src/erc.rs
@@ -0,0 +1,414 @@
+use core::{
+ char::{REPLACEMENT_CHARACTER, decode_utf16},
+ convert::TryInto,
+};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*};
+use frame_support::BoundedVec;
+use nft_data_structs::TokenId;
+use pallet_evm_coder_substrate::dispatch_to_evm;
+use sp_core::{H160, U256};
+use sp_std::{vec::Vec, vec};
+use pallet_common::{account::CrossAccountId, erc::CommonEvmHandler};
+use pallet_evm_coder_substrate::call_internal;
+use pallet_common::erc::PrecompileOutput;
+
+use crate::{
+ AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
+};
+
+#[derive(ToLog)]
+pub enum ERC721Events {
+ Transfer {
+ #[indexed]
+ from: address,
+ #[indexed]
+ to: address,
+ #[indexed]
+ token_id: uint256,
+ },
+ Approval {
+ #[indexed]
+ owner: address,
+ #[indexed]
+ approved: address,
+ #[indexed]
+ token_id: uint256,
+ },
+ #[allow(dead_code)]
+ ApprovalForAll {
+ #[indexed]
+ owner: address,
+ #[indexed]
+ operator: address,
+ approved: bool,
+ },
+}
+
+#[derive(ToLog)]
+pub enum ERC721MintableEvents {
+ #[allow(dead_code)]
+ MintingFinished {},
+}
+
+#[solidity_interface(name = "ERC721Metadata")]
+impl<T: Config> NonfungibleHandle<T> {
+ fn name(&self) -> Result<string> {
+ Ok(decode_utf16(self.name.iter().copied())
+ .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+ .collect::<string>())
+ }
+ fn symbol(&self) -> Result<string> {
+ Ok(string::from_utf8_lossy(&self.token_prefix).into())
+ }
+
+ #[solidity(rename_selector = "tokenURI")]
+ fn token_uri(&self, token_id: uint256) -> Result<string> {
+ let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
+ Ok(string::from_utf8_lossy(
+ &<TokenData<T>>::get((self.id, token_id))
+ .ok_or("token not found")?
+ .const_data,
+ )
+ .into())
+ }
+}
+
+#[solidity_interface(name = "ERC721Enumerable")]
+impl<T: Config> NonfungibleHandle<T> {
+ fn token_by_index(&self, index: uint256) -> Result<uint256> {
+ Ok(index)
+ }
+
+ fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+
+ fn total_supply(&self) -> Result<uint256> {
+ Ok(<Pallet<T>>::total_supply(self).into())
+ }
+}
+
+#[solidity_interface(name = "ERC721", events(ERC721Events))]
+impl<T: Config> NonfungibleHandle<T> {
+ fn balance_of(&self, owner: address) -> Result<uint256> {
+ let owner = T::CrossAccountId::from_eth(owner);
+ let balance = <AccountBalance<T>>::get((self.id, owner.as_sub()));
+ Ok(balance.into())
+ }
+ fn owner_of(&self, token_id: uint256) -> Result<address> {
+ let token: TokenId = token_id.try_into()?;
+ Ok(*<TokenData<T>>::get((self.id, token))
+ .ok_or("token not found")?
+ .owner
+ .as_eth())
+ }
+ fn safe_transfer_from_with_data(
+ &mut self,
+ _from: address,
+ _to: address,
+ _token_id: uint256,
+ _data: bytes,
+ _value: value,
+ ) -> Result<void> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+ fn safe_transfer_from(
+ &mut self,
+ _from: address,
+ _to: address,
+ _token_id: uint256,
+ _value: value,
+ ) -> Result<void> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+
+ fn transfer_from(
+ &mut self,
+ caller: caller,
+ from: address,
+ to: address,
+ token_id: uint256,
+ _value: value,
+ ) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let from = T::CrossAccountId::from_eth(from);
+ let to = T::CrossAccountId::from_eth(to);
+ let token = token_id.try_into()?;
+
+ <Pallet<T>>::transfer_from(self, &caller, &from, &to, token)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ fn approve(
+ &mut self,
+ caller: caller,
+ approved: address,
+ token_id: uint256,
+ _value: value,
+ ) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let approved = T::CrossAccountId::from_eth(approved);
+ let token = token_id.try_into()?;
+
+ <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ fn set_approval_for_all(
+ &mut self,
+ _caller: caller,
+ _operator: address,
+ _approved: bool,
+ ) -> Result<void> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+
+ fn get_approved(&self, _token_id: uint256) -> Result<address> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+
+ fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {
+ // TODO: Not implemetable
+ Err("not implemented".into())
+ }
+}
+
+#[solidity_interface(name = "ERC721Burnable")]
+impl<T: Config> NonfungibleHandle<T> {
+ fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let token = token_id.try_into()?;
+
+ <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+}
+
+#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]
+impl<T: Config> NonfungibleHandle<T> {
+ fn minting_finished(&self) -> Result<bool> {
+ Ok(false)
+ }
+
+ fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let to = T::CrossAccountId::from_eth(to);
+ let token_id: u32 = token_id.try_into()?;
+ if <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ != token_id
+ {
+ return Err("item id should be next".into());
+ }
+
+ <Pallet<T>>::create_item(
+ self,
+ &caller,
+ CreateItemData {
+ const_data: BoundedVec::default(),
+ variable_data: BoundedVec::default(),
+ owner: to,
+ },
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+
+ Ok(true)
+ }
+
+ #[solidity(rename_selector = "mintWithTokenURI")]
+ fn mint_with_token_uri(
+ &mut self,
+ caller: caller,
+ to: address,
+ token_id: uint256,
+ token_uri: string,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let to = T::CrossAccountId::from_eth(to);
+ let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;
+ if <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ != token_id
+ {
+ return Err("item id should be next".into());
+ }
+
+ <Pallet<T>>::create_item(
+ self,
+ &caller,
+ CreateItemData {
+ const_data: Vec::<u8>::from(token_uri)
+ .try_into()
+ .map_err(|_| "token uri is too long")?,
+ variable_data: BoundedVec::default(),
+ owner: to,
+ },
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+
+ fn finish_minting(&mut self, _caller: caller) -> Result<bool> {
+ Err("not implementable".into())
+ }
+}
+
+#[solidity_interface(name = "ERC721UniqueExtensions")]
+impl<T: Config> NonfungibleHandle<T> {
+ fn transfer(
+ &mut self,
+ caller: caller,
+ to: address,
+ token_id: uint256,
+ _value: value,
+ ) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let to = T::CrossAccountId::from_eth(to);
+ let token = token_id.try_into()?;
+
+ <Pallet<T>>::transfer(self, &caller, &to, token).map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ fn burn_from(
+ &mut self,
+ caller: caller,
+ from: address,
+ token_id: uint256,
+ _value: value,
+ ) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let from = T::CrossAccountId::from_eth(from);
+ let token = token_id.try_into()?;
+
+ <Pallet<T>>::burn_from(self, &caller, &from, token).map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ fn next_token_id(&self) -> Result<uint256> {
+ Ok(<TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?
+ .into())
+ }
+
+ fn set_variable_metadata(
+ &mut self,
+ caller: caller,
+ token_id: uint256,
+ data: bytes,
+ ) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let token = token_id.try_into()?;
+
+ <Pallet<T>>::set_variable_metadata(self, &caller, token, data)
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {
+ let token: TokenId = token_id.try_into()?;
+
+ Ok(<TokenData<T>>::get((self.id, token))
+ .ok_or("token not found")?
+ .variable_data)
+ }
+
+ fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let to = T::CrossAccountId::from_eth(to);
+ let mut expected_index = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?;
+
+ let total_tokens = token_ids.len();
+ for id in token_ids.into_iter() {
+ let id: u32 = id.try_into().map_err(|_| "token id overflow")?;
+ if id != expected_index {
+ return Err("item id should be next".into());
+ }
+ expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
+ }
+ let data = (0..total_tokens)
+ .map(|_| CreateItemData {
+ const_data: BoundedVec::default(),
+ variable_data: BoundedVec::default(),
+ owner: to.clone(),
+ })
+ .collect();
+
+ <Pallet<T>>::create_multiple_items(self, &caller, data).map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+
+ #[solidity(rename_selector = "mintBulkWithTokenURI")]
+ fn mint_bulk_with_token_uri(
+ &mut self,
+ caller: caller,
+ to: address,
+ tokens: Vec<(uint256, string)>,
+ ) -> Result<bool> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let to = T::CrossAccountId::from_eth(to);
+ let mut expected_index = <TokensMinted<T>>::get(self.id)
+ .checked_add(1)
+ .ok_or("item id overflow")?;
+
+ let mut data = Vec::with_capacity(tokens.len());
+ for (id, token_uri) in tokens {
+ let id: u32 = id.try_into().map_err(|_| "token id overflow")?;
+ if id != expected_index {
+ panic!("item id should be next ({}) but got {}", expected_index, id);
+ }
+ expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
+
+ data.push(CreateItemData {
+ const_data: Vec::<u8>::from(token_uri)
+ .try_into()
+ .map_err(|_| "token uri is too long")?,
+ variable_data: vec![].try_into().unwrap(),
+ owner: to.clone(),
+ });
+ }
+
+ <Pallet<T>>::create_multiple_items(self, &caller, data).map_err(dispatch_to_evm::<T>)?;
+ Ok(true)
+ }
+}
+
+#[solidity_interface(
+ name = "UniqueNFT",
+ is(
+ ERC721,
+ ERC721Metadata,
+ ERC721Enumerable,
+ ERC721UniqueExtensions,
+ ERC721Mintable,
+ ERC721Burnable,
+ )
+)]
+impl<T: Config> NonfungibleHandle<T> {}
+
+// Not a tests, but code generators
+generate_stubgen!(gen_impl, UniqueNFTCall, true);
+generate_stubgen!(gen_iface, UniqueNFTCall, false);
+
+pub const CODE: &[u8] = include_bytes!("./stubs/UniqueNFT.raw");
+
+impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {
+ const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");
+
+ fn call(mut self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileOutput> {
+ let result = call_internal::<UniqueNFTCall, _>(*source, &mut self, value, input);
+ self.0.recorder.evm_to_precompile_output(result)
+ }
+}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/nonfungible/src/lib.rs
@@ -0,0 +1,564 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use erc::ERC721Events;
+use frame_support::{BoundedVec, ensure};
+use nft_data_structs::{
+ AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit, TokenId,
+};
+use pallet_common::{
+ Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
+};
+use sp_core::H160;
+use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
+use sp_std::{vec::Vec, vec};
+use core::ops::Deref;
+use sp_std::collections::btree_map::BTreeMap;
+use codec::{Encode, Decode};
+use scale_info::TypeInfo;
+
+pub use pallet::*;
+#[cfg(feature = "runtime-benchmarks")]
+pub mod benchmarking;
+pub mod common;
+pub mod erc;
+pub mod weights;
+
+pub struct CreateItemData<T: Config> {
+ pub const_data: BoundedVec<u8, CustomDataLimit>,
+ pub variable_data: BoundedVec<u8, CustomDataLimit>,
+ pub owner: T::CrossAccountId,
+}
+pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
+
+#[derive(Encode, Decode, TypeInfo)]
+pub struct ItemData<T: Config> {
+ pub const_data: Vec<u8>,
+ pub variable_data: Vec<u8>,
+ pub owner: T::CrossAccountId,
+}
+
+#[frame_support::pallet]
+pub mod pallet {
+ use super::*;
+ use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};
+ use nft_data_structs::{CollectionId, TokenId};
+ use super::weights::WeightInfo;
+
+ #[pallet::error]
+ pub enum Error<T> {
+ /// Not Nonfungible item data used to mint in Nonfungible collection.
+ NotNonfungibleDataUsedToMintFungibleCollectionToken,
+ /// Used amount > 1 with NFT
+ NonfungibleItemsHaveNoAmount,
+ }
+
+ #[pallet::config]
+ pub trait Config: frame_system::Config + pallet_common::Config {
+ type WeightInfo: WeightInfo;
+ }
+
+ #[pallet::pallet]
+ #[pallet::generate_store(pub(super) trait Store)]
+ pub struct Pallet<T>(_);
+
+ #[pallet::storage]
+ pub(super) type TokensMinted<T: Config> =
+ StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
+ #[pallet::storage]
+ pub(super) type TokensBurnt<T: Config> =
+ StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
+
+ #[pallet::storage]
+ pub(super) type TokenData<T: Config> = StorageNMap<
+ Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
+ Value = ItemData<T>,
+ QueryKind = OptionQuery,
+ >;
+
+ /// Used to enumerate tokens owned by account
+ #[pallet::storage]
+ pub(super) type Owned<T: Config> = StorageNMap<
+ Key = (
+ Key<Twox64Concat, CollectionId>,
+ Key<Blake2_128Concat, T::AccountId>,
+ Key<Twox64Concat, TokenId>,
+ ),
+ Value = bool,
+ QueryKind = ValueQuery,
+ >;
+
+ #[pallet::storage]
+ pub(super) type AccountBalance<T: Config> = StorageNMap<
+ Key = (
+ Key<Twox64Concat, CollectionId>,
+ Key<Blake2_128Concat, T::AccountId>,
+ ),
+ Value = u32,
+ QueryKind = ValueQuery,
+ >;
+
+ #[pallet::storage]
+ pub(super) type Allowance<T: Config> = StorageNMap<
+ Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
+ Value = T::CrossAccountId,
+ QueryKind = OptionQuery,
+ >;
+}
+
+pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);
+impl<T: Config> NonfungibleHandle<T> {
+ pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {
+ Self(inner)
+ }
+ pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
+ self.0
+ }
+}
+impl<T: Config> Deref for NonfungibleHandle<T> {
+ type Target = pallet_common::CollectionHandle<T>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl<T: Config> Pallet<T> {
+ pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {
+ <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)
+ }
+ pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {
+ <TokenData<T>>::contains_key((collection.id, token))
+ }
+}
+
+// unchecked calls skips any permission checks
+impl<T: Config> Pallet<T> {
+ pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
+ PalletCommon::init_collection(data)
+ }
+ pub fn destroy_collection(
+ collection: NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ ) -> DispatchResult {
+ let id = collection.id;
+
+ // =========
+
+ PalletCommon::destroy_collection(collection.0, sender)?;
+
+ <TokenData<T>>::remove_prefix((id,), None);
+ <Owned<T>>::remove_prefix((id,), None);
+ <TokensMinted<T>>::remove(id);
+ <TokensBurnt<T>>::remove(id);
+ <Allowance<T>>::remove_prefix((id,), None);
+ <AccountBalance<T>>::remove_prefix((id,), None);
+ Ok(())
+ }
+
+ pub fn burn(
+ collection: &NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ token: TokenId,
+ ) -> DispatchResult {
+ let token_data = <TokenData<T>>::get((collection.id, token))
+ .ok_or_else(|| <CommonError<T>>::TokenNotFound)?;
+ ensure!(
+ &token_data.owner == sender
+ || (collection.limits.owner_can_transfer
+ && collection.is_owner_or_admin(sender)?),
+ <CommonError<T>>::NoPermission
+ );
+
+ if collection.access == AccessMode::WhiteList {
+ collection.check_allowlist(sender)?;
+ }
+
+ let burnt = <TokensBurnt<T>>::get(collection.id)
+ .checked_add(1)
+ .ok_or(ArithmeticError::Overflow)?;
+
+ // =========
+
+ <Owned<T>>::remove((collection.id, token_data.owner.as_sub(), token));
+ <TokensBurnt<T>>::insert(collection.id, burnt);
+ <TokenData<T>>::remove((collection.id, token));
+ let old_spender = <Allowance<T>>::take((collection.id, token));
+
+ if let Some(old_spender) = old_spender {
+ <PalletCommon<T>>::deposit_event(CommonEvent::Approved(
+ collection.id,
+ token,
+ sender.clone(),
+ old_spender.clone(),
+ 0,
+ ));
+ }
+
+ collection.log_infallible(ERC721Events::Transfer {
+ from: *token_data.owner.as_eth(),
+ to: H160::default(),
+ token_id: token.into(),
+ });
+ <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
+ collection.id,
+ token,
+ token_data.owner,
+ 1,
+ ));
+ return Ok(());
+ }
+
+ pub fn transfer(
+ collection: &NonfungibleHandle<T>,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ token: TokenId,
+ ) -> DispatchResult {
+ ensure!(
+ collection.transfers_enabled,
+ <CommonError<T>>::TransferNotAllowed
+ );
+
+ let token_data = <TokenData<T>>::get((collection.id, token))
+ .ok_or_else(|| <CommonError<T>>::TokenNotFound)?;
+ ensure!(
+ &token_data.owner == from
+ || (collection.limits.owner_can_transfer && collection.is_owner_or_admin(from)?),
+ <CommonError<T>>::NoPermission
+ );
+
+ if collection.access == AccessMode::WhiteList {
+ collection.check_allowlist(from)?;
+ collection.check_allowlist(to)?;
+ }
+ <PalletCommon<T>>::ensure_correct_receiver(to)?;
+
+ let balance_from = <AccountBalance<T>>::get((collection.id, from.as_sub()))
+ .checked_sub(1)
+ .ok_or(<CommonError<T>>::TokenValueTooLow)?;
+ let balance_to = if from != to {
+ let balance_to = <AccountBalance<T>>::get((collection.id, to.as_sub()))
+ .checked_add(1)
+ .ok_or(ArithmeticError::Overflow)?;
+
+ ensure!(
+ balance_to < collection.limits.account_token_ownership_limit(),
+ <CommonError<T>>::AccountTokenLimitExceeded,
+ );
+
+ Some(balance_to)
+ } else {
+ None
+ };
+
+ collection.consume_sstores(4)?;
+ collection.consume_log(3, 0)?;
+
+ // =========
+
+ <TokenData<T>>::insert(
+ (collection.id, token),
+ ItemData {
+ owner: to.clone(),
+ ..token_data
+ },
+ );
+
+ if let Some(balance_to) = balance_to {
+ // from != to
+ if balance_from == 0 {
+ <AccountBalance<T>>::remove((collection.id, from.as_sub()));
+ } else {
+ <AccountBalance<T>>::insert((collection.id, from.as_sub()), balance_from);
+ }
+ <AccountBalance<T>>::insert((collection.id, to.as_sub()), balance_to);
+ <Owned<T>>::remove((collection.id, from.as_sub(), token));
+ <Owned<T>>::insert((collection.id, to.as_sub(), token), true);
+ }
+ Self::set_allowance_unchecked(collection, from, token, None);
+
+ collection.log_infallible(ERC721Events::Transfer {
+ from: *from.as_eth(),
+ to: *to.as_eth(),
+ token_id: token.into(),
+ });
+ <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(
+ collection.id,
+ token,
+ from.clone(),
+ to.clone(),
+ 1,
+ ));
+ Ok(())
+ }
+
+ pub fn create_multiple_items(
+ collection: &NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ data: Vec<CreateItemData<T>>,
+ ) -> DispatchResult {
+ let unrestricted_minting = collection.is_owner_or_admin(sender)?;
+ if !unrestricted_minting {
+ ensure!(
+ collection.mint_mode,
+ <CommonError<T>>::PublicMintingNotAllowed
+ );
+ collection.check_allowlist(sender)?;
+
+ for item in data.iter() {
+ collection.check_allowlist(&item.owner)?;
+ }
+ }
+
+ for data in data.iter() {
+ <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;
+ if !data.const_data.is_empty() {
+ collection.consume_sstore()?;
+ }
+ if !data.variable_data.is_empty() {
+ collection.consume_sstore()?;
+ }
+ collection.consume_sstore()?;
+ collection.consume_log(3, 0)?;
+ }
+
+ let first_token = <TokensMinted<T>>::get(collection.id);
+ let tokens_minted = first_token
+ .checked_add(data.len() as u32)
+ .ok_or(ArithmeticError::Overflow)?;
+ ensure!(
+ tokens_minted < collection.limits.token_limit,
+ <CommonError<T>>::CollectionTokenLimitExceeded
+ );
+ collection.consume_sstore()?;
+
+ let mut balances = BTreeMap::new();
+ for data in &data {
+ let balance = balances
+ .entry(data.owner.as_sub())
+ .or_insert_with(|| <AccountBalance<T>>::get((collection.id, data.owner.as_sub())));
+ *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;
+
+ ensure!(
+ *balance <= collection.limits.account_token_ownership_limit(),
+ <CommonError<T>>::AccountTokenLimitExceeded,
+ );
+ }
+ collection.consume_sstores(balances.len())?;
+
+ // =========
+
+ <TokensMinted<T>>::insert(collection.id, tokens_minted);
+ for (account, balance) in balances {
+ <AccountBalance<T>>::insert((collection.id, account), balance);
+ }
+ for (i, data) in data.into_iter().enumerate() {
+ let token = first_token + i as u32 + 1;
+
+ <TokenData<T>>::insert(
+ (collection.id, token),
+ ItemData {
+ const_data: data.const_data.into(),
+ variable_data: data.variable_data.into(),
+ owner: data.owner.clone(),
+ },
+ );
+ <Owned<T>>::insert((collection.id, data.owner.as_sub(), token), true);
+
+ collection.log_infallible(ERC721Events::Transfer {
+ from: H160::default(),
+ to: *data.owner.as_eth(),
+ token_id: token.into(),
+ });
+ <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
+ collection.id,
+ TokenId(token),
+ data.owner.clone(),
+ 1,
+ ));
+ }
+ Ok(())
+ }
+
+ pub fn set_allowance_unchecked(
+ collection: &NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ token: TokenId,
+ spender: Option<&T::CrossAccountId>,
+ ) {
+ if let Some(spender) = spender {
+ let old_spender = <Allowance<T>>::get((collection.id, token));
+ <Allowance<T>>::insert((collection.id, token), spender);
+ // In ERC721 there is only one possible approved user of token, so we set
+ // approved user to spender
+ collection.log_infallible(ERC721Events::Approval {
+ owner: *sender.as_eth(),
+ approved: *spender.as_eth(),
+ token_id: token.into(),
+ });
+ // In Unique chain, any token can have any amount of approved users, so we need to
+ // set allowance of old owner to 0, and allowance of new owner to 1
+ if old_spender.as_ref() != Some(spender) {
+ if let Some(old_owner) = old_spender {
+ <PalletCommon<T>>::deposit_event(CommonEvent::Approved(
+ collection.id,
+ token,
+ sender.clone(),
+ old_owner.clone(),
+ 0,
+ ));
+ }
+ <PalletCommon<T>>::deposit_event(CommonEvent::Approved(
+ collection.id,
+ token,
+ sender.clone(),
+ spender.clone(),
+ 1,
+ ));
+ }
+ } else {
+ let old_spender = <Allowance<T>>::take((collection.id, token));
+ // In ERC721 there is only one possible approved user of token, so we set
+ // approved user to zero address
+ collection.log_infallible(ERC721Events::Approval {
+ owner: *sender.as_eth(),
+ approved: H160::default(),
+ token_id: token.into(),
+ });
+ // In Unique chain, any token can have any amount of approved users, so we need to
+ // set allowance of old owner to 0
+ if let Some(old_spender) = old_spender {
+ <PalletCommon<T>>::deposit_event(CommonEvent::Approved(
+ collection.id,
+ token,
+ sender.clone(),
+ old_spender.clone(),
+ 0,
+ ));
+ }
+ }
+ }
+
+ pub fn set_allowance(
+ collection: &NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ token: TokenId,
+ spender: Option<&T::CrossAccountId>,
+ ) -> DispatchResult {
+ if collection.access == AccessMode::WhiteList {
+ collection.check_allowlist(&sender)?;
+ if let Some(spender) = spender {
+ collection.check_allowlist(&spender)?;
+ }
+ }
+
+ if let Some(spender) = spender {
+ <PalletCommon<T>>::ensure_correct_receiver(spender)?;
+ }
+ let token_data =
+ <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
+ if &token_data.owner != sender {
+ ensure!(
+ collection.ignores_owned_amount(sender)?,
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, sender, token, spender);
+ Ok(())
+ }
+
+ pub fn transfer_from(
+ collection: &NonfungibleHandle<T>,
+ spender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ token: TokenId,
+ ) -> DispatchResult {
+ if spender == from {
+ return Self::transfer(collection, from, to, token);
+ }
+ if collection.access == AccessMode::WhiteList {
+ // `from`, `to` checked in [`transfer`]
+ collection.check_allowlist(spender)?;
+ }
+
+ if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {
+ ensure!(
+ collection.ignores_allowance(spender)?,
+ <CommonError<T>>::TokenValueNotEnough
+ );
+ }
+
+ // =========
+
+ Self::transfer(collection, &from, to, token)?;
+ // Allowance is reset in [`transfer`]
+ Ok(())
+ }
+
+ pub fn burn_from(
+ collection: &NonfungibleHandle<T>,
+ spender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ token: TokenId,
+ ) -> DispatchResult {
+ if spender == from {
+ return Self::burn(collection, from, token);
+ }
+ if collection.access == AccessMode::WhiteList {
+ // `from` checked in [`burn`]
+ collection.check_allowlist(spender)?;
+ }
+
+ if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {
+ ensure!(
+ collection.ignores_allowance(spender)?,
+ <CommonError<T>>::TokenValueNotEnough
+ );
+ }
+
+ // =========
+
+ Self::burn(collection, &from, token)
+ }
+
+ pub fn set_variable_metadata(
+ collection: &NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ token: TokenId,
+ data: Vec<u8>,
+ ) -> DispatchResult {
+ ensure!(
+ data.len() as u32 <= CUSTOM_DATA_LIMIT,
+ <CommonError<T>>::TokenVariableDataLimitExceeded
+ );
+ let token_data =
+ <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
+ collection.check_can_update_meta(sender, &token_data.owner)?;
+
+ collection.consume_sstore()?;
+
+ // =========
+
+ <TokenData<T>>::insert(
+ (collection.id, token),
+ ItemData {
+ variable_data: data,
+ ..token_data
+ },
+ );
+ Ok(())
+ }
+
+ /// Delegated to `create_multiple_items`
+ pub fn create_item(
+ collection: &NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ data: CreateItemData<T>,
+ ) -> DispatchResult {
+ Self::create_multiple_items(collection, sender, vec![data])
+ }
+}
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- /dev/null
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -0,0 +1,330 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+// Anonymous struct
+struct Tuple0 {
+ uint256 field_0;
+ string field_1;
+}
+
+// Common stubs holder
+contract Dummy {
+ uint8 dummy;
+ string stub_error = "this contract is implemented in native";
+}
+
+contract ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID)
+ external
+ view
+ returns (bool)
+ {
+ require(false, stub_error);
+ interfaceID;
+ return true;
+ }
+}
+
+// Inline
+contract ERC721Events {
+ event Transfer(
+ address indexed from,
+ address indexed to,
+ uint256 indexed tokenId
+ );
+ event Approval(
+ address indexed owner,
+ address indexed approved,
+ uint256 indexed tokenId
+ );
+ event ApprovalForAll(
+ address indexed owner,
+ address indexed operator,
+ bool approved
+ );
+}
+
+// Inline
+contract ERC721MintableEvents {
+ event MintingFinished();
+}
+
+contract ERC721 is Dummy, ERC165, ERC721Events {
+ // Selector: balanceOf(address) 70a08231
+ function balanceOf(address owner) public view returns (uint256) {
+ require(false, stub_error);
+ owner;
+ dummy;
+ return 0;
+ }
+
+ // Selector: ownerOf(uint256) 6352211e
+ function ownerOf(uint256 tokenId) public view returns (address) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+
+ // Selector: safeTransferFromWithData(address,address,uint256,bytes) 60a11672
+ function safeTransferFromWithData(
+ address from,
+ address to,
+ uint256 tokenId,
+ bytes memory data
+ ) public {
+ require(false, stub_error);
+ from;
+ to;
+ tokenId;
+ data;
+ dummy = 0;
+ }
+
+ // Selector: safeTransferFrom(address,address,uint256) 42842e0e
+ function safeTransferFrom(
+ address from,
+ address to,
+ uint256 tokenId
+ ) public {
+ require(false, stub_error);
+ from;
+ to;
+ tokenId;
+ dummy = 0;
+ }
+
+ // Selector: transferFrom(address,address,uint256) 23b872dd
+ function transferFrom(
+ address from,
+ address to,
+ uint256 tokenId
+ ) public {
+ require(false, stub_error);
+ from;
+ to;
+ tokenId;
+ dummy = 0;
+ }
+
+ // Selector: approve(address,uint256) 095ea7b3
+ function approve(address approved, uint256 tokenId) public {
+ require(false, stub_error);
+ approved;
+ tokenId;
+ dummy = 0;
+ }
+
+ // Selector: setApprovalForAll(address,bool) a22cb465
+ function setApprovalForAll(address operator, bool approved) public {
+ require(false, stub_error);
+ operator;
+ approved;
+ dummy = 0;
+ }
+
+ // Selector: getApproved(uint256) 081812fc
+ function getApproved(uint256 tokenId) public view returns (address) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+
+ // Selector: isApprovedForAll(address,address) e985e9c5
+ function isApprovedForAll(address owner, address operator)
+ public
+ view
+ returns (address)
+ {
+ require(false, stub_error);
+ owner;
+ operator;
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+}
+
+contract ERC721Burnable is Dummy, ERC165 {
+ // Selector: burn(uint256) 42966c68
+ function burn(uint256 tokenId) public {
+ require(false, stub_error);
+ tokenId;
+ dummy = 0;
+ }
+}
+
+contract ERC721Enumerable is Dummy, ERC165 {
+ // Selector: tokenByIndex(uint256) 4f6ccce7
+ function tokenByIndex(uint256 index) public view returns (uint256) {
+ require(false, stub_error);
+ index;
+ dummy;
+ return 0;
+ }
+
+ // Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
+ function tokenOfOwnerByIndex(address owner, uint256 index)
+ public
+ view
+ returns (uint256)
+ {
+ require(false, stub_error);
+ owner;
+ index;
+ dummy;
+ return 0;
+ }
+
+ // Selector: totalSupply() 18160ddd
+ function totalSupply() public view returns (uint256) {
+ require(false, stub_error);
+ dummy;
+ return 0;
+ }
+}
+
+contract ERC721Metadata is Dummy, ERC165 {
+ // Selector: name() 06fdde03
+ function name() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ // Selector: symbol() 95d89b41
+ function symbol() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ // Selector: tokenURI(uint256) c87b56dd
+ function tokenURI(uint256 tokenId) public view returns (string memory) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return "";
+ }
+}
+
+contract ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+ // Selector: mintingFinished() 05d2035b
+ function mintingFinished() public view returns (bool) {
+ require(false, stub_error);
+ dummy;
+ return false;
+ }
+
+ // Selector: mint(address,uint256) 40c10f19
+ function mint(address to, uint256 tokenId) public returns (bool) {
+ require(false, stub_error);
+ to;
+ tokenId;
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: mintWithTokenURI(address,uint256,string) 50bb4e7f
+ function mintWithTokenURI(
+ address to,
+ uint256 tokenId,
+ string memory tokenUri
+ ) public returns (bool) {
+ require(false, stub_error);
+ to;
+ tokenId;
+ tokenUri;
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: finishMinting() 7d64bcb4
+ function finishMinting() public returns (bool) {
+ require(false, stub_error);
+ dummy = 0;
+ return false;
+ }
+}
+
+contract ERC721UniqueExtensions is Dummy, ERC165 {
+ // Selector: transfer(address,uint256) a9059cbb
+ function transfer(address to, uint256 tokenId) public {
+ require(false, stub_error);
+ to;
+ tokenId;
+ dummy = 0;
+ }
+
+ // Selector: burnFrom(address,uint256) 79cc6790
+ function burnFrom(address from, uint256 tokenId) public {
+ require(false, stub_error);
+ from;
+ tokenId;
+ dummy = 0;
+ }
+
+ // Selector: nextTokenId() 75794a3c
+ function nextTokenId() public view returns (uint256) {
+ require(false, stub_error);
+ dummy;
+ return 0;
+ }
+
+ // Selector: setVariableMetadata(uint256,bytes) d4eac26d
+ function setVariableMetadata(uint256 tokenId, bytes memory data) public {
+ require(false, stub_error);
+ tokenId;
+ data;
+ dummy = 0;
+ }
+
+ // Selector: getVariableMetadata(uint256) e6c5ce6f
+ function getVariableMetadata(uint256 tokenId)
+ public
+ view
+ returns (bytes memory)
+ {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return hex"";
+ }
+
+ // Selector: mintBulk(address,uint256[]) 44a9945e
+ function mintBulk(address to, uint256[] memory tokenIds)
+ public
+ returns (bool)
+ {
+ require(false, stub_error);
+ to;
+ tokenIds;
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
+ function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
+ public
+ returns (bool)
+ {
+ require(false, stub_error);
+ to;
+ tokens;
+ dummy = 0;
+ return false;
+ }
+}
+
+contract UniqueNFT is
+ Dummy,
+ ERC165,
+ ERC721,
+ ERC721Metadata,
+ ERC721Enumerable,
+ ERC721UniqueExtensions,
+ ERC721Mintable,
+ ERC721Burnable
+{}
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/nonfungible/src/weights.rs
@@ -0,0 +1,172 @@
+// Template adopted from https://github.com/paritytech/substrate/blob/master/.maintain/frame-weight-template.hbs
+
+//! Autogenerated weights for pallet_nonfungible
+//!
+//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
+//! DATE: 2021-10-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 128
+
+// Executed Command:
+// target/release/nft
+// benchmark
+// --pallet
+// pallet-nonfungible
+// --wasm-execution
+// compiled
+// --extrinsic
+// *
+// --template
+// .maintain/frame-weight-template.hbs
+// --steps=50
+// --repeat=20
+// --output=./pallets/nonfungible/src/weights.rs
+
+
+#![cfg_attr(rustfmt, rustfmt_skip)]
+#![allow(unused_parens)]
+#![allow(unused_imports)]
+
+use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
+use sp_std::marker::PhantomData;
+
+/// Weight functions needed for pallet_nonfungible.
+pub trait WeightInfo {
+ fn create_item() -> Weight;
+ fn create_multiple_items(b: u32, ) -> Weight;
+ fn burn_item() -> Weight;
+ fn transfer() -> Weight;
+ fn approve() -> Weight;
+ fn transfer_from() -> Weight;
+ fn set_variable_metadata(b: u32, ) -> Weight;
+}
+
+/// Weights for pallet_nonfungible using the Substrate node and recommended hardware.
+pub struct SubstrateWeight<T>(PhantomData<T>);
+impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
+ // Storage: Nonfungible TokensMinted (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:1 w:1)
+ // Storage: Nonfungible TokenData (r:0 w:1)
+ // Storage: Nonfungible Owned (r:0 w:1)
+ fn create_item() -> Weight {
+ (16_902_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(4 as Weight))
+ }
+ // Storage: Nonfungible TokensMinted (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:1 w:1)
+ // Storage: Nonfungible TokenData (r:0 w:4)
+ // Storage: Nonfungible Owned (r:0 w:4)
+ fn create_multiple_items(b: u32, ) -> Weight {
+ (15_860_000 as Weight)
+ // Standard Error: 5_000
+ .saturating_add((3_916_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(b as Weight)))
+ }
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible TokensBurnt (r:1 w:1)
+ // Storage: Nonfungible Allowance (r:1 w:0)
+ // Storage: Nonfungible Owned (r:0 w:1)
+ fn burn_item() -> Weight {
+ (17_966_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(3 as Weight))
+ .saturating_add(T::DbWeight::get().writes(3 as Weight))
+ }
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:2 w:2)
+ // Storage: Nonfungible Allowance (r:1 w:0)
+ // Storage: Nonfungible Owned (r:0 w:2)
+ fn transfer() -> Weight {
+ (23_886_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(4 as Weight))
+ .saturating_add(T::DbWeight::get().writes(5 as Weight))
+ }
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible Allowance (r:1 w:1)
+ fn approve() -> Weight {
+ (14_697_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Nonfungible Allowance (r:1 w:1)
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:2 w:2)
+ // Storage: Nonfungible Owned (r:0 w:2)
+ fn transfer_from() -> Weight {
+ (28_001_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(4 as Weight))
+ .saturating_add(T::DbWeight::get().writes(6 as Weight))
+ }
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ fn set_variable_metadata(_b: u32, ) -> Weight {
+ (6_380_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+}
+
+// For backwards compatibility and tests
+impl WeightInfo for () {
+ // Storage: Nonfungible TokensMinted (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:1 w:1)
+ // Storage: Nonfungible TokenData (r:0 w:1)
+ // Storage: Nonfungible Owned (r:0 w:1)
+ fn create_item() -> Weight {
+ (16_902_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(4 as Weight))
+ }
+ // Storage: Nonfungible TokensMinted (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:1 w:1)
+ // Storage: Nonfungible TokenData (r:0 w:4)
+ // Storage: Nonfungible Owned (r:0 w:4)
+ fn create_multiple_items(b: u32, ) -> Weight {
+ (15_860_000 as Weight)
+ // Standard Error: 5_000
+ .saturating_add((3_916_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(b as Weight)))
+ }
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible TokensBurnt (r:1 w:1)
+ // Storage: Nonfungible Allowance (r:1 w:0)
+ // Storage: Nonfungible Owned (r:0 w:1)
+ fn burn_item() -> Weight {
+ (17_966_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(3 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(3 as Weight))
+ }
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:2 w:2)
+ // Storage: Nonfungible Allowance (r:1 w:0)
+ // Storage: Nonfungible Owned (r:0 w:2)
+ fn transfer() -> Weight {
+ (23_886_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(4 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(5 as Weight))
+ }
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible Allowance (r:1 w:1)
+ fn approve() -> Weight {
+ (14_697_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Nonfungible Allowance (r:1 w:1)
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:2 w:2)
+ // Storage: Nonfungible Owned (r:0 w:2)
+ fn transfer_from() -> Weight {
+ (28_001_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(4 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(6 as Weight))
+ }
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ fn set_variable_metadata(_b: u32, ) -> Weight {
+ (6_380_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+}
pallets/refungible/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/pallets/refungible/Cargo.toml
@@ -0,0 +1,40 @@
+[package]
+name = "pallet-refungible"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies.codec]
+default-features = false
+features = ['derive']
+package = 'parity-scale-codec'
+version = '2.0.0'
+
+[dependencies]
+frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+pallet-common = { default-features = false, path = '../common' }
+nft-data-structs = { default-features = false, path = '../../primitives/nft' }
+frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+scale-info = { version = "1.0.0", default-features = false, features = [
+ "derive",
+] }
+
+[features]
+default = ["std"]
+std = [
+ "frame-support/std",
+ "frame-system/std",
+ "sp-runtime/std",
+ "sp-std/std",
+ "nft-data-structs/std",
+ "pallet-common/std",
+ 'frame-benchmarking/std',
+]
+runtime-benchmarks = [
+ 'frame-benchmarking',
+ 'frame-support/runtime-benchmarks',
+ 'frame-system/runtime-benchmarks',
+]
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/refungible/src/benchmarking.rs
@@ -0,0 +1,161 @@
+use super::*;
+use crate::{Pallet, Config, RefungibleHandle};
+
+use sp_std::prelude::*;
+use pallet_common::benchmarking::{create_collection_raw, create_data};
+use frame_benchmarking::{benchmarks, account};
+use nft_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH};
+use pallet_common::bench_init;
+use core::convert::TryInto;
+use core::iter::IntoIterator;
+
+const SEED: u32 = 1;
+
+fn create_max_item_data<T: Config>(
+ users: impl IntoIterator<Item = (T::CrossAccountId, u128)>,
+) -> CreateItemData<T> {
+ let const_data = create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap();
+ let variable_data = create_data(CUSTOM_DATA_LIMIT as usize).try_into().unwrap();
+ CreateItemData {
+ const_data,
+ variable_data,
+ users: users.into_iter().collect(),
+ }
+}
+fn create_max_item<T: Config>(
+ collection: &RefungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ users: impl IntoIterator<Item = (T::CrossAccountId, u128)>,
+) -> Result<TokenId, DispatchError> {
+ <Pallet<T>>::create_item(&collection, sender, create_max_item_data(users))?;
+ Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
+}
+
+fn create_collection<T: Config>(owner: T::AccountId) -> Result<RefungibleHandle<T>, DispatchError> {
+ create_collection_raw(
+ owner,
+ CollectionMode::NFT,
+ <Pallet<T>>::init_collection,
+ RefungibleHandle::cast,
+ )
+}
+benchmarks! {
+ create_item {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); to: cross_sub;
+ };
+ }: {create_max_item(&collection, &sender, [(to.clone(), 200)])?}
+
+ create_multiple_items {
+ let b in 0..MAX_ITEMS_PER_BATCH;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); to: cross_sub;
+ };
+ let data = (0..b).map(|_| create_max_item_data([(to.clone(), 200)])).collect();
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+
+ // Other user left, token data is kept
+ burn_item_partial {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); burner: cross_sub; another_owner: cross_sub;
+ };
+ let item = create_max_item(&collection, &sender, [(burner.clone(), 200), (another_owner, 200)])?;
+ }: {<Pallet<T>>::burn(&collection, &burner, item, 200)?}
+ // No users remaining, token is destroyed
+ burn_item_fully {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); burner: cross_sub; another_owner: cross_sub;
+ };
+ let item = create_max_item(&collection, &sender, [(burner.clone(), 200)])?;
+ }: {<Pallet<T>>::burn(&collection, &burner, item, 200)?}
+
+ transfer_normal {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); receiver: cross_sub;
+ };
+ let item = create_max_item(&collection, &sender, [(sender.clone(), 200), (receiver.clone(), 200)])?;
+ }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 100)?}
+ // Target account is created
+ transfer_creating {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); receiver: cross_sub;
+ };
+ let item = create_max_item(&collection, &sender, [(sender.clone(), 200)])?;
+ }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 100)?}
+ // Source account is destroyed
+ transfer_removing {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); receiver: cross_sub;
+ };
+ let item = create_max_item(&collection, &sender, [(sender.clone(), 200), (receiver.clone(), 200)])?;
+ }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 200)?}
+ // Source account destroyed, target created
+ transfer_creating_removing {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); receiver: cross_sub;
+ };
+ let item = create_max_item(&collection, &sender, [(sender.clone(), 200)])?;
+ }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, 200)?}
+
+ approve {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+ };
+ let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
+ }: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?}
+
+ transfer_from_normal {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+ };
+ let item = create_max_item(&collection, &owner, [(sender.clone(), 200), (receiver.clone(), 200)])?;
+ <Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?;
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100)?}
+ // Target account is created
+ transfer_from_creating {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+ };
+ let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
+ <Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?;
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100)?}
+ // Source account is destroyed
+ transfer_from_removing {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+ };
+ let item = create_max_item(&collection, &owner, [(sender.clone(), 200), (receiver.clone(), 200)])?;
+ <Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 200)?;
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200)?}
+ // Source account destroyed, target created
+ transfer_from_creating_removing {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+ };
+ let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
+ <Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 200)?;
+ }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200)?}
+
+ set_variable_metadata {
+ let b in 0..CUSTOM_DATA_LIMIT;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner);
+ };
+ let item = create_max_item(&collection, &sender, [(sender.clone(), 200)])?;
+ let data = create_data(b as usize);
+ }: {<Pallet<T>>::set_variable_metadata(&collection, &sender, item, data)?}
+}
pallets/refungible/src/common.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/refungible/src/common.rs
@@ -0,0 +1,242 @@
+use core::marker::PhantomData;
+
+use sp_std::collections::btree_map::BTreeMap;
+use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};
+use nft_data_structs::TokenId;
+use pallet_common::{
+ CommonCollectionOperations, CommonWeightInfo, account::CrossAccountId, with_weight,
+};
+use sp_runtime::DispatchError;
+use sp_std::vec::Vec;
+
+use crate::{
+ AccountBalance, Allowance, Balance, Config, CreateItemData, Error, Owned, Pallet,
+ RefungibleHandle, SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,
+};
+
+macro_rules! max_weight_of {
+ ($($method:ident ($($args:tt)*)),*) => {
+ 0
+ $(
+ .max(<SelfWeightOf<T>>::$method($($args)*))
+ )*
+ };
+}
+
+pub struct CommonWeights<T: Config>(PhantomData<T>);
+impl<T: Config> CommonWeightInfo for CommonWeights<T> {
+ fn create_item() -> Weight {
+ <SelfWeightOf<T>>::create_item()
+ }
+
+ fn create_multiple_items(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::create_multiple_items(amount)
+ }
+
+ fn burn_item() -> Weight {
+ max_weight_of!(burn_item_partial(), burn_item_fully())
+ }
+
+ fn transfer() -> Weight {
+ max_weight_of!(
+ transfer_normal(),
+ transfer_creating(),
+ transfer_removing(),
+ transfer_creating_removing()
+ )
+ }
+
+ fn approve() -> Weight {
+ <SelfWeightOf<T>>::approve()
+ }
+
+ fn transfer_from() -> Weight {
+ max_weight_of!(
+ transfer_from_normal(),
+ transfer_from_creating(),
+ transfer_from_removing(),
+ transfer_from_creating_removing()
+ )
+ }
+
+ fn burn_from() -> Weight {
+ 0
+ }
+
+ fn set_variable_metadata(bytes: u32) -> Weight {
+ <SelfWeightOf<T>>::set_variable_metadata(bytes)
+ }
+}
+
+fn map_create_data<T: Config>(
+ data: nft_data_structs::CreateItemData,
+ to: &T::CrossAccountId,
+) -> Result<CreateItemData<T>, DispatchError> {
+ match data {
+ nft_data_structs::CreateItemData::ReFungible(data) => Ok(CreateItemData {
+ const_data: data.const_data,
+ variable_data: data.variable_data,
+ users: {
+ let mut out = BTreeMap::new();
+ out.insert(to.clone(), data.pieces);
+ out
+ },
+ }),
+ _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),
+ }
+}
+
+impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {
+ fn create_item(
+ &self,
+ sender: T::CrossAccountId,
+ to: T::CrossAccountId,
+ data: nft_data_structs::CreateItemData,
+ ) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::create_item(self, &sender, map_create_data(data, &to)?),
+ <CommonWeights<T>>::create_item(),
+ )
+ }
+
+ fn create_multiple_items(
+ &self,
+ sender: T::CrossAccountId,
+ to: T::CrossAccountId,
+ data: Vec<nft_data_structs::CreateItemData>,
+ ) -> DispatchResultWithPostInfo {
+ let data = data
+ .into_iter()
+ .map(|d| map_create_data::<T>(d, &to))
+ .collect::<Result<Vec<_>, DispatchError>>()?;
+
+ let amount = data.len();
+ with_weight(
+ <Pallet<T>>::create_multiple_items(self, &sender, data),
+ <CommonWeights<T>>::create_multiple_items(amount as u32),
+ )
+ }
+
+ fn burn_item(
+ &self,
+ sender: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::burn(self, &sender, token, amount),
+ <CommonWeights<T>>::burn_item(),
+ )
+ }
+
+ fn transfer(
+ &self,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::transfer(&self, &from, &to, token, amount),
+ <CommonWeights<T>>::transfer(),
+ )
+ }
+
+ fn approve(
+ &self,
+ sender: T::CrossAccountId,
+ spender: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::set_allowance(&self, &sender, &spender, token, amount),
+ <CommonWeights<T>>::approve(),
+ )
+ }
+
+ fn transfer_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::transfer_from(&self, &sender, &from, &to, token, amount),
+ <CommonWeights<T>>::transfer_from(),
+ )
+ }
+
+ fn burn_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::burn_from(&self, &sender, &from, token, amount),
+ <CommonWeights<T>>::burn_from(),
+ )
+ }
+
+ fn set_variable_metadata(
+ &self,
+ sender: T::CrossAccountId,
+ token: TokenId,
+ data: Vec<u8>,
+ ) -> DispatchResultWithPostInfo {
+ let len = data.len();
+ with_weight(
+ <Pallet<T>>::set_variable_metadata(&self, &sender, token, data),
+ <CommonWeights<T>>::set_variable_metadata(len as u32),
+ )
+ }
+
+ fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
+ <Owned<T>>::iter_prefix((self.id, account.as_sub()))
+ .map(|(id, _)| id)
+ .collect()
+ }
+
+ fn token_exists(&self, token: TokenId) -> bool {
+ <Pallet<T>>::token_exists(self, token)
+ }
+
+ fn last_token_id(&self) -> TokenId {
+ TokenId(<TokensMinted<T>>::get(self.id))
+ }
+
+ fn token_owner(&self, _token: TokenId) -> T::CrossAccountId {
+ T::CrossAccountId::default()
+ }
+ fn const_metadata(&self, token: TokenId) -> Vec<u8> {
+ <TokenData<T>>::get((self.id, token)).const_data
+ }
+ fn variable_metadata(&self, token: TokenId) -> Vec<u8> {
+ <TokenData<T>>::get((self.id, token)).variable_data
+ }
+
+ fn collection_tokens(&self) -> u32 {
+ <Pallet<T>>::total_supply(self)
+ }
+
+ fn account_balance(&self, account: T::CrossAccountId) -> u32 {
+ <AccountBalance<T>>::get((self.id, account.as_sub()))
+ }
+
+ fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {
+ <Balance<T>>::get((self.id, token, account.as_sub()))
+ }
+
+ fn allowance(
+ &self,
+ sender: T::CrossAccountId,
+ spender: T::CrossAccountId,
+ token: TokenId,
+ ) -> u128 {
+ <Allowance<T>>::get((self.id, token, sender.as_sub(), spender))
+ }
+}
pallets/refungible/src/erc.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/refungible/src/erc.rs
@@ -0,0 +1,34 @@
+use nft_data_structs::TokenId;
+use pallet_common::erc::CommonEvmHandler;
+
+use crate::{Config, RefungibleHandle};
+
+impl<T: Config> CommonEvmHandler for RefungibleHandle<T> {
+ const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");
+
+ fn call(
+ self,
+ _source: &sp_core::H160,
+ _input: &[u8],
+ _value: sp_core::U256,
+ ) -> Option<pallet_common::erc::PrecompileOutput> {
+ // TODO: Implement RFT variant of ERC721
+ None
+ }
+}
+
+pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);
+
+impl<T: Config> CommonEvmHandler for RefungibleTokenHandle<T> {
+ const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungibleToken.raw");
+
+ fn call(
+ self,
+ _source: &sp_core::H160,
+ _input: &[u8],
+ _value: sp_core::U256,
+ ) -> Option<pallet_common::erc::PrecompileOutput> {
+ // TODO: Implement RFT variant of ERC20
+ None
+ }
+}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/refungible/src/lib.rs
@@ -0,0 +1,611 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use frame_support::{ensure, BoundedVec};
+use nft_data_structs::{
+ AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit,
+ MAX_REFUNGIBLE_PIECES, TokenId,
+};
+use pallet_common::{
+ Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
+};
+use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
+use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
+use core::ops::Deref;
+use codec::{Encode, Decode};
+use scale_info::TypeInfo;
+
+pub use pallet::*;
+#[cfg(feature = "runtime-benchmarks")]
+pub mod benchmarking;
+pub mod common;
+pub mod erc;
+pub mod weights;
+pub struct CreateItemData<T: Config> {
+ pub const_data: BoundedVec<u8, CustomDataLimit>,
+ pub variable_data: BoundedVec<u8, CustomDataLimit>,
+ pub users: BTreeMap<T::CrossAccountId, u128>,
+}
+pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
+
+#[derive(Encode, Decode, Default, TypeInfo)]
+pub struct ItemData {
+ pub const_data: Vec<u8>,
+ pub variable_data: Vec<u8>,
+}
+
+#[frame_support::pallet]
+pub mod pallet {
+ use super::*;
+ use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};
+ use nft_data_structs::{CollectionId, TokenId};
+ use super::weights::WeightInfo;
+
+ #[pallet::error]
+ pub enum Error<T> {
+ /// Not Refungible item data used to mint in Refungible collection.
+ NotRefungibleDataUsedToMintFungibleCollectionToken,
+ /// Maximum refungibility exceeded
+ WrongRefungiblePieces,
+ }
+
+ #[pallet::config]
+ pub trait Config: frame_system::Config + pallet_common::Config {
+ type WeightInfo: WeightInfo;
+ }
+
+ #[pallet::pallet]
+ #[pallet::generate_store(pub(super) trait Store)]
+ pub struct Pallet<T>(_);
+
+ #[pallet::storage]
+ pub(super) type TokensMinted<T: Config> =
+ StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
+ #[pallet::storage]
+ pub(super) type TokensBurnt<T: Config> =
+ StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
+
+ #[pallet::storage]
+ pub(super) type TokenData<T: Config> = StorageNMap<
+ Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
+ Value = ItemData,
+ QueryKind = ValueQuery,
+ >;
+
+ #[pallet::storage]
+ pub(super) type TotalSupply<T: Config> = StorageNMap<
+ Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
+ Value = u128,
+ QueryKind = ValueQuery,
+ >;
+
+ /// Used to enumerate tokens owned by account
+ #[pallet::storage]
+ pub(super) type Owned<T: Config> = StorageNMap<
+ Key = (
+ Key<Twox64Concat, CollectionId>,
+ Key<Blake2_128Concat, T::AccountId>,
+ Key<Twox64Concat, TokenId>,
+ ),
+ Value = bool,
+ QueryKind = ValueQuery,
+ >;
+
+ #[pallet::storage]
+ pub(super) type AccountBalance<T: Config> = StorageNMap<
+ Key = (
+ Key<Twox64Concat, CollectionId>,
+ // Owner
+ Key<Blake2_128Concat, T::AccountId>,
+ ),
+ Value = u32,
+ QueryKind = ValueQuery,
+ >;
+
+ #[pallet::storage]
+ pub(super) type Balance<T: Config> = StorageNMap<
+ Key = (
+ Key<Twox64Concat, CollectionId>,
+ Key<Twox64Concat, TokenId>,
+ // Owner
+ Key<Blake2_128Concat, T::AccountId>,
+ ),
+ Value = u128,
+ QueryKind = ValueQuery,
+ >;
+
+ #[pallet::storage]
+ pub(super) type Allowance<T: Config> = StorageNMap<
+ Key = (
+ Key<Twox64Concat, CollectionId>,
+ Key<Twox64Concat, TokenId>,
+ // Owner
+ Key<Blake2_128, T::AccountId>,
+ // Spender
+ Key<Blake2_128Concat, T::CrossAccountId>,
+ ),
+ Value = u128,
+ QueryKind = ValueQuery,
+ >;
+}
+
+pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);
+impl<T: Config> RefungibleHandle<T> {
+ pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {
+ Self(inner)
+ }
+ pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
+ self.0
+ }
+}
+impl<T: Config> Deref for RefungibleHandle<T> {
+ type Target = pallet_common::CollectionHandle<T>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl<T: Config> Pallet<T> {
+ pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {
+ <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)
+ }
+ pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {
+ <TotalSupply<T>>::contains_key((collection.id, token))
+ }
+}
+
+// unchecked calls skips any permission checks
+impl<T: Config> Pallet<T> {
+ pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
+ PalletCommon::init_collection(data)
+ }
+ pub fn destroy_collection(
+ collection: RefungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ ) -> DispatchResult {
+ let id = collection.id;
+
+ // =========
+
+ PalletCommon::destroy_collection(collection.0, sender)?;
+
+ <TokensMinted<T>>::remove(id);
+ <TokensBurnt<T>>::remove(id);
+ <TokenData<T>>::remove_prefix((id,), None);
+ <TotalSupply<T>>::remove_prefix((id,), None);
+ <Balance<T>>::remove_prefix((id,), None);
+ <Allowance<T>>::remove_prefix((id,), None);
+ Ok(())
+ }
+
+ pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {
+ let burnt = <TokensBurnt<T>>::get(collection.id)
+ .checked_add(1)
+ .ok_or(ArithmeticError::Overflow)?;
+
+ <TokensBurnt<T>>::insert(collection.id, burnt);
+ <TokenData<T>>::remove((collection.id, token_id));
+ <TotalSupply<T>>::remove((collection.id, token_id));
+ <Balance<T>>::remove_prefix((collection.id, token_id), None);
+ <Allowance<T>>::remove_prefix((collection.id, token_id), None);
+ // TODO: ERC721 transfer event
+ return Ok(());
+ }
+
+ pub fn burn(
+ collection: &RefungibleHandle<T>,
+ owner: &T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ let total_supply = <TotalSupply<T>>::get((collection.id, token))
+ .checked_sub(amount)
+ .ok_or(<CommonError<T>>::TokenValueTooLow)?;
+
+ // This was probally last owner of this token?
+ if total_supply == 0 {
+ // Ensure user actually owns this amount
+ ensure!(
+ <Balance<T>>::get((collection.id, token, owner.as_sub())) == amount,
+ <CommonError<T>>::TokenValueTooLow
+ );
+ let account_balance = <AccountBalance<T>>::get((collection.id, owner.as_sub()))
+ .checked_sub(1)
+ // Should not occur
+ .ok_or(ArithmeticError::Underflow)?;
+
+ // =========
+
+ <Owned<T>>::remove((collection.id, owner.as_sub(), token));
+ <AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);
+ Self::burn_token(collection, token)?;
+ <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
+ collection.id,
+ token,
+ owner.clone(),
+ amount,
+ ));
+ return Ok(());
+ }
+
+ let balance = <Balance<T>>::get((collection.id, token, owner.as_sub()))
+ .checked_sub(amount)
+ .ok_or(<CommonError<T>>::TokenValueTooLow)?;
+ let account_balance = if balance == 0 {
+ <AccountBalance<T>>::get((collection.id, owner.as_sub()))
+ .checked_sub(1)
+ // Should not occur
+ .ok_or(ArithmeticError::Underflow)?
+ } else {
+ 0
+ };
+
+ // =========
+
+ if balance == 0 {
+ <Owned<T>>::remove((collection.id, owner.as_sub(), token));
+ <Balance<T>>::remove((collection.id, token, owner.as_sub()));
+ <AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);
+ } else {
+ <Balance<T>>::insert((collection.id, token, owner.as_sub()), balance);
+ }
+ <TotalSupply<T>>::insert((collection.id, token), total_supply);
+ // TODO: ERC20 transfer event
+ <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
+ collection.id,
+ token,
+ owner.clone(),
+ amount,
+ ));
+ Ok(())
+ }
+
+ pub fn transfer(
+ collection: &RefungibleHandle<T>,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ ensure!(
+ collection.transfers_enabled,
+ <CommonError<T>>::TransferNotAllowed
+ );
+
+ if collection.access == AccessMode::WhiteList {
+ collection.check_allowlist(from)?;
+ collection.check_allowlist(to)?;
+ }
+ <PalletCommon<T>>::ensure_correct_receiver(to)?;
+
+ let balance_from = <Balance<T>>::get((collection.id, token, from.as_sub()))
+ .checked_sub(amount)
+ .ok_or(<CommonError<T>>::TokenValueTooLow)?;
+ let mut create_target = false;
+ let from_to_differ = from != to;
+ let balance_to = if from != to {
+ let old_balance = <Balance<T>>::get((collection.id, token, to.as_sub()));
+ if old_balance == 0 {
+ create_target = true;
+ }
+ Some(
+ old_balance
+ .checked_add(amount)
+ .ok_or(ArithmeticError::Overflow)?,
+ )
+ } else {
+ None
+ };
+
+ let account_balance_from = if balance_from == 0 {
+ Some(
+ <AccountBalance<T>>::get((collection.id, from.as_sub()))
+ .checked_sub(1)
+ // Should not occur
+ .ok_or(ArithmeticError::Underflow)?,
+ )
+ } else {
+ None
+ };
+ // Account data is created in token, AccountBalance should be increased
+ // But only if from != to as we shouldn't check overflow in this case
+ let account_balance_to = if create_target && from_to_differ {
+ let account_balance_to = <AccountBalance<T>>::get((collection.id, to.as_sub()))
+ .checked_add(1)
+ .ok_or(ArithmeticError::Overflow)?;
+ ensure!(
+ account_balance_to < collection.limits.account_token_ownership_limit(),
+ <CommonError<T>>::AccountTokenLimitExceeded,
+ );
+
+ Some(account_balance_to)
+ } else {
+ None
+ };
+
+ // =========
+
+ if let Some(balance_to) = balance_to {
+ // from != to
+ if balance_from == 0 {
+ <Balance<T>>::remove((collection.id, token, from.as_sub()));
+ } else {
+ <Balance<T>>::insert((collection.id, token, from.as_sub()), balance_from);
+ }
+ <Balance<T>>::insert((collection.id, token, to.as_sub()), balance_to);
+ if let Some(account_balance_from) = account_balance_from {
+ <AccountBalance<T>>::insert((collection.id, from.as_sub()), account_balance_from);
+ <Owned<T>>::remove((collection.id, from.as_sub(), token));
+ }
+ if let Some(account_balance_to) = account_balance_to {
+ <AccountBalance<T>>::insert((collection.id, to.as_sub()), account_balance_to);
+ <Owned<T>>::insert((collection.id, to.as_sub(), token), true);
+ }
+ }
+
+ // TODO: ERC20 transfer event
+ <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(
+ collection.id,
+ token,
+ from.clone(),
+ to.clone(),
+ amount,
+ ));
+ Ok(())
+ }
+
+ pub fn create_multiple_items(
+ collection: &RefungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ data: Vec<CreateItemData<T>>,
+ ) -> DispatchResult {
+ let unrestricted_minting = collection.is_owner_or_admin(sender)?;
+ if !unrestricted_minting {
+ ensure!(
+ collection.mint_mode,
+ <CommonError<T>>::PublicMintingNotAllowed
+ );
+ collection.check_allowlist(sender)?;
+
+ for item in data.iter() {
+ for (user, _) in &item.users {
+ collection.check_allowlist(&user)?;
+ }
+ }
+ }
+
+ for item in data.iter() {
+ for (owner, _) in item.users.iter() {
+ <PalletCommon<T>>::ensure_correct_receiver(owner)?;
+ }
+ }
+
+ // Total pieces per tokens
+ let totals = data
+ .iter()
+ .map(|data| {
+ Ok(data
+ .users
+ .iter()
+ .map(|u| u.1)
+ .try_fold(0u128, |acc, v| acc.checked_add(*v))
+ .ok_or(ArithmeticError::Overflow)?)
+ })
+ .collect::<Result<Vec<_>, DispatchError>>()?;
+ for total in &totals {
+ ensure!(
+ *total <= MAX_REFUNGIBLE_PIECES,
+ <Error<T>>::WrongRefungiblePieces
+ );
+ }
+
+ let first_token_id = <TokensMinted<T>>::get(collection.id);
+ let tokens_minted = first_token_id
+ .checked_add(data.len() as u32)
+ .ok_or(ArithmeticError::Overflow)?;
+ ensure!(
+ tokens_minted < collection.limits.token_limit,
+ <CommonError<T>>::CollectionTokenLimitExceeded
+ );
+
+ let mut balances = BTreeMap::new();
+ for data in &data {
+ for (owner, _) in &data.users {
+ let balance = balances
+ .entry(owner.as_sub())
+ .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner.as_sub())));
+ *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;
+
+ ensure!(
+ *balance <= collection.limits.account_token_ownership_limit(),
+ <CommonError<T>>::AccountTokenLimitExceeded,
+ );
+ }
+ }
+
+ // =========
+
+ <TokensMinted<T>>::insert(collection.id, tokens_minted);
+ for (account, balance) in balances {
+ <AccountBalance<T>>::insert((collection.id, account), balance);
+ }
+ for (i, token) in data.into_iter().enumerate() {
+ let token_id = first_token_id + i as u32 + 1;
+ <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);
+
+ <TokenData<T>>::insert(
+ (collection.id, token_id),
+ ItemData {
+ const_data: token.const_data.into(),
+ variable_data: token.variable_data.into(),
+ },
+ );
+ for (user, amount) in token.users.into_iter() {
+ if amount == 0 {
+ continue;
+ }
+ <Balance<T>>::insert((collection.id, token_id, user.as_sub()), amount);
+ <Owned<T>>::insert((collection.id, user.as_sub(), TokenId(token_id)), true);
+ // TODO: ERC20 transfer event
+ <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
+ collection.id,
+ TokenId(token_id),
+ user,
+ amount,
+ ));
+ }
+ }
+ Ok(())
+ }
+
+ pub fn set_allowance_unchecked(
+ collection: &RefungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) {
+ <Allowance<T>>::insert((collection.id, token, sender.as_sub(), spender), amount);
+ // TODO: ERC20 approval event
+ <PalletCommon<T>>::deposit_event(CommonEvent::Approved(
+ collection.id,
+ token,
+ sender.clone(),
+ spender.clone(),
+ amount,
+ ))
+ }
+
+ pub fn set_allowance(
+ collection: &RefungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ if collection.access == AccessMode::WhiteList {
+ collection.check_allowlist(&sender)?;
+ collection.check_allowlist(&spender)?;
+ }
+
+ <PalletCommon<T>>::ensure_correct_receiver(spender)?;
+
+ if <Balance<T>>::get((collection.id, token, sender.as_sub())) < amount {
+ ensure!(
+ collection.ignores_owned_amount(sender)?,
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, sender, spender, token, amount);
+ Ok(())
+ }
+
+ pub fn transfer_from(
+ collection: &RefungibleHandle<T>,
+ spender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ if spender == from {
+ return Self::transfer(collection, from, to, token, amount);
+ }
+ if collection.access == AccessMode::WhiteList {
+ // `from`, `to` checked in [`transfer`]
+ collection.check_allowlist(spender)?;
+ }
+
+ let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))
+ .checked_sub(amount);
+ if allowance.is_none() {
+ ensure!(
+ collection.ignores_allowance(spender)?,
+ <CommonError<T>>::TokenValueNotEnough
+ );
+ }
+
+ // =========
+
+ Self::transfer(collection, from, to, token, amount)?;
+ if let Some(allowance) = allowance {
+ Self::set_allowance_unchecked(collection, from, spender, token, allowance);
+ }
+ Ok(())
+ }
+
+ pub fn burn_from(
+ collection: &RefungibleHandle<T>,
+ spender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ if spender == from {
+ return Self::burn(collection, from, token, amount);
+ }
+ if collection.access == AccessMode::WhiteList {
+ // `from` checked in [`burn`]
+ collection.check_allowlist(spender)?;
+ }
+
+ let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))
+ .checked_sub(amount);
+ if allowance.is_none() {
+ ensure!(
+ collection.ignores_allowance(spender)?,
+ <CommonError<T>>::TokenValueNotEnough
+ );
+ }
+
+ // =========
+
+ Self::burn(collection, from, token, amount)?;
+ if let Some(allowance) = allowance {
+ Self::set_allowance_unchecked(collection, from, spender, token, allowance);
+ }
+ Ok(())
+ }
+
+ pub fn set_variable_metadata(
+ collection: &RefungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ token: TokenId,
+ data: Vec<u8>,
+ ) -> DispatchResult {
+ ensure!(
+ data.len() as u32 <= CUSTOM_DATA_LIMIT,
+ <CommonError<T>>::TokenVariableDataLimitExceeded
+ );
+ collection.check_can_update_meta(
+ sender,
+ &T::CrossAccountId::from_sub(collection.owner.clone()),
+ )?;
+
+ collection.consume_sstore()?;
+ let token_data = <TokenData<T>>::get((collection.id, token));
+
+ // =========
+
+ <TokenData<T>>::insert(
+ (collection.id, token),
+ ItemData {
+ variable_data: data,
+ ..token_data
+ },
+ );
+ Ok(())
+ }
+
+ /// Delegated to `create_multiple_items`
+ pub fn create_item(
+ collection: &RefungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ data: CreateItemData<T>,
+ ) -> DispatchResult {
+ Self::create_multiple_items(collection, sender, vec![data])
+ }
+}
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterboth--- /dev/null
+++ b/pallets/refungible/src/stubs/UniqueRefungible.raw
@@ -0,0 +1 @@
+TODO
pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterboth--- /dev/null
+++ b/pallets/refungible/src/stubs/UniqueRefungibleToken.raw
@@ -0,0 +1 @@
+TODO
pallets/refungible/src/weights.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/refungible/src/weights.rs
@@ -0,0 +1,301 @@
+// Template adopted from https://github.com/paritytech/substrate/blob/master/.maintain/frame-weight-template.hbs
+
+//! Autogenerated weights for pallet_refungible
+//!
+//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
+//! DATE: 2021-10-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 128
+
+// Executed Command:
+// target/release/nft
+// benchmark
+// --pallet
+// pallet-refungible
+// --wasm-execution
+// compiled
+// --extrinsic
+// *
+// --template
+// .maintain/frame-weight-template.hbs
+// --steps=50
+// --repeat=20
+// --output=./pallets/refungible/src/weights.rs
+
+
+#![cfg_attr(rustfmt, rustfmt_skip)]
+#![allow(unused_parens)]
+#![allow(unused_imports)]
+
+use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
+use sp_std::marker::PhantomData;
+
+/// Weight functions needed for pallet_refungible.
+pub trait WeightInfo {
+ fn create_item() -> Weight;
+ fn create_multiple_items(b: u32, ) -> Weight;
+ fn burn_item_partial() -> Weight;
+ fn burn_item_fully() -> Weight;
+ fn transfer_normal() -> Weight;
+ fn transfer_creating() -> Weight;
+ fn transfer_removing() -> Weight;
+ fn transfer_creating_removing() -> Weight;
+ fn approve() -> Weight;
+ fn transfer_from_normal() -> Weight;
+ fn transfer_from_creating() -> Weight;
+ fn transfer_from_removing() -> Weight;
+ fn transfer_from_creating_removing() -> Weight;
+ fn set_variable_metadata(b: u32, ) -> Weight;
+}
+
+/// Weights for pallet_refungible using the Substrate node and recommended hardware.
+pub struct SubstrateWeight<T>(PhantomData<T>);
+impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
+ // Storage: Refungible TokensMinted (r:1 w:1)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Balance (r:0 w:1)
+ // Storage: Refungible TotalSupply (r:0 w:1)
+ // Storage: Refungible TokenData (r:0 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn create_item() -> Weight {
+ (18_681_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(6 as Weight))
+ }
+ // Storage: Refungible TokensMinted (r:1 w:1)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Balance (r:0 w:4)
+ // Storage: Refungible TotalSupply (r:0 w:4)
+ // Storage: Refungible TokenData (r:0 w:4)
+ // Storage: Refungible Owned (r:0 w:4)
+ fn create_multiple_items(b: u32, ) -> Weight {
+ (13_869_000 as Weight)
+ // Standard Error: 28_000
+ .saturating_add((5_611_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
+ }
+ // Storage: Refungible TotalSupply (r:1 w:1)
+ // Storage: Refungible Balance (r:1 w:1)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn burn_item_partial() -> Weight {
+ (21_591_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(3 as Weight))
+ .saturating_add(T::DbWeight::get().writes(4 as Weight))
+ }
+ // Storage: Refungible TotalSupply (r:1 w:1)
+ // Storage: Refungible Balance (r:1 w:1)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible TokensBurnt (r:1 w:1)
+ // Storage: Refungible TokenData (r:0 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn burn_item_fully() -> Weight {
+ (29_257_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(4 as Weight))
+ .saturating_add(T::DbWeight::get().writes(6 as Weight))
+ }
+ // Storage: Refungible Balance (r:2 w:2)
+ fn transfer_normal() -> Weight {
+ (17_733_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn transfer_creating() -> Weight {
+ (20_943_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(3 as Weight))
+ .saturating_add(T::DbWeight::get().writes(4 as Weight))
+ }
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn transfer_removing() -> Weight {
+ (22_406_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(3 as Weight))
+ .saturating_add(T::DbWeight::get().writes(4 as Weight))
+ }
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:2 w:2)
+ // Storage: Refungible Owned (r:0 w:2)
+ fn transfer_creating_removing() -> Weight {
+ (24_762_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(4 as Weight))
+ .saturating_add(T::DbWeight::get().writes(6 as Weight))
+ }
+ // Storage: Refungible Balance (r:1 w:0)
+ // Storage: Refungible Allowance (r:0 w:1)
+ fn approve() -> Weight {
+ (14_109_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Refungible Allowance (r:1 w:1)
+ // Storage: Refungible Balance (r:2 w:2)
+ fn transfer_from_normal() -> Weight {
+ (25_348_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(3 as Weight))
+ .saturating_add(T::DbWeight::get().writes(3 as Weight))
+ }
+ // Storage: Refungible Allowance (r:1 w:1)
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn transfer_from_creating() -> Weight {
+ (28_647_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(4 as Weight))
+ .saturating_add(T::DbWeight::get().writes(5 as Weight))
+ }
+ // Storage: Refungible Allowance (r:1 w:1)
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn transfer_from_removing() -> Weight {
+ (30_472_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(4 as Weight))
+ .saturating_add(T::DbWeight::get().writes(5 as Weight))
+ }
+ // Storage: Refungible Allowance (r:1 w:1)
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:2 w:2)
+ // Storage: Refungible Owned (r:0 w:2)
+ fn transfer_from_creating_removing() -> Weight {
+ (32_362_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(5 as Weight))
+ .saturating_add(T::DbWeight::get().writes(7 as Weight))
+ }
+ // Storage: Refungible TokenData (r:1 w:1)
+ fn set_variable_metadata(_b: u32, ) -> Weight {
+ (6_801_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+}
+
+// For backwards compatibility and tests
+impl WeightInfo for () {
+ // Storage: Refungible TokensMinted (r:1 w:1)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Balance (r:0 w:1)
+ // Storage: Refungible TotalSupply (r:0 w:1)
+ // Storage: Refungible TokenData (r:0 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn create_item() -> Weight {
+ (18_681_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(6 as Weight))
+ }
+ // Storage: Refungible TokensMinted (r:1 w:1)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Balance (r:0 w:4)
+ // Storage: Refungible TotalSupply (r:0 w:4)
+ // Storage: Refungible TokenData (r:0 w:4)
+ // Storage: Refungible Owned (r:0 w:4)
+ fn create_multiple_items(b: u32, ) -> Weight {
+ (13_869_000 as Weight)
+ // Standard Error: 28_000
+ .saturating_add((5_611_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
+ }
+ // Storage: Refungible TotalSupply (r:1 w:1)
+ // Storage: Refungible Balance (r:1 w:1)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn burn_item_partial() -> Weight {
+ (21_591_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(3 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(4 as Weight))
+ }
+ // Storage: Refungible TotalSupply (r:1 w:1)
+ // Storage: Refungible Balance (r:1 w:1)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible TokensBurnt (r:1 w:1)
+ // Storage: Refungible TokenData (r:0 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn burn_item_fully() -> Weight {
+ (29_257_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(4 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(6 as Weight))
+ }
+ // Storage: Refungible Balance (r:2 w:2)
+ fn transfer_normal() -> Weight {
+ (17_733_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn transfer_creating() -> Weight {
+ (20_943_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(3 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(4 as Weight))
+ }
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn transfer_removing() -> Weight {
+ (22_406_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(3 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(4 as Weight))
+ }
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:2 w:2)
+ // Storage: Refungible Owned (r:0 w:2)
+ fn transfer_creating_removing() -> Weight {
+ (24_762_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(4 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(6 as Weight))
+ }
+ // Storage: Refungible Balance (r:1 w:0)
+ // Storage: Refungible Allowance (r:0 w:1)
+ fn approve() -> Weight {
+ (14_109_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Refungible Allowance (r:1 w:1)
+ // Storage: Refungible Balance (r:2 w:2)
+ fn transfer_from_normal() -> Weight {
+ (25_348_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(3 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(3 as Weight))
+ }
+ // Storage: Refungible Allowance (r:1 w:1)
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn transfer_from_creating() -> Weight {
+ (28_647_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(4 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(5 as Weight))
+ }
+ // Storage: Refungible Allowance (r:1 w:1)
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:1 w:1)
+ // Storage: Refungible Owned (r:0 w:1)
+ fn transfer_from_removing() -> Weight {
+ (30_472_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(4 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(5 as Weight))
+ }
+ // Storage: Refungible Allowance (r:1 w:1)
+ // Storage: Refungible Balance (r:2 w:2)
+ // Storage: Refungible AccountBalance (r:2 w:2)
+ // Storage: Refungible Owned (r:0 w:2)
+ fn transfer_from_creating_removing() -> Weight {
+ (32_362_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(5 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(7 as Weight))
+ }
+ // Storage: Refungible TokenData (r:1 w:1)
+ fn set_variable_metadata(_b: u32, ) -> Weight {
+ (6_801_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+}
primitives/nft/src/lib.rsdiffbeforeafterboth--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -1,10 +1,13 @@
#![cfg_attr(not(feature = "std"), no_std)]
+use core::convert::{TryFrom, TryInto};
+
#[cfg(feature = "serde")]
pub use serde::{Serialize, Deserialize};
-use sp_runtime::sp_std::prelude::Vec;
-use codec::{Decode, Encode, MaxEncodedLen};
+use sp_core::U256;
+use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};
+use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
pub use frame_support::{
BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,
dispatch::DispatchResult,
@@ -67,8 +70,48 @@
pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;
}
-pub type CollectionId = u32;
-pub type TokenId = u32;
+#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct CollectionId(pub u32);
+impl EncodeLike<u32> for CollectionId {}
+impl EncodeLike<CollectionId> for u32 {}
+
+#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct TokenId(pub u32);
+impl EncodeLike<u32> for TokenId {}
+impl EncodeLike<TokenId> for u32 {}
+
+impl TokenId {
+ pub fn try_next(self) -> Result<TokenId, ArithmeticError> {
+ self.0
+ .checked_add(1)
+ .ok_or(ArithmeticError::Overflow)
+ .map(Self)
+ }
+}
+
+impl From<TokenId> for U256 {
+ fn from(t: TokenId) -> Self {
+ t.0.into()
+ }
+}
+
+impl TryFrom<U256> for TokenId {
+ type Error = &'static str;
+
+ fn try_from(value: U256) -> Result<Self, Self::Error> {
+ Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))
+ }
+}
+
+pub struct OverflowError;
+impl From<OverflowError> for &'static str {
+ fn from(_: OverflowError) -> Self {
+ "overflow occured"
+ }
+}
+
pub type DecimalPoints = u8;
#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]
@@ -167,7 +210,6 @@
pub owner: T::AccountId,
pub mode: CollectionMode,
pub access: AccessMode,
- pub decimal_points: DecimalPoints,
pub name: Vec<u16>, // 64 include null escape char
pub description: Vec<u16>, // 256 include null escape char
pub token_prefix: Vec<u8>, // 16 include null escape char
@@ -207,7 +249,7 @@
#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct CollectionLimits<BlockNumber: Encode + Decode> {
- pub account_token_ownership_limit: u32,
+ pub account_token_ownership_limit: Option<u32>,
pub sponsored_data_size: u32,
/// None - setVariableMetadata is not sponsored
/// Some(v) - setVariableMetadata is sponsored
@@ -221,10 +263,18 @@
pub owner_can_destroy: bool,
}
+impl<BlockNumber: Encode + Decode> CollectionLimits<BlockNumber> {
+ pub fn account_token_ownership_limit(&self) -> u32 {
+ self.account_token_ownership_limit
+ .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)
+ .min(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)
+ }
+}
+
impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {
fn default() -> Self {
Self {
- account_token_ownership_limit: 10_000_000,
+ account_token_ownership_limit: Some(10_000_000),
token_limit: u32::max_value(),
sponsored_data_size: u32::MAX,
sponsored_data_rate_limit: None,
primitives/rpc/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/primitives/rpc/Cargo.toml
@@ -0,0 +1,27 @@
+[package]
+name = "up-rpc"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+pallet-common = { default-features = false, path = '../../pallets/common' }
+nft-data-structs = { default-features = false, path = '../nft' }
+codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [
+ "derive",
+] }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-api = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+
+[features]
+default = ["std"]
+std = [
+ "codec/std",
+ "sp-core/std",
+ "sp-std/std",
+ "sp-api/std",
+ "sp-runtime/std",
+ "pallet-common/std",
+ "nft-data-structs/std",
+]
primitives/rpc/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/primitives/rpc/src/lib.rs
@@ -0,0 +1,37 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use nft_data_structs::{CollectionId, TokenId};
+use sp_std::vec::Vec;
+use sp_core::H160;
+use codec::Decode;
+
+sp_api::decl_runtime_apis! {
+ pub trait NftApi<CrossAccountId, AccountId> where
+ AccountId: Decode,
+ CrossAccountId: pallet_common::account::CrossAccountId<AccountId>,
+ {
+ fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>;
+ fn token_exists(collection: CollectionId, token: TokenId) -> bool;
+
+ fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId;
+ fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>;
+ fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>;
+
+ fn collection_tokens(collection: CollectionId) -> u32;
+ fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32;
+ fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128;
+ fn allowance(
+ collection: CollectionId,
+ sender: CrossAccountId,
+ spender: CrossAccountId,
+ token: TokenId,
+ ) -> u128;
+
+ /// Used for ethereum integration
+ fn eth_contract_code(account: H160) -> Option<Vec<u8>>;
+
+ fn adminlist(collection: CollectionId) -> Vec<AccountId>;
+ fn allowlist(collection: CollectionId) -> Vec<AccountId>;
+ fn last_token_id(collection: CollectionId) -> TokenId;
+ }
+}
runtime/Cargo.tomldiffbeforeafterboth--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -26,6 +26,10 @@
'pallet-evm-migration/runtime-benchmarks',
'pallet-balances/runtime-benchmarks',
'pallet-timestamp/runtime-benchmarks',
+ 'pallet-common/runtime-benchmarks',
+ 'pallet-fungible/runtime-benchmarks',
+ 'pallet-refungible/runtime-benchmarks',
+ 'pallet-nonfungible/runtime-benchmarks',
'pallet-nft/runtime-benchmarks',
'pallet-inflation/runtime-benchmarks',
'pallet-xcm/runtime-benchmarks',
@@ -64,10 +68,15 @@
'pallet-evm-coder-substrate/std',
'pallet-ethereum/std',
'fp-rpc/std',
+ 'up-rpc/std',
'fp-self-contained/std',
'parachain-info/std',
'serde',
'pallet-inflation/std',
+ 'pallet-common/std',
+ 'pallet-fungible/std',
+ 'pallet-refungible/std',
+ 'pallet-nonfungible/std',
'pallet-nft/std',
'pallet-unq-scheduler/std',
'pallet-nft-charge-transaction/std',
@@ -156,19 +165,19 @@
# [dependencies.pallet-contracts]
# git = 'https://github.com/paritytech/substrate.git'
# default-features = false
-# branch = 'polkadot-v0.9.9'
+# branch = 'polkadot-v0.9.12'
# version = '4.0.0-dev'
# [dependencies.pallet-contracts-primitives]
# git = 'https://github.com/paritytech/substrate.git'
# default-features = false
-# branch = 'polkadot-v0.9.9'
+# branch = 'polkadot-v0.9.12'
# version = '4.0.0-dev'
# [dependencies.pallet-contracts-rpc-runtime-api]
# git = 'https://github.com/paritytech/substrate.git'
# default-features = false
-# branch = 'polkadot-v0.9.9'
+# branch = 'polkadot-v0.9.12'
# version = '4.0.0-dev'
[dependencies.pallet-randomness-collective-flip]
@@ -355,11 +364,18 @@
# local dependencies
[dependencies]
-scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
+scale-info = { version = "1.0.0", default-features = false, features = [
+ "derive",
+] }
derivative = "2.2.0"
pallet-nft = { path = '../pallets/nft', default-features = false, version = '3.0.0' }
+up-rpc = { path = "../primitives/rpc", default-features = false }
pallet-inflation = { path = '../pallets/inflation', default-features = false, version = '3.0.0' }
nft-data-structs = { path = '../primitives/nft', default-features = false, version = '0.9.0' }
+pallet-common = { default-features = false, path = "../pallets/common" }
+pallet-fungible = { default-features = false, path = "../pallets/fungible" }
+pallet-refungible = { default-features = false, path = "../pallets/refungible" }
+pallet-nonfungible = { default-features = false, path = "../pallets/nonfungible" }
pallet-unq-scheduler = { path = '../pallets/scheduler', default-features = false, version = '3.0.0' }
# pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
pallet-nft-transaction-payment = { path = '../pallets/nft-transaction-payment', default-features = false, version = '3.0.0' }
runtime/src/lib.rsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24 traits::{25 AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,26 AccountIdConversion,27 },28 transaction_validity::{TransactionSource, TransactionValidity},29 ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{38 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,39};40// A few exports that help ease life for downstream crates.41pub use pallet_balances::Call as BalancesCall;42pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};43pub use frame_support::{44 construct_runtime, match_type,45 dispatch::DispatchResult,46 PalletId, parameter_types, StorageValue, ConsensusEngineId,47 traits::{48 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,49 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,50 },51 weights::{52 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},53 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,54 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,55 },56};57use nft_data_structs::*;58// use pallet_contracts::weights::WeightInfo;59// #[cfg(any(feature = "std", test))]60use frame_system::{61 self as system, EnsureRoot, EnsureSigned,62 limits::{BlockWeights, BlockLength},63};64use sp_arithmetic::{65 traits::{BaseArithmetic, Unsigned},66};67use smallvec::smallvec;68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;72use sp_runtime::{73 traits::{Dispatchable, PostDispatchInfoOf},74 transaction_validity::TransactionValidityError,75};7677// pub use pallet_timestamp::Call as TimestampCall;78pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7980// Polkadot imports81use pallet_xcm::XcmPassthrough;82use polkadot_parachain::primitives::Sibling;83use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};84use xcm_builder::{85 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,86 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,87 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,88 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,89 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,90};91use xcm_executor::{Config, XcmExecutor};9293// mod chain_extension;94// use crate::chain_extension::{NFTExtension, Imbalance};9596/// An index to a block.97pub type BlockNumber = u32;9899/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.100pub type Signature = MultiSignature;101102/// Some way of identifying an account on the chain. We intentionally make it equivalent103/// to the public key of our transaction signing scheme.104pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;105106/// The type for looking up accounts. We don't expect more than 4 billion of them, but you107/// never know...108pub type AccountIndex = u32;109110/// Balance of an account.111pub type Balance = u128;112113/// Index of a transaction in the chain.114pub type Index = u32;115116/// A hash of some data used by the chain.117pub type Hash = sp_core::H256;118119/// Digest item type.120pub type DigestItem = generic::DigestItem<Hash>;121122/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know123/// the specifics of the runtime. They can then be made to be agnostic over specific formats124/// of data like extrinsics, allowing for them to continue syncing the network through upgrades125/// to even the core data structures.126pub mod opaque {127 use super::*;128129 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;130131 /// Opaque block type.132 pub type Block = generic::Block<Header, UncheckedExtrinsic>;133134 pub type SessionHandlers = ();135136 impl_opaque_keys! {137 pub struct SessionKeys {138 pub aura: Aura,139 }140 }141}142143/// This runtime version.144pub const VERSION: RuntimeVersion = RuntimeVersion {145 spec_name: create_runtime_str!("opal"),146 impl_name: create_runtime_str!("opal"),147 authoring_version: 1,148 spec_version: 912200,149 impl_version: 1,150 apis: RUNTIME_API_VERSIONS,151 transaction_version: 1,152};153154pub const MILLISECS_PER_BLOCK: u64 = 12000;155156pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;157158// These time units are defined in number of blocks.159pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);160pub const HOURS: BlockNumber = MINUTES * 60;161pub const DAYS: BlockNumber = HOURS * 24;162163parameter_types! {164 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;165}166167#[derive(codec::Encode, codec::Decode)]168pub enum XCMPMessage<XAccountId, XBalance> {169 /// Transfer tokens to the given account from the Parachain account.170 TransferToken(XAccountId, XBalance),171}172173/// The version information used to identify this runtime when compiled natively.174#[cfg(feature = "std")]175pub fn native_version() -> NativeVersion {176 NativeVersion {177 runtime_version: VERSION,178 can_author_with: Default::default(),179 }180}181182type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;183184pub struct DealWithFees;185impl OnUnbalanced<NegativeImbalance> for DealWithFees {186 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {187 if let Some(fees) = fees_then_tips.next() {188 // for fees, 100% to treasury189 let mut split = fees.ration(100, 0);190 if let Some(tips) = fees_then_tips.next() {191 // for tips, if any, 100% to treasury192 tips.ration_merge_into(100, 0, &mut split);193 }194 Treasury::on_unbalanced(split.0);195 // Author::on_unbalanced(split.1);196 }197 }198}199200/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.201/// This is used to limit the maximal weight of a single extrinsic.202const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);203/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used204/// by Operational extrinsics.205const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);206/// We allow for 2 seconds of compute with a 6 second average block time.207const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;208209parameter_types! {210 pub const BlockHashCount: BlockNumber = 2400;211 pub RuntimeBlockLength: BlockLength =212 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);213 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);214 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;215 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()216 .base_block(BlockExecutionWeight::get())217 .for_class(DispatchClass::all(), |weights| {218 weights.base_extrinsic = ExtrinsicBaseWeight::get();219 })220 .for_class(DispatchClass::Normal, |weights| {221 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);222 })223 .for_class(DispatchClass::Operational, |weights| {224 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);225 // Operational transactions have some extra reserved space, so that they226 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.227 weights.reserved = Some(228 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT229 );230 })231 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)232 .build_or_panic();233 pub const Version: RuntimeVersion = VERSION;234 pub const SS58Prefix: u8 = 42;235}236237parameter_types! {238 pub const ChainId: u64 = 8888;239}240241pub struct FixedFee;242impl FeeCalculator for FixedFee {243 fn min_gas_price() -> U256 {244 1.into()245 }246}247248impl pallet_evm::Config for Runtime {249 type BlockGasLimit = BlockGasLimit;250 type FeeCalculator = FixedFee;251 type GasWeightMapping = ();252 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;253 type CallOrigin = EnsureAddressTruncated;254 type WithdrawOrigin = EnsureAddressTruncated;255 type AddressMapping = HashedAddressMapping<Self::Hashing>;256 type Precompiles = ();257 type Currency = Balances;258 type Event = Event;259 type OnMethodCall = (260 pallet_evm_migration::OnMethodCall<Self>,261 pallet_nft::NftErcSupport<Self>,262 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,263 );264 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;265 type ChainId = ChainId;266 type Runner = pallet_evm::runner::stack::Runner<Self>;267 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;268 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;269 type FindAuthor = EthereumFindAuthor<Aura>;270}271272impl pallet_evm_migration::Config for Runtime {273 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;274}275276pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);277impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {278 fn find_author<'a, I>(digests: I) -> Option<H160>279 where280 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,281 {282 if let Some(author_index) = F::find_author(digests) {283 let authority_id = Aura::authorities()[author_index as usize].clone();284 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));285 }286 None287 }288}289290parameter_types! {291 pub BlockGasLimit: U256 = U256::from(u32::max_value());292}293294impl pallet_ethereum::Config for Runtime {295 type Event = Event;296 type StateRoot = pallet_ethereum::IntermediateStateRoot;297 type EvmSubmitLog = pallet_evm::Pallet<Self>;298}299300impl pallet_randomness_collective_flip::Config for Runtime {}301302impl system::Config for Runtime {303 /// The data to be stored in an account.304 type AccountData = pallet_balances::AccountData<Balance>;305 /// The identifier used to distinguish between accounts.306 type AccountId = AccountId;307 /// The basic call filter to use in dispatchable.308 type BaseCallFilter = Everything;309 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).310 type BlockHashCount = BlockHashCount;311 /// The maximum length of a block (in bytes).312 type BlockLength = RuntimeBlockLength;313 /// The index type for blocks.314 type BlockNumber = BlockNumber;315 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.316 type BlockWeights = RuntimeBlockWeights;317 /// The aggregated dispatch type that is available for extrinsics.318 type Call = Call;319 /// The weight of database operations that the runtime can invoke.320 type DbWeight = RocksDbWeight;321 /// The ubiquitous event type.322 type Event = Event;323 /// The type for hashing blocks and tries.324 type Hash = Hash;325 /// The hashing algorithm used.326 type Hashing = BlakeTwo256;327 /// The header type.328 type Header = generic::Header<BlockNumber, BlakeTwo256>;329 /// The index type for storing how many extrinsics an account has signed.330 type Index = Index;331 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.332 type Lookup = AccountIdLookup<AccountId, ()>;333 /// What to do if an account is fully reaped from the system.334 type OnKilledAccount = ();335 /// What to do if a new account is created.336 type OnNewAccount = ();337 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;338 /// The ubiquitous origin type.339 type Origin = Origin;340 /// This type is being generated by `construct_runtime!`.341 type PalletInfo = PalletInfo;342 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.343 type SS58Prefix = SS58Prefix;344 /// Weight information for the extrinsics of this pallet.345 type SystemWeightInfo = system::weights::SubstrateWeight<Self>;346 /// Version of the runtime.347 type Version = Version;348}349350parameter_types! {351 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;352}353354impl pallet_timestamp::Config for Runtime {355 /// A timestamp: milliseconds since the unix epoch.356 type Moment = u64;357 type OnTimestampSet = ();358 type MinimumPeriod = MinimumPeriod;359 type WeightInfo = ();360}361362parameter_types! {363 // pub const ExistentialDeposit: u128 = 500;364 pub const ExistentialDeposit: u128 = 0;365 pub const MaxLocks: u32 = 50;366}367368impl pallet_balances::Config for Runtime {369 type MaxLocks = MaxLocks;370 type MaxReserves = ();371 type ReserveIdentifier = [u8; 8];372 /// The type for recording an account's balance.373 type Balance = Balance;374 /// The ubiquitous event type.375 type Event = Event;376 type DustRemoval = Treasury;377 type ExistentialDeposit = ExistentialDeposit;378 type AccountStore = System;379 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;380}381382pub const MICROUNIQUE: Balance = 1_000_000_000;383pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;384pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;385pub const UNIQUE: Balance = 100 * CENTIUNIQUE;386387pub const fn deposit(items: u32, bytes: u32) -> Balance {388 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE389}390391/*392parameter_types! {393 pub TombstoneDeposit: Balance = deposit(394 1,395 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,396 );397 pub DepositPerContract: Balance = TombstoneDeposit::get();398 pub const DepositPerStorageByte: Balance = deposit(0, 1);399 pub const DepositPerStorageItem: Balance = deposit(1, 0);400 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);401 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;402 pub const SignedClaimHandicap: u32 = 2;403 pub const MaxDepth: u32 = 32;404 pub const MaxValueSize: u32 = 16 * 1024;405 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb406 // The lazy deletion runs inside on_initialize.407 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *408 RuntimeBlockWeights::get().max_block;409 // The weight needed for decoding the queue should be less or equal than a fifth410 // of the overall weight dedicated to the lazy deletion.411 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (412 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -413 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)414 )) / 5) as u32;415 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();416}417418impl pallet_contracts::Config for Runtime {419 type Time = Timestamp;420 type Randomness = RandomnessCollectiveFlip;421 type Currency = Balances;422 type Event = Event;423 type RentPayment = ();424 type SignedClaimHandicap = SignedClaimHandicap;425 type TombstoneDeposit = TombstoneDeposit;426 type DepositPerContract = DepositPerContract;427 type DepositPerStorageByte = DepositPerStorageByte;428 type DepositPerStorageItem = DepositPerStorageItem;429 type RentFraction = RentFraction;430 type SurchargeReward = SurchargeReward;431 type WeightPrice = pallet_transaction_payment::Pallet<Self>;432 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;433 type ChainExtension = NFTExtension;434 type DeletionQueueDepth = DeletionQueueDepth;435 type DeletionWeightLimit = DeletionWeightLimit;436 type Schedule = Schedule;437 type CallStack = [pallet_contracts::Frame<Self>; 31];438}439*/440441parameter_types! {442 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer443 /// This value increases the priority of `Operational` transactions by adding444 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.445 pub const OperationalFeeMultiplier: u8 = 5;446}447448/// Linear implementor of `WeightToFeePolynomial`449pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);450451impl<T> WeightToFeePolynomial for LinearFee<T>452where453 T: BaseArithmetic + From<u32> + Copy + Unsigned,454{455 type Balance = T;456457 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {458 smallvec!(WeightToFeeCoefficient {459 coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer460 coeff_frac: Perbill::zero(),461 negative: false,462 degree: 1,463 })464 }465}466467impl pallet_transaction_payment::Config for Runtime {468 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;469 type TransactionByteFee = TransactionByteFee;470 type OperationalFeeMultiplier = OperationalFeeMultiplier;471 type WeightToFee = LinearFee<Balance>;472 type FeeMultiplierUpdate = ();473}474475parameter_types! {476 pub const ProposalBond: Permill = Permill::from_percent(5);477 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;478 pub const SpendPeriod: BlockNumber = 5 * MINUTES;479 pub const Burn: Permill = Permill::from_percent(0);480 pub const TipCountdown: BlockNumber = 1 * DAYS;481 pub const TipFindersFee: Percent = Percent::from_percent(20);482 pub const TipReportDepositBase: Balance = 1 * UNIQUE;483 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;484 pub const BountyDepositBase: Balance = 1 * UNIQUE;485 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;486 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");487 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;488 pub const MaximumReasonLength: u32 = 16384;489 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);490 pub const BountyValueMinimum: Balance = 5 * UNIQUE;491 pub const MaxApprovals: u32 = 100;492}493494impl pallet_treasury::Config for Runtime {495 type PalletId = TreasuryModuleId;496 type Currency = Balances;497 type ApproveOrigin = EnsureRoot<AccountId>;498 type RejectOrigin = EnsureRoot<AccountId>;499 type Event = Event;500 type OnSlash = ();501 type ProposalBond = ProposalBond;502 type ProposalBondMinimum = ProposalBondMinimum;503 type SpendPeriod = SpendPeriod;504 type Burn = Burn;505 type BurnDestination = ();506 type SpendFunds = ();507 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;508 type MaxApprovals = MaxApprovals;509}510511impl pallet_sudo::Config for Runtime {512 type Event = Event;513 type Call = Call;514}515516parameter_types! {517 pub const MinVestedTransfer: Balance = 10 * UNIQUE;518}519520impl pallet_vesting::Config for Runtime {521 type Event = Event;522 type Currency = Balances;523 type BlockNumberToBalance = ConvertInto;524 type MinVestedTransfer = MinVestedTransfer;525 type WeightInfo = ();526 const MAX_VESTING_SCHEDULES: u32 = 28;527}528529parameter_types! {530 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;531 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;532}533534impl cumulus_pallet_parachain_system::Config for Runtime {535 type Event = Event;536 type OnValidationData = ();537 type SelfParaId = parachain_info::Pallet<Self>;538 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<539 // MaxDownwardMessageWeight,540 // XcmExecutor<XcmConfig>,541 // Call,542 // >;543 type OutboundXcmpMessageSource = XcmpQueue;544 type DmpMessageHandler = DmpQueue;545 type ReservedDmpWeight = ReservedDmpWeight;546 type ReservedXcmpWeight = ReservedXcmpWeight;547 type XcmpMessageHandler = XcmpQueue;548}549550impl parachain_info::Config for Runtime {}551552impl cumulus_pallet_aura_ext::Config for Runtime {}553554parameter_types! {555 pub const RelayLocation: MultiLocation = MultiLocation::parent();556 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;557 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();558 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();559}560561/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used562/// when determining ownership of accounts for asset transacting and when attempting to use XCM563/// `Transact` in order to determine the dispatch Origin.564pub type LocationToAccountId = (565 // The parent (Relay-chain) origin converts to the default `AccountId`.566 ParentIsDefault<AccountId>,567 // Sibling parachain origins convert to AccountId via the `ParaId::into`.568 SiblingParachainConvertsVia<Sibling, AccountId>,569 // Straight up local `AccountId32` origins just alias directly to `AccountId`.570 AccountId32Aliases<RelayNetwork, AccountId>,571);572573/// Means for transacting assets on this chain.574pub type LocalAssetTransactor = CurrencyAdapter<575 // Use this currency:576 Balances,577 // Use this currency when it is a fungible asset matching the given location or name:578 IsConcrete<RelayLocation>,579 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:580 LocationToAccountId,581 // Our chain's account ID type (we can't get away without mentioning it explicitly):582 AccountId,583 // We don't track any teleports.584 (),585>;586587/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,588/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can589/// biases the kind of local `Origin` it will become.590pub type XcmOriginToTransactDispatchOrigin = (591 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location592 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for593 // foreign chains who want to have a local sovereign account on this chain which they control.594 SovereignSignedViaLocation<LocationToAccountId, Origin>,595 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when596 // recognised.597 RelayChainAsNative<RelayOrigin, Origin>,598 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when599 // recognised.600 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,601 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a602 // transaction from the Root origin.603 ParentAsSuperuser<Origin>,604 // Native signed account converter; this just converts an `AccountId32` origin into a normal605 // `Origin::Signed` origin of the same 32-byte value.606 SignedAccountId32AsNative<RelayNetwork, Origin>,607 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.608 XcmPassthrough<Origin>,609);610611parameter_types! {612 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.613 pub UnitWeightCost: Weight = 1_000_000;614 // 1200 UNIQUEs buy 1 second of weight.615 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);616 pub const MaxInstructions: u32 = 100;617 pub const MaxAuthorities: u32 = 100_000;618}619620match_type! {621 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {622 MultiLocation { parents: 1, interior: Here } |623 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }624 };625}626627pub type Barrier = (628 TakeWeightCredit,629 AllowTopLevelPaidExecutionFrom<Everything>,630 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,631 // ^^^ Parent & its unit plurality gets free execution632);633634pub struct XcmConfig;635impl Config for XcmConfig {636 type Call = Call;637 type XcmSender = XcmRouter;638 // How to withdraw and deposit an asset.639 type AssetTransactor = LocalAssetTransactor;640 type OriginConverter = XcmOriginToTransactDispatchOrigin;641 type IsReserve = NativeAsset;642 type IsTeleporter = (); // Teleportation is disabled643 type LocationInverter = LocationInverter<Ancestry>;644 type Barrier = Barrier;645 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;646 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;647 type ResponseHandler = (); // Don't handle responses for now.648 type SubscriptionService = PolkadotXcm;649650 type AssetTrap = PolkadotXcm;651 type AssetClaims = PolkadotXcm;652}653654// parameter_types! {655// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;656// }657658/// No local origins on this chain are allowed to dispatch XCM sends/executions.659pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);660661/// The means for routing XCM messages which are not for local execution into the right message662/// queues.663pub type XcmRouter = (664 // Two routers - use UMP to communicate with the relay chain:665 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,666 // ..and XCMP to communicate with the sibling chains.667 XcmpQueue,668);669670impl pallet_evm_coder_substrate::Config for Runtime {671 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;672}673674impl pallet_xcm::Config for Runtime {675 type Event = Event;676 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;677 type XcmRouter = XcmRouter;678 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;679 type XcmExecuteFilter = Everything;680 type XcmExecutor = XcmExecutor<XcmConfig>;681 type XcmTeleportFilter = Everything;682 type XcmReserveTransferFilter = Everything;683 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;684 type LocationInverter = LocationInverter<Ancestry>;685 type Origin = Origin;686 type Call = Call;687 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;688 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;689}690691impl cumulus_pallet_xcm::Config for Runtime {692 type Event = Event;693 type XcmExecutor = XcmExecutor<XcmConfig>;694}695696impl cumulus_pallet_xcmp_queue::Config for Runtime {697 type Event = Event;698 type XcmExecutor = XcmExecutor<XcmConfig>;699 type ChannelInfo = ParachainSystem;700 type VersionWrapper = ();701}702703impl cumulus_pallet_dmp_queue::Config for Runtime {704 type Event = Event;705 type XcmExecutor = XcmExecutor<XcmConfig>;706 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;707}708709impl pallet_aura::Config for Runtime {710 type AuthorityId = AuraId;711 type DisabledValidators = ();712 type MaxAuthorities = MaxAuthorities;713}714715parameter_types! {716 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();717 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;718}719720/// Used for the pallet nft in `./nft.rs`721impl pallet_nft::Config for Runtime {722 type Event = Event;723 type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;724725 type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;726 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;727 type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;728729 type Currency = Balances;730 type CollectionCreationPrice = CollectionCreationPrice;731 type TreasuryAccountId = TreasuryAccountId;732}733734parameter_types! {735 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied736}737738/// Used for the pallet inflation739impl pallet_inflation::Config for Runtime {740 type Currency = Balances;741 type TreasuryAccountId = TreasuryAccountId;742 type InflationBlockInterval = InflationBlockInterval;743}744745parameter_types! {746 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *747 RuntimeBlockWeights::get().max_block;748 pub const MaxScheduledPerBlock: u32 = 50;749}750751pub struct Sponsoring;752impl SponsoringResolve<AccountId, Call> for Sponsoring {753 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>754 where755 Call: Dispatchable<Info = DispatchInfo>,756 AccountId: AsRef<[u8]>,757 {758 pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)759 }760}761762type SponsorshipHandler = (763 pallet_nft::NftSponsorshipHandler<Runtime>,764 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,765);766767impl pallet_unq_scheduler::Config for Runtime {768 type Event = Event;769 type Origin = Origin;770 type PalletsOrigin = OriginCaller;771 type Call = Call;772 type MaximumWeight = MaximumSchedulerWeight;773 type ScheduleOrigin = EnsureSigned<AccountId>;774 type MaxScheduledPerBlock = MaxScheduledPerBlock;775 type SponsorshipHandler = SponsorshipHandler;776 type WeightInfo = ();777}778779impl pallet_nft_transaction_payment::Config for Runtime {780 type SponsorshipHandler = SponsorshipHandler;781}782783impl pallet_evm_transaction_payment::Config for Runtime {784 type SponsorshipHandler = (785 pallet_nft::NftEthSponsorshipHandler<Self>,786 pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,787 );788 type Currency = Balances;789}790791impl pallet_nft_charge_transaction::Config for Runtime {}792793// impl pallet_contract_helpers::Config for Runtime {794// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;795// }796797parameter_types! {798 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049799 pub const HelpersContractAddress: H160 = H160([800 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,801 ]);802}803804impl pallet_evm_contract_helpers::Config for Runtime {805 type ContractAddress = HelpersContractAddress;806 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;807}808809construct_runtime!(810 pub enum Runtime where811 Block = Block,812 NodeBlock = opaque::Block,813 UncheckedExtrinsic = UncheckedExtrinsic814 {815 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,816 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,817818 Aura: pallet_aura::{Pallet, Config<T>} = 22,819 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,820821 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,822 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,823 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,824 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,825 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,826 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,827 System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,828 Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,829 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,830831 // XCM helpers.832 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,833 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,834 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,835 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,836837 // Unique Pallets838 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,839 Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>} = 61,840 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,841 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,842 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,843 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,844845 // Frontier846 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,847 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,848849 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,850 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,851 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,852 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,853 }854);855856pub struct TransactionConverter;857858impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {859 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {860 UncheckedExtrinsic::new_unsigned(861 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),862 )863 }864}865866impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {867 fn convert_transaction(868 &self,869 transaction: pallet_ethereum::Transaction,870 ) -> opaque::UncheckedExtrinsic {871 let extrinsic = UncheckedExtrinsic::new_unsigned(872 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),873 );874 let encoded = extrinsic.encode();875 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])876 .expect("Encoded extrinsic is always valid")877 }878}879880/// The address format for describing accounts.881pub type Address = sp_runtime::MultiAddress<AccountId, ()>;882/// Block header type as expected by this runtime.883pub type Header = generic::Header<BlockNumber, BlakeTwo256>;884/// Block type as expected by this runtime.885pub type Block = generic::Block<Header, UncheckedExtrinsic>;886/// A Block signed with a Justification887pub type SignedBlock = generic::SignedBlock<Block>;888/// BlockId type as expected by this runtime.889pub type BlockId = generic::BlockId<Block>;890/// The SignedExtension to the basic transaction logic.891pub type SignedExtra = (892 system::CheckSpecVersion<Runtime>,893 // system::CheckTxVersion<Runtime>,894 system::CheckGenesis<Runtime>,895 system::CheckEra<Runtime>,896 system::CheckNonce<Runtime>,897 system::CheckWeight<Runtime>,898 pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,899 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,900);901/// Unchecked extrinsic type as expected by this runtime.902pub type UncheckedExtrinsic =903 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;904/// Extrinsic type that has already been checked.905pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;906/// Executive: handles dispatch to the various modules.907pub type Executive = frame_executive::Executive<908 Runtime,909 Block,910 frame_system::ChainContext<Runtime>,911 Runtime,912 AllPallets,913>;914915impl_opaque_keys! {916 pub struct SessionKeys {917 pub aura: Aura,918 }919}920921impl fp_self_contained::SelfContainedCall for Call {922 type SignedInfo = H160;923924 fn is_self_contained(&self) -> bool {925 match self {926 Call::Ethereum(call) => call.is_self_contained(),927 _ => false,928 }929 }930931 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {932 match self {933 Call::Ethereum(call) => call.check_self_contained(),934 _ => None,935 }936 }937938 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {939 match self {940 Call::Ethereum(call) => call.validate_self_contained(info),941 _ => None,942 }943 }944945 fn pre_dispatch_self_contained(946 &self,947 info: &Self::SignedInfo,948 ) -> Option<Result<(), TransactionValidityError>> {949 match self {950 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),951 _ => None,952 }953 }954955 fn apply_self_contained(956 self,957 info: Self::SignedInfo,958 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {959 match self {960 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(961 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),962 )),963 _ => None,964 }965 }966}967968impl_runtime_apis! {969 impl pallet_nft::NftApi<Block>970 for Runtime971 {972 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))974 }975 }976977 impl sp_api::Core<Block> for Runtime {978 fn version() -> RuntimeVersion {979 VERSION980 }981982 fn execute_block(block: Block) {983 Executive::execute_block(block)984 }985986 fn initialize_block(header: &<Block as BlockT>::Header) {987 Executive::initialize_block(header)988 }989 }990991 impl sp_api::Metadata<Block> for Runtime {992 fn metadata() -> OpaqueMetadata {993 OpaqueMetadata::new(Runtime::metadata().into())994 }995 }996997 impl sp_block_builder::BlockBuilder<Block> for Runtime {998 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {999 Executive::apply_extrinsic(extrinsic)1000 }10011002 fn finalize_block() -> <Block as BlockT>::Header {1003 Executive::finalize_block()1004 }10051006 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1007 data.create_extrinsics()1008 }10091010 fn check_inherents(1011 block: Block,1012 data: sp_inherents::InherentData,1013 ) -> sp_inherents::CheckInherentsResult {1014 data.check_extrinsics(&block)1015 }10161017 // fn random_seed() -> <Block as BlockT>::Hash {1018 // RandomnessCollectiveFlip::random_seed().01019 // }1020 }10211022 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1023 fn validate_transaction(1024 source: TransactionSource,1025 tx: <Block as BlockT>::Extrinsic,1026 hash: <Block as BlockT>::Hash,1027 ) -> TransactionValidity {1028 Executive::validate_transaction(source, tx, hash)1029 }1030 }10311032 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1033 fn offchain_worker(header: &<Block as BlockT>::Header) {1034 Executive::offchain_worker(header)1035 }1036 }10371038 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1039 fn chain_id() -> u64 {1040 <Runtime as pallet_evm::Config>::ChainId::get()1041 }10421043 fn account_basic(address: H160) -> EVMAccount {1044 EVM::account_basic(&address)1045 }10461047 fn gas_price() -> U256 {1048 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1049 }10501051 fn account_code_at(address: H160) -> Vec<u8> {1052 EVM::account_codes(address)1053 }10541055 fn author() -> H160 {1056 <pallet_evm::Pallet<Runtime>>::find_author()1057 }10581059 fn storage_at(address: H160, index: U256) -> H256 {1060 let mut tmp = [0u8; 32];1061 index.to_big_endian(&mut tmp);1062 EVM::account_storages(address, H256::from_slice(&tmp[..]))1063 }10641065 fn call(1066 from: H160,1067 to: H160,1068 data: Vec<u8>,1069 value: U256,1070 gas_limit: U256,1071 gas_price: Option<U256>,1072 nonce: Option<U256>,1073 estimate: bool,1074 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1075 let config = if estimate {1076 let mut config = <Runtime as pallet_evm::Config>::config().clone();1077 config.estimate = true;1078 Some(config)1079 } else {1080 None1081 };10821083 <Runtime as pallet_evm::Config>::Runner::call(1084 from,1085 to,1086 data,1087 value,1088 gas_limit.low_u64(),1089 gas_price,1090 nonce,1091 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1092 ).map_err(|err| err.into())1093 }10941095 fn create(1096 from: H160,1097 data: Vec<u8>,1098 value: U256,1099 gas_limit: U256,1100 gas_price: Option<U256>,1101 nonce: Option<U256>,1102 estimate: bool,1103 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1104 let config = if estimate {1105 let mut config = <Runtime as pallet_evm::Config>::config().clone();1106 config.estimate = true;1107 Some(config)1108 } else {1109 None1110 };11111112 <Runtime as pallet_evm::Config>::Runner::create(1113 from,1114 data,1115 value,1116 gas_limit.low_u64(),1117 gas_price,1118 nonce,1119 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1120 ).map_err(|err| err.into())1121 }11221123 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1124 Ethereum::current_transaction_statuses()1125 }11261127 fn current_block() -> Option<pallet_ethereum::Block> {1128 Ethereum::current_block()1129 }11301131 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1132 Ethereum::current_receipts()1133 }11341135 fn current_all() -> (1136 Option<pallet_ethereum::Block>,1137 Option<Vec<pallet_ethereum::Receipt>>,1138 Option<Vec<TransactionStatus>>1139 ) {1140 (1141 Ethereum::current_block(),1142 Ethereum::current_receipts(),1143 Ethereum::current_transaction_statuses()1144 )1145 }11461147 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1148 xts.into_iter().filter_map(|xt| match xt.0.function {1149 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1150 _ => None1151 }).collect()1152 }1153 }11541155 impl sp_session::SessionKeys<Block> for Runtime {1156 fn decode_session_keys(1157 encoded: Vec<u8>,1158 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1159 SessionKeys::decode_into_raw_public_keys(&encoded)1160 }11611162 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1163 SessionKeys::generate(seed)1164 }1165 }11661167 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1168 fn slot_duration() -> sp_consensus_aura::SlotDuration {1169 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1170 }11711172 fn authorities() -> Vec<AuraId> {1173 Aura::authorities().to_vec()1174 }1175 }11761177 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1178 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1179 ParachainSystem::collect_collation_info()1180 }1181 }11821183 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1184 fn account_nonce(account: AccountId) -> Index {1185 System::account_nonce(account)1186 }1187 }11881189 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1190 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1191 TransactionPayment::query_info(uxt, len)1192 }1193 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1194 TransactionPayment::query_fee_details(uxt, len)1195 }1196 }11971198 /*1199 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1200 for Runtime1201 {1202 fn call(1203 origin: AccountId,1204 dest: AccountId,1205 value: Balance,1206 gas_limit: u64,1207 input_data: Vec<u8>,1208 ) -> pallet_contracts_primitives::ContractExecResult {1209 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1210 }12111212 fn instantiate(1213 origin: AccountId,1214 endowment: Balance,1215 gas_limit: u64,1216 code: pallet_contracts_primitives::Code<Hash>,1217 data: Vec<u8>,1218 salt: Vec<u8>,1219 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1220 {1221 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1222 }12231224 fn get_storage(1225 address: AccountId,1226 key: [u8; 32],1227 ) -> pallet_contracts_primitives::GetStorageResult {1228 Contracts::get_storage(address, key)1229 }12301231 fn rent_projection(1232 address: AccountId,1233 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1234 Contracts::rent_projection(address)1235 }1236 }1237 */12381239 #[cfg(feature = "runtime-benchmarks")]1240 impl frame_benchmarking::Benchmark<Block> for Runtime {1241 fn dispatch_benchmark(1242 config: frame_benchmarking::BenchmarkConfig1243 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1244 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};12451246 let whitelist: Vec<TrackedStorageKey> = vec![1247 // Alice account1248 hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),1249 // // Total Issuance1250 // hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1251 // // Execution Phase1252 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1253 // // Event Count1254 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1255 // // System Events1256 // hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1257 ];12581259 let mut batches = Vec::<BenchmarkBatch>::new();1260 let params = (&config, &whitelist);12611262 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1263 add_benchmark!(params, batches, pallet_nft, Nft);1264 add_benchmark!(params, batches, pallet_inflation, Inflation);12651266 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1267 Ok(batches)1268 }1269 }1270}12711272struct CheckInherents;12731274impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1275 fn check_inherents(1276 block: &Block,1277 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1278 ) -> sp_inherents::CheckInherentsResult {1279 let relay_chain_slot = relay_state_proof1280 .read_slot()1281 .expect("Could not read the relay chain slot from the proof");12821283 let inherent_data =1284 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1285 relay_chain_slot,1286 sp_std::time::Duration::from_secs(6),1287 )1288 .create_inherent_data()1289 .expect("Could not create the timestamp inherent data");12901291 inherent_data.check_extrinsics(block)1292 }1293}12941295cumulus_pallet_parachain_system::register_validate_block!(1296 Runtime = Runtime,1297 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1298 CheckInherents = CheckInherents,1299);1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24 traits::{25 AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,26 AccountIdConversion,27 },28 transaction_validity::{TransactionSource, TransactionValidity},29 ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{38 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,39};40// A few exports that help ease life for downstream crates.41pub use pallet_balances::Call as BalancesCall;42pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};43pub use frame_support::{44 construct_runtime, match_type,45 dispatch::DispatchResult,46 PalletId, parameter_types, StorageValue, ConsensusEngineId,47 traits::{48 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,49 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,50 },51 weights::{52 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},53 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,54 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,55 },56};57use nft_data_structs::*;58// use pallet_contracts::weights::WeightInfo;59// #[cfg(any(feature = "std", test))]60use frame_system::{61 self as system, EnsureRoot, EnsureSigned,62 limits::{BlockWeights, BlockLength},63};64use sp_arithmetic::{65 traits::{BaseArithmetic, Unsigned},66};67use smallvec::smallvec;68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;72use sp_runtime::{73 traits::{Dispatchable, PostDispatchInfoOf},74 transaction_validity::TransactionValidityError,75};7677// pub use pallet_timestamp::Call as TimestampCall;78pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7980// Polkadot imports81use pallet_xcm::XcmPassthrough;82use polkadot_parachain::primitives::Sibling;83use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};84use xcm_builder::{85 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,86 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,87 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,88 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,89 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,90};91use xcm_executor::{Config, XcmExecutor};9293// mod chain_extension;94// use crate::chain_extension::{NFTExtension, Imbalance};9596/// An index to a block.97pub type BlockNumber = u32;9899/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.100pub type Signature = MultiSignature;101102/// Some way of identifying an account on the chain. We intentionally make it equivalent103/// to the public key of our transaction signing scheme.104pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;105106pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;107108/// The type for looking up accounts. We don't expect more than 4 billion of them, but you109/// never know...110pub type AccountIndex = u32;111112/// Balance of an account.113pub type Balance = u128;114115/// Index of a transaction in the chain.116pub type Index = u32;117118/// A hash of some data used by the chain.119pub type Hash = sp_core::H256;120121/// Digest item type.122pub type DigestItem = generic::DigestItem<Hash>;123124/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know125/// the specifics of the runtime. They can then be made to be agnostic over specific formats126/// of data like extrinsics, allowing for them to continue syncing the network through upgrades127/// to even the core data structures.128pub mod opaque {129 use super::*;130131 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;132133 /// Opaque block type.134 pub type Block = generic::Block<Header, UncheckedExtrinsic>;135136 pub type SessionHandlers = ();137138 impl_opaque_keys! {139 pub struct SessionKeys {140 pub aura: Aura,141 }142 }143}144145/// This runtime version.146pub const VERSION: RuntimeVersion = RuntimeVersion {147 spec_name: create_runtime_str!("opal"),148 impl_name: create_runtime_str!("opal"),149 authoring_version: 1,150 spec_version: 912200,151 impl_version: 1,152 apis: RUNTIME_API_VERSIONS,153 transaction_version: 1,154};155156pub const MILLISECS_PER_BLOCK: u64 = 12000;157158pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;159160// These time units are defined in number of blocks.161pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);162pub const HOURS: BlockNumber = MINUTES * 60;163pub const DAYS: BlockNumber = HOURS * 24;164165parameter_types! {166 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;167}168169#[derive(codec::Encode, codec::Decode)]170pub enum XCMPMessage<XAccountId, XBalance> {171 /// Transfer tokens to the given account from the Parachain account.172 TransferToken(XAccountId, XBalance),173}174175/// The version information used to identify this runtime when compiled natively.176#[cfg(feature = "std")]177pub fn native_version() -> NativeVersion {178 NativeVersion {179 runtime_version: VERSION,180 can_author_with: Default::default(),181 }182}183184type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;185186pub struct DealWithFees;187impl OnUnbalanced<NegativeImbalance> for DealWithFees {188 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {189 if let Some(fees) = fees_then_tips.next() {190 // for fees, 100% to treasury191 let mut split = fees.ration(100, 0);192 if let Some(tips) = fees_then_tips.next() {193 // for tips, if any, 100% to treasury194 tips.ration_merge_into(100, 0, &mut split);195 }196 Treasury::on_unbalanced(split.0);197 // Author::on_unbalanced(split.1);198 }199 }200}201202/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.203/// This is used to limit the maximal weight of a single extrinsic.204const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);205/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used206/// by Operational extrinsics.207const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);208/// We allow for 2 seconds of compute with a 6 second average block time.209const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;210211parameter_types! {212 pub const BlockHashCount: BlockNumber = 2400;213 pub RuntimeBlockLength: BlockLength =214 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);215 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);216 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;217 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()218 .base_block(BlockExecutionWeight::get())219 .for_class(DispatchClass::all(), |weights| {220 weights.base_extrinsic = ExtrinsicBaseWeight::get();221 })222 .for_class(DispatchClass::Normal, |weights| {223 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);224 })225 .for_class(DispatchClass::Operational, |weights| {226 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);227 // Operational transactions have some extra reserved space, so that they228 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.229 weights.reserved = Some(230 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT231 );232 })233 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)234 .build_or_panic();235 pub const Version: RuntimeVersion = VERSION;236 pub const SS58Prefix: u8 = 42;237}238239parameter_types! {240 pub const ChainId: u64 = 8888;241}242243pub struct FixedFee;244impl FeeCalculator for FixedFee {245 fn min_gas_price() -> U256 {246 1.into()247 }248}249250impl pallet_evm::Config for Runtime {251 type BlockGasLimit = BlockGasLimit;252 type FeeCalculator = FixedFee;253 type GasWeightMapping = ();254 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;255 type CallOrigin = EnsureAddressTruncated;256 type WithdrawOrigin = EnsureAddressTruncated;257 type AddressMapping = HashedAddressMapping<Self::Hashing>;258 type Precompiles = ();259 type Currency = Balances;260 type Event = Event;261 type OnMethodCall = (262 pallet_evm_migration::OnMethodCall<Self>,263 pallet_nft::NftErcSupport<Self>,264 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,265 );266 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;267 type ChainId = ChainId;268 type Runner = pallet_evm::runner::stack::Runner<Self>;269 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;270 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;271 type FindAuthor = EthereumFindAuthor<Aura>;272}273274impl pallet_evm_migration::Config for Runtime {275 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;276}277278pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);279impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {280 fn find_author<'a, I>(digests: I) -> Option<H160>281 where282 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,283 {284 if let Some(author_index) = F::find_author(digests) {285 let authority_id = Aura::authorities()[author_index as usize].clone();286 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));287 }288 None289 }290}291292parameter_types! {293 pub BlockGasLimit: U256 = U256::from(u32::max_value());294}295296impl pallet_ethereum::Config for Runtime {297 type Event = Event;298 type StateRoot = pallet_ethereum::IntermediateStateRoot;299 type EvmSubmitLog = pallet_evm::Pallet<Self>;300}301302impl pallet_randomness_collective_flip::Config for Runtime {}303304impl system::Config for Runtime {305 /// The data to be stored in an account.306 type AccountData = pallet_balances::AccountData<Balance>;307 /// The identifier used to distinguish between accounts.308 type AccountId = AccountId;309 /// The basic call filter to use in dispatchable.310 type BaseCallFilter = Everything;311 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).312 type BlockHashCount = BlockHashCount;313 /// The maximum length of a block (in bytes).314 type BlockLength = RuntimeBlockLength;315 /// The index type for blocks.316 type BlockNumber = BlockNumber;317 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.318 type BlockWeights = RuntimeBlockWeights;319 /// The aggregated dispatch type that is available for extrinsics.320 type Call = Call;321 /// The weight of database operations that the runtime can invoke.322 type DbWeight = RocksDbWeight;323 /// The ubiquitous event type.324 type Event = Event;325 /// The type for hashing blocks and tries.326 type Hash = Hash;327 /// The hashing algorithm used.328 type Hashing = BlakeTwo256;329 /// The header type.330 type Header = generic::Header<BlockNumber, BlakeTwo256>;331 /// The index type for storing how many extrinsics an account has signed.332 type Index = Index;333 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.334 type Lookup = AccountIdLookup<AccountId, ()>;335 /// What to do if an account is fully reaped from the system.336 type OnKilledAccount = ();337 /// What to do if a new account is created.338 type OnNewAccount = ();339 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;340 /// The ubiquitous origin type.341 type Origin = Origin;342 /// This type is being generated by `construct_runtime!`.343 type PalletInfo = PalletInfo;344 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.345 type SS58Prefix = SS58Prefix;346 /// Weight information for the extrinsics of this pallet.347 type SystemWeightInfo = system::weights::SubstrateWeight<Self>;348 /// Version of the runtime.349 type Version = Version;350}351352parameter_types! {353 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;354}355356impl pallet_timestamp::Config for Runtime {357 /// A timestamp: milliseconds since the unix epoch.358 type Moment = u64;359 type OnTimestampSet = ();360 type MinimumPeriod = MinimumPeriod;361 type WeightInfo = ();362}363364parameter_types! {365 // pub const ExistentialDeposit: u128 = 500;366 pub const ExistentialDeposit: u128 = 0;367 pub const MaxLocks: u32 = 50;368}369370impl pallet_balances::Config for Runtime {371 type MaxLocks = MaxLocks;372 type MaxReserves = ();373 type ReserveIdentifier = [u8; 8];374 /// The type for recording an account's balance.375 type Balance = Balance;376 /// The ubiquitous event type.377 type Event = Event;378 type DustRemoval = Treasury;379 type ExistentialDeposit = ExistentialDeposit;380 type AccountStore = System;381 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;382}383384pub const MICROUNIQUE: Balance = 1_000_000_000;385pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;386pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;387pub const UNIQUE: Balance = 100 * CENTIUNIQUE;388389pub const fn deposit(items: u32, bytes: u32) -> Balance {390 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE391}392393/*394parameter_types! {395 pub TombstoneDeposit: Balance = deposit(396 1,397 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,398 );399 pub DepositPerContract: Balance = TombstoneDeposit::get();400 pub const DepositPerStorageByte: Balance = deposit(0, 1);401 pub const DepositPerStorageItem: Balance = deposit(1, 0);402 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);403 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;404 pub const SignedClaimHandicap: u32 = 2;405 pub const MaxDepth: u32 = 32;406 pub const MaxValueSize: u32 = 16 * 1024;407 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb408 // The lazy deletion runs inside on_initialize.409 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *410 RuntimeBlockWeights::get().max_block;411 // The weight needed for decoding the queue should be less or equal than a fifth412 // of the overall weight dedicated to the lazy deletion.413 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (414 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -415 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)416 )) / 5) as u32;417 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();418}419420impl pallet_contracts::Config for Runtime {421 type Time = Timestamp;422 type Randomness = RandomnessCollectiveFlip;423 type Currency = Balances;424 type Event = Event;425 type RentPayment = ();426 type SignedClaimHandicap = SignedClaimHandicap;427 type TombstoneDeposit = TombstoneDeposit;428 type DepositPerContract = DepositPerContract;429 type DepositPerStorageByte = DepositPerStorageByte;430 type DepositPerStorageItem = DepositPerStorageItem;431 type RentFraction = RentFraction;432 type SurchargeReward = SurchargeReward;433 type WeightPrice = pallet_transaction_payment::Pallet<Self>;434 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;435 type ChainExtension = NFTExtension;436 type DeletionQueueDepth = DeletionQueueDepth;437 type DeletionWeightLimit = DeletionWeightLimit;438 type Schedule = Schedule;439 type CallStack = [pallet_contracts::Frame<Self>; 31];440}441*/442443parameter_types! {444 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer445 /// This value increases the priority of `Operational` transactions by adding446 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.447 pub const OperationalFeeMultiplier: u8 = 5;448}449450/// Linear implementor of `WeightToFeePolynomial`451pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);452453impl<T> WeightToFeePolynomial for LinearFee<T>454where455 T: BaseArithmetic + From<u32> + Copy + Unsigned,456{457 type Balance = T;458459 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {460 smallvec!(WeightToFeeCoefficient {461 coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer462 coeff_frac: Perbill::zero(),463 negative: false,464 degree: 1,465 })466 }467}468469impl pallet_transaction_payment::Config for Runtime {470 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;471 type TransactionByteFee = TransactionByteFee;472 type OperationalFeeMultiplier = OperationalFeeMultiplier;473 type WeightToFee = LinearFee<Balance>;474 type FeeMultiplierUpdate = ();475}476477parameter_types! {478 pub const ProposalBond: Permill = Permill::from_percent(5);479 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;480 pub const SpendPeriod: BlockNumber = 5 * MINUTES;481 pub const Burn: Permill = Permill::from_percent(0);482 pub const TipCountdown: BlockNumber = 1 * DAYS;483 pub const TipFindersFee: Percent = Percent::from_percent(20);484 pub const TipReportDepositBase: Balance = 1 * UNIQUE;485 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;486 pub const BountyDepositBase: Balance = 1 * UNIQUE;487 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;488 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");489 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;490 pub const MaximumReasonLength: u32 = 16384;491 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);492 pub const BountyValueMinimum: Balance = 5 * UNIQUE;493 pub const MaxApprovals: u32 = 100;494}495496impl pallet_treasury::Config for Runtime {497 type PalletId = TreasuryModuleId;498 type Currency = Balances;499 type ApproveOrigin = EnsureRoot<AccountId>;500 type RejectOrigin = EnsureRoot<AccountId>;501 type Event = Event;502 type OnSlash = ();503 type ProposalBond = ProposalBond;504 type ProposalBondMinimum = ProposalBondMinimum;505 type SpendPeriod = SpendPeriod;506 type Burn = Burn;507 type BurnDestination = ();508 type SpendFunds = ();509 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;510 type MaxApprovals = MaxApprovals;511}512513impl pallet_sudo::Config for Runtime {514 type Event = Event;515 type Call = Call;516}517518parameter_types! {519 pub const MinVestedTransfer: Balance = 10 * UNIQUE;520}521522impl pallet_vesting::Config for Runtime {523 type Event = Event;524 type Currency = Balances;525 type BlockNumberToBalance = ConvertInto;526 type MinVestedTransfer = MinVestedTransfer;527 type WeightInfo = ();528 const MAX_VESTING_SCHEDULES: u32 = 28;529}530531parameter_types! {532 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;533 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;534}535536impl cumulus_pallet_parachain_system::Config for Runtime {537 type Event = Event;538 type OnValidationData = ();539 type SelfParaId = parachain_info::Pallet<Self>;540 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<541 // MaxDownwardMessageWeight,542 // XcmExecutor<XcmConfig>,543 // Call,544 // >;545 type OutboundXcmpMessageSource = XcmpQueue;546 type DmpMessageHandler = DmpQueue;547 type ReservedDmpWeight = ReservedDmpWeight;548 type ReservedXcmpWeight = ReservedXcmpWeight;549 type XcmpMessageHandler = XcmpQueue;550}551552impl parachain_info::Config for Runtime {}553554impl cumulus_pallet_aura_ext::Config for Runtime {}555556parameter_types! {557 pub const RelayLocation: MultiLocation = MultiLocation::parent();558 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;559 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();560 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();561}562563/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used564/// when determining ownership of accounts for asset transacting and when attempting to use XCM565/// `Transact` in order to determine the dispatch Origin.566pub type LocationToAccountId = (567 // The parent (Relay-chain) origin converts to the default `AccountId`.568 ParentIsDefault<AccountId>,569 // Sibling parachain origins convert to AccountId via the `ParaId::into`.570 SiblingParachainConvertsVia<Sibling, AccountId>,571 // Straight up local `AccountId32` origins just alias directly to `AccountId`.572 AccountId32Aliases<RelayNetwork, AccountId>,573);574575/// Means for transacting assets on this chain.576pub type LocalAssetTransactor = CurrencyAdapter<577 // Use this currency:578 Balances,579 // Use this currency when it is a fungible asset matching the given location or name:580 IsConcrete<RelayLocation>,581 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:582 LocationToAccountId,583 // Our chain's account ID type (we can't get away without mentioning it explicitly):584 AccountId,585 // We don't track any teleports.586 (),587>;588589/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,590/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can591/// biases the kind of local `Origin` it will become.592pub type XcmOriginToTransactDispatchOrigin = (593 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location594 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for595 // foreign chains who want to have a local sovereign account on this chain which they control.596 SovereignSignedViaLocation<LocationToAccountId, Origin>,597 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when598 // recognised.599 RelayChainAsNative<RelayOrigin, Origin>,600 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when601 // recognised.602 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,603 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a604 // transaction from the Root origin.605 ParentAsSuperuser<Origin>,606 // Native signed account converter; this just converts an `AccountId32` origin into a normal607 // `Origin::Signed` origin of the same 32-byte value.608 SignedAccountId32AsNative<RelayNetwork, Origin>,609 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.610 XcmPassthrough<Origin>,611);612613parameter_types! {614 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.615 pub UnitWeightCost: Weight = 1_000_000;616 // 1200 UNIQUEs buy 1 second of weight.617 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);618 pub const MaxInstructions: u32 = 100;619 pub const MaxAuthorities: u32 = 100_000;620}621622match_type! {623 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {624 MultiLocation { parents: 1, interior: Here } |625 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }626 };627}628629pub type Barrier = (630 TakeWeightCredit,631 AllowTopLevelPaidExecutionFrom<Everything>,632 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,633 // ^^^ Parent & its unit plurality gets free execution634);635636pub struct XcmConfig;637impl Config for XcmConfig {638 type Call = Call;639 type XcmSender = XcmRouter;640 // How to withdraw and deposit an asset.641 type AssetTransactor = LocalAssetTransactor;642 type OriginConverter = XcmOriginToTransactDispatchOrigin;643 type IsReserve = NativeAsset;644 type IsTeleporter = (); // Teleportation is disabled645 type LocationInverter = LocationInverter<Ancestry>;646 type Barrier = Barrier;647 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;648 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;649 type ResponseHandler = (); // Don't handle responses for now.650 type SubscriptionService = PolkadotXcm;651652 type AssetTrap = PolkadotXcm;653 type AssetClaims = PolkadotXcm;654}655656// parameter_types! {657// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;658// }659660/// No local origins on this chain are allowed to dispatch XCM sends/executions.661pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);662663/// The means for routing XCM messages which are not for local execution into the right message664/// queues.665pub type XcmRouter = (666 // Two routers - use UMP to communicate with the relay chain:667 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,668 // ..and XCMP to communicate with the sibling chains.669 XcmpQueue,670);671672impl pallet_evm_coder_substrate::Config for Runtime {673 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;674}675676impl pallet_xcm::Config for Runtime {677 type Event = Event;678 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;679 type XcmRouter = XcmRouter;680 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;681 type XcmExecuteFilter = Everything;682 type XcmExecutor = XcmExecutor<XcmConfig>;683 type XcmTeleportFilter = Everything;684 type XcmReserveTransferFilter = Everything;685 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;686 type LocationInverter = LocationInverter<Ancestry>;687 type Origin = Origin;688 type Call = Call;689 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;690 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;691}692693impl cumulus_pallet_xcm::Config for Runtime {694 type Event = Event;695 type XcmExecutor = XcmExecutor<XcmConfig>;696}697698impl cumulus_pallet_xcmp_queue::Config for Runtime {699 type Event = Event;700 type XcmExecutor = XcmExecutor<XcmConfig>;701 type ChannelInfo = ParachainSystem;702 type VersionWrapper = ();703}704705impl cumulus_pallet_dmp_queue::Config for Runtime {706 type Event = Event;707 type XcmExecutor = XcmExecutor<XcmConfig>;708 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;709}710711impl pallet_aura::Config for Runtime {712 type AuthorityId = AuraId;713 type DisabledValidators = ();714 type MaxAuthorities = MaxAuthorities;715}716717parameter_types! {718 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();719 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;720}721722impl pallet_common::Config for Runtime {723 type Event = Event;724 type EvmBackwardsAddressMapping = pallet_common::account::MapBackwardsAddressTruncated;725 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;726 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;727728 type Currency = Balances;729 type CollectionCreationPrice = CollectionCreationPrice;730 type TreasuryAccountId = TreasuryAccountId;731}732733impl 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}742743/// Used for the pallet nft in `./nft.rs`744impl pallet_nft::Config for Runtime {745 type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;746}747748parameter_types! {749 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied750}751752/// Used for the pallet inflation753impl pallet_inflation::Config for Runtime {754 type Currency = Balances;755 type TreasuryAccountId = TreasuryAccountId;756 type InflationBlockInterval = InflationBlockInterval;757}758759parameter_types! {760 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *761 RuntimeBlockWeights::get().max_block;762 pub const MaxScheduledPerBlock: u32 = 50;763}764765pub struct Sponsoring;766impl SponsoringResolve<AccountId, Call> for Sponsoring {767 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>768 where769 Call: Dispatchable<Info = DispatchInfo>,770 AccountId: AsRef<[u8]>,771 {772 pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)773 }774}775776type SponsorshipHandler = (777 pallet_nft::NftSponsorshipHandler<Runtime>,778 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,779);780781impl pallet_unq_scheduler::Config for Runtime {782 type Event = Event;783 type Origin = Origin;784 type PalletsOrigin = OriginCaller;785 type Call = Call;786 type MaximumWeight = MaximumSchedulerWeight;787 type ScheduleOrigin = EnsureSigned<AccountId>;788 type MaxScheduledPerBlock = MaxScheduledPerBlock;789 type SponsorshipHandler = SponsorshipHandler;790 type WeightInfo = ();791}792793impl pallet_nft_transaction_payment::Config for Runtime {794 type SponsorshipHandler = SponsorshipHandler;795}796797impl pallet_evm_transaction_payment::Config for Runtime {798 type SponsorshipHandler = (799 pallet_nft::NftEthSponsorshipHandler<Self>,800 pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,801 );802 type Currency = Balances;803}804805impl pallet_nft_charge_transaction::Config for Runtime {}806807// impl pallet_contract_helpers::Config for Runtime {808// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;809// }810811parameter_types! {812 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049813 pub const HelpersContractAddress: H160 = H160([814 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,815 ]);816}817818impl pallet_evm_contract_helpers::Config for Runtime {819 type ContractAddress = HelpersContractAddress;820 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;821}822823construct_runtime!(824 pub enum Runtime where825 Block = Block,826 NodeBlock = opaque::Block,827 UncheckedExtrinsic = UncheckedExtrinsic828 {829 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,830 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,831832 Aura: pallet_aura::{Pallet, Config<T>} = 22,833 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,834835 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,836 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,837 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,838 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,839 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,840 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,841 System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,842 Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,843 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,844845 // XCM helpers.846 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,847 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,848 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,849 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,850851 // Unique Pallets852 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,853 Nft: pallet_nft::{Pallet, Call, Storage} = 61,854 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,855 NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,856 Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,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,862863 // Frontier864 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,865 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,866867 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,868 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,869 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,870 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,871 }872);873874pub struct TransactionConverter;875876impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {877 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {878 UncheckedExtrinsic::new_unsigned(879 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),880 )881 }882}883884impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {885 fn convert_transaction(886 &self,887 transaction: pallet_ethereum::Transaction,888 ) -> opaque::UncheckedExtrinsic {889 let extrinsic = UncheckedExtrinsic::new_unsigned(890 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),891 );892 let encoded = extrinsic.encode();893 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])894 .expect("Encoded extrinsic is always valid")895 }896}897898/// The address format for describing accounts.899pub type Address = sp_runtime::MultiAddress<AccountId, ()>;900/// Block header type as expected by this runtime.901pub type Header = generic::Header<BlockNumber, BlakeTwo256>;902/// Block type as expected by this runtime.903pub type Block = generic::Block<Header, UncheckedExtrinsic>;904/// A Block signed with a Justification905pub type SignedBlock = generic::SignedBlock<Block>;906/// BlockId type as expected by this runtime.907pub type BlockId = generic::BlockId<Block>;908/// The SignedExtension to the basic transaction logic.909pub type SignedExtra = (910 system::CheckSpecVersion<Runtime>,911 // system::CheckTxVersion<Runtime>,912 system::CheckGenesis<Runtime>,913 system::CheckEra<Runtime>,914 system::CheckNonce<Runtime>,915 system::CheckWeight<Runtime>,916 pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,917 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,918);919/// Unchecked extrinsic type as expected by this runtime.920pub type UncheckedExtrinsic =921 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;922/// Extrinsic type that has already been checked.923pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;924/// Executive: handles dispatch to the various modules.925pub type Executive = frame_executive::Executive<926 Runtime,927 Block,928 frame_system::ChainContext<Runtime>,929 Runtime,930 AllPallets,931>;932933impl_opaque_keys! {934 pub struct SessionKeys {935 pub aura: Aura,936 }937}938939impl fp_self_contained::SelfContainedCall for Call {940 type SignedInfo = H160;941942 fn is_self_contained(&self) -> bool {943 match self {944 Call::Ethereum(call) => call.is_self_contained(),945 _ => false,946 }947 }948949 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {950 match self {951 Call::Ethereum(call) => call.check_self_contained(),952 _ => None,953 }954 }955956 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {957 match self {958 Call::Ethereum(call) => call.validate_self_contained(info),959 _ => None,960 }961 }962963 fn pre_dispatch_self_contained(964 &self,965 info: &Self::SignedInfo,966 ) -> Option<Result<(), TransactionValidityError>> {967 match self {968 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),969 _ => None,970 }971 }972973 fn apply_self_contained(974 self,975 info: Self::SignedInfo,976 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {977 match self {978 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(979 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),980 )),981 _ => None,982 }983 }984}985986macro_rules! dispatch_nft_runtime {987 ($collection:ident.$method:ident($($name:ident),*)) => {{988 use pallet_nft::dispatch::Dispatched;989990 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());991 let dispatch = collection.as_dyn();992993 dispatch.$method($($name),*)994 }};995}996impl_runtime_apis! {997 impl up_rpc::NftApi<Block, CrossAccountId, AccountId>998 for Runtime999 {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 }10061007 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 }10161017 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 }10341035 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {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))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 }1047 }10481049 impl sp_api::Core<Block> for Runtime {1050 fn version() -> RuntimeVersion {1051 VERSION1052 }10531054 fn execute_block(block: Block) {1055 Executive::execute_block(block)1056 }10571058 fn initialize_block(header: &<Block as BlockT>::Header) {1059 Executive::initialize_block(header)1060 }1061 }10621063 impl sp_api::Metadata<Block> for Runtime {1064 fn metadata() -> OpaqueMetadata {1065 OpaqueMetadata::new(Runtime::metadata().into())1066 }1067 }10681069 impl sp_block_builder::BlockBuilder<Block> for Runtime {1070 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1071 Executive::apply_extrinsic(extrinsic)1072 }10731074 fn finalize_block() -> <Block as BlockT>::Header {1075 Executive::finalize_block()1076 }10771078 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1079 data.create_extrinsics()1080 }10811082 fn check_inherents(1083 block: Block,1084 data: sp_inherents::InherentData,1085 ) -> sp_inherents::CheckInherentsResult {1086 data.check_extrinsics(&block)1087 }10881089 // fn random_seed() -> <Block as BlockT>::Hash {1090 // RandomnessCollectiveFlip::random_seed().01091 // }1092 }10931094 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1095 fn validate_transaction(1096 source: TransactionSource,1097 tx: <Block as BlockT>::Extrinsic,1098 hash: <Block as BlockT>::Hash,1099 ) -> TransactionValidity {1100 Executive::validate_transaction(source, tx, hash)1101 }1102 }11031104 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1105 fn offchain_worker(header: &<Block as BlockT>::Header) {1106 Executive::offchain_worker(header)1107 }1108 }11091110 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1111 fn chain_id() -> u64 {1112 <Runtime as pallet_evm::Config>::ChainId::get()1113 }11141115 fn account_basic(address: H160) -> EVMAccount {1116 EVM::account_basic(&address)1117 }11181119 fn gas_price() -> U256 {1120 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1121 }11221123 fn account_code_at(address: H160) -> Vec<u8> {1124 EVM::account_codes(address)1125 }11261127 fn author() -> H160 {1128 <pallet_evm::Pallet<Runtime>>::find_author()1129 }11301131 fn storage_at(address: H160, index: U256) -> H256 {1132 let mut tmp = [0u8; 32];1133 index.to_big_endian(&mut tmp);1134 EVM::account_storages(address, H256::from_slice(&tmp[..]))1135 }11361137 fn call(1138 from: H160,1139 to: H160,1140 data: Vec<u8>,1141 value: U256,1142 gas_limit: U256,1143 gas_price: Option<U256>,1144 nonce: Option<U256>,1145 estimate: bool,1146 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1147 let config = if estimate {1148 let mut config = <Runtime as pallet_evm::Config>::config().clone();1149 config.estimate = true;1150 Some(config)1151 } else {1152 None1153 };11541155 <Runtime as pallet_evm::Config>::Runner::call(1156 from,1157 to,1158 data,1159 value,1160 gas_limit.low_u64(),1161 gas_price,1162 nonce,1163 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1164 ).map_err(|err| err.into())1165 }11661167 fn create(1168 from: H160,1169 data: Vec<u8>,1170 value: U256,1171 gas_limit: U256,1172 gas_price: Option<U256>,1173 nonce: Option<U256>,1174 estimate: bool,1175 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1176 let config = if estimate {1177 let mut config = <Runtime as pallet_evm::Config>::config().clone();1178 config.estimate = true;1179 Some(config)1180 } else {1181 None1182 };11831184 <Runtime as pallet_evm::Config>::Runner::create(1185 from,1186 data,1187 value,1188 gas_limit.low_u64(),1189 gas_price,1190 nonce,1191 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1192 ).map_err(|err| err.into())1193 }11941195 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1196 Ethereum::current_transaction_statuses()1197 }11981199 fn current_block() -> Option<pallet_ethereum::Block> {1200 Ethereum::current_block()1201 }12021203 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1204 Ethereum::current_receipts()1205 }12061207 fn current_all() -> (1208 Option<pallet_ethereum::Block>,1209 Option<Vec<pallet_ethereum::Receipt>>,1210 Option<Vec<TransactionStatus>>1211 ) {1212 (1213 Ethereum::current_block(),1214 Ethereum::current_receipts(),1215 Ethereum::current_transaction_statuses()1216 )1217 }12181219 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1220 xts.into_iter().filter_map(|xt| match xt.0.function {1221 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1222 _ => None1223 }).collect()1224 }1225 }12261227 impl sp_session::SessionKeys<Block> for Runtime {1228 fn decode_session_keys(1229 encoded: Vec<u8>,1230 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1231 SessionKeys::decode_into_raw_public_keys(&encoded)1232 }12331234 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1235 SessionKeys::generate(seed)1236 }1237 }12381239 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1240 fn slot_duration() -> sp_consensus_aura::SlotDuration {1241 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1242 }12431244 fn authorities() -> Vec<AuraId> {1245 Aura::authorities().to_vec()1246 }1247 }12481249 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1250 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1251 ParachainSystem::collect_collation_info()1252 }1253 }12541255 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1256 fn account_nonce(account: AccountId) -> Index {1257 System::account_nonce(account)1258 }1259 }12601261 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1262 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1263 TransactionPayment::query_info(uxt, len)1264 }1265 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1266 TransactionPayment::query_fee_details(uxt, len)1267 }1268 }12691270 /*1271 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1272 for Runtime1273 {1274 fn call(1275 origin: AccountId,1276 dest: AccountId,1277 value: Balance,1278 gas_limit: u64,1279 input_data: Vec<u8>,1280 ) -> pallet_contracts_primitives::ContractExecResult {1281 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1282 }12831284 fn instantiate(1285 origin: AccountId,1286 endowment: Balance,1287 gas_limit: u64,1288 code: pallet_contracts_primitives::Code<Hash>,1289 data: Vec<u8>,1290 salt: Vec<u8>,1291 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1292 {1293 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1294 }12951296 fn get_storage(1297 address: AccountId,1298 key: [u8; 32],1299 ) -> pallet_contracts_primitives::GetStorageResult {1300 Contracts::get_storage(address, key)1301 }13021303 fn rent_projection(1304 address: AccountId,1305 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1306 Contracts::rent_projection(address)1307 }1308 }1309 */13101311 #[cfg(feature = "runtime-benchmarks")]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;13191320 let mut list = Vec::<BenchmarkList>::new();13211322 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);13281329 let storage_info = AllPalletsWithSystem::storage_info();13301331 return (list, storage_info)1332 }13331334 fn dispatch_benchmark(1335 config: frame_benchmarking::BenchmarkConfig1336 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1337 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};13381339 let whitelist: Vec<TrackedStorageKey> = vec![1340 // Block Number1341 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1342 // Total Issuance1343 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1344 // Execution Phase1345 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1346 // Event Count1347 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1348 // System Events1349 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1350 ];13511352 let mut batches = Vec::<BenchmarkBatch>::new();1353 let params = (&config, &whitelist);13541355 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1356 add_benchmark!(params, batches, pallet_nft, Nft);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);13611362 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1363 Ok(batches)1364 }1365 }1366}13671368struct CheckInherents;13691370impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1371 fn check_inherents(1372 block: &Block,1373 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1374 ) -> sp_inherents::CheckInherentsResult {1375 let relay_chain_slot = relay_state_proof1376 .read_slot()1377 .expect("Could not read the relay chain slot from the proof");13781379 let inherent_data =1380 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1381 relay_chain_slot,1382 sp_std::time::Duration::from_secs(6),1383 )1384 .create_inherent_data()1385 .expect("Could not create the timestamp inherent data");13861387 inherent_data.check_extrinsics(block)1388 }1389}13901391cumulus_pallet_parachain_system::register_validate_block!(1392 Runtime = Runtime,1393 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1394 CheckInherents = CheckInherents,1395);tests/src/eth/api/ContractHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/ContractHelpers.sol
+++ b/tests/src/eth/api/ContractHelpers.sol
@@ -8,7 +8,11 @@
}
-interface ContractHelpers is Dummy {
+interface ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID) external view returns (bool);
+}
+
+interface ContractHelpers is Dummy, ERC165 {
// Selector: contractOwner(address) 5152b14c
function contractOwner(address contractAddress)
external
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -8,6 +8,10 @@
}
+interface ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID) external view returns (bool);
+}
+
// Inline
interface ERC20Events {
event Transfer(address indexed from, address indexed to, uint256 value);
@@ -18,27 +22,16 @@
);
}
-// Inline
-interface InlineNameSymbol is Dummy {
+interface ERC20 is Dummy, ERC165, ERC20Events {
// Selector: name() 06fdde03
function name() external view returns (string memory);
// Selector: symbol() 95d89b41
function symbol() external view returns (string memory);
-}
-// Inline
-interface InlineTotalSupply is Dummy {
// Selector: totalSupply() 18160ddd
function totalSupply() external view returns (uint256);
-}
-
-interface ERC165 is Dummy {
- // Selector: supportsInterface(bytes4) 01ffc9a7
- function supportsInterface(uint32 interfaceId) external view returns (bool);
-}
-interface ERC20 is Dummy, InlineNameSymbol, InlineTotalSupply, ERC20Events {
// Selector: decimals() 313ce567
function decimals() external view returns (uint8);
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -14,6 +14,10 @@
}
+interface ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID) external view returns (bool);
+}
+
// Inline
interface ERC721Events {
event Transfer(
@@ -36,26 +40,6 @@
// Inline
interface ERC721MintableEvents {
event MintingFinished();
-}
-
-// Inline
-interface InlineNameSymbol is Dummy {
- // Selector: name() 06fdde03
- function name() external view returns (string memory);
-
- // Selector: symbol() 95d89b41
- function symbol() external view returns (string memory);
-}
-
-// Inline
-interface InlineTotalSupply is Dummy {
- // Selector: totalSupply() 18160ddd
- function totalSupply() external view returns (uint256);
-}
-
-interface ERC165 is Dummy {
- // Selector: supportsInterface(bytes4) 01ffc9a7
- function supportsInterface(uint32 interfaceId) external view returns (bool);
}
interface ERC721 is Dummy, ERC165, ERC721Events {
@@ -103,12 +87,12 @@
returns (address);
}
-interface ERC721Burnable is Dummy {
+interface ERC721Burnable is Dummy, ERC165 {
// Selector: burn(uint256) 42966c68
function burn(uint256 tokenId) external;
}
-interface ERC721Enumerable is Dummy, InlineTotalSupply {
+interface ERC721Enumerable is Dummy, ERC165 {
// Selector: tokenByIndex(uint256) 4f6ccce7
function tokenByIndex(uint256 index) external view returns (uint256);
@@ -117,14 +101,23 @@
external
view
returns (uint256);
+
+ // Selector: totalSupply() 18160ddd
+ function totalSupply() external view returns (uint256);
}
-interface ERC721Metadata is Dummy, InlineNameSymbol {
+interface ERC721Metadata is Dummy, ERC165 {
+ // Selector: name() 06fdde03
+ function name() external view returns (string memory);
+
+ // Selector: symbol() 95d89b41
+ function symbol() external view returns (string memory);
+
// Selector: tokenURI(uint256) c87b56dd
function tokenURI(uint256 tokenId) external view returns (string memory);
}
-interface ERC721Mintable is Dummy, ERC721MintableEvents {
+interface ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
// Selector: mintingFinished() 05d2035b
function mintingFinished() external view returns (bool);
@@ -142,10 +135,13 @@
function finishMinting() external returns (bool);
}
-interface ERC721UniqueExtensions is Dummy {
+interface ERC721UniqueExtensions is Dummy, ERC165 {
// Selector: transfer(address,uint256) a9059cbb
function transfer(address to, uint256 tokenId) external;
+ // Selector: burnFrom(address,uint256) 79cc6790
+ function burnFrom(address from, uint256 tokenId) external;
+
// Selector: nextTokenId() 75794a3c
function nextTokenId() external view returns (uint256);
tests/src/substrate/rpc_defs.jsondiffbeforeafterboth--- /dev/null
+++ b/tests/src/substrate/rpc_defs.json
@@ -0,0 +1,76 @@
+{
+ "nft": {
+ "accountBalance": {
+ "description": "Get amount of different user tokens",
+ "params": [
+ {
+ "name": "collectionId",
+ "type": "CollectionId"
+ },
+ {
+ "name": "account",
+ "type": "CrossAccountId"
+ },
+ {
+ "isOptional": true,
+ "name": "at",
+ "type": "Hash"
+ }
+ ],
+ "type": "u32"
+ },
+ "adminlist": {
+ "description": "Get admin list",
+ "params": [
+ {
+ "name": "collectionId",
+ "type": "CollectionId"
+ },
+ {
+ "isOptional": true,
+ "name": "at",
+ "type": "Hash"
+ }
+ ],
+ "type": "Vec<AccountId>"
+ },
+ "balance": {
+ "description": "Get amount of specific account token",
+ "params": [
+ {
+ "name": "collectionId",
+ "type": "CollectionId"
+ },
+ {
+ "name": "account",
+ "type": "CrossAccountId"
+ },
+ {
+ "name": "tokenId",
+ "type": "TokenId"
+ },
+ {
+ "isOptional": true,
+ "name": "at",
+ "type": "Hash"
+ }
+ ],
+ "type": "u128"
+ },
+ "lastTokenId": {
+ "description": "Get last token id",
+ "params": [
+ {
+ "name": "collectionId",
+ "type": "CollectionId"
+ },
+ {
+ "isOptional": true,
+ "name": "at",
+ "type": "Hash"
+ }
+ ],
+ "type": "TokenId"
+ }
+ }
+}