git.delta.rocks / unique-network / refs/commits / 9c7fc18e6abe

difftreelog

feat connect split pallets via runtime

Yaroslav Bolyukin2021-10-12parent: #b70e369.patch.diff
in: master

3 files changed

modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
before · node/cli/src/chain_spec.rs
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56use cumulus_primitives_core::ParaId;7use nft_runtime::*;8use nft_data_structs::*;9use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};10use sc_service::ChainType;11use sp_core::{sr25519, Pair, Public};12use sp_runtime::traits::{IdentifyAccount, Verify};13use std::collections::BTreeMap;1415use serde::{Deserialize, Serialize};16use serde_json::map::Map;1718/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.19pub type ChainSpec = sc_service::GenericChainSpec<nft_runtime::GenesisConfig, Extensions>;2021/// Helper function to generate a crypto pair from seed22pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {23	TPublic::Pair::from_string(&format!("//{}", seed), None)24		.expect("static values are valid; qed")25		.public()26}2728/// The extensions for the [`ChainSpec`].29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]30#[serde(deny_unknown_fields)]31pub struct Extensions {32	/// The relay chain of the Parachain.33	pub relay_chain: String,34	/// The id of the Parachain.35	pub para_id: u32,36}3738impl Extensions {39	/// Try to get the extension from the given `ChainSpec`.40	pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> {41		sc_chain_spec::get_extension(chain_spec.extensions())42	}43}4445type AccountPublic = <Signature as Verify>::Signer;4647/// Helper function to generate an account ID from seed48pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId49where50	AccountPublic: From<<TPublic::Pair as Pair>::Public>,51{52	AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()53}5455pub fn development_config(id: ParaId) -> ChainSpec {56	let mut properties = Map::new();57	properties.insert("tokenSymbol".into(), "testUNQ".into());58	properties.insert("tokenDecimals".into(), 15.into());59	properties.insert("ss58Format".into(), 42.into()); // Generic Substrate wildcard (SS58 checksum preimage)6061	ChainSpec::from_genesis(62		// Name63		"Development",64		// ID65		"dev",66		ChainType::Local,67		move || {68			testnet_genesis(69				// Sudo account70				get_account_id_from_seed::<sr25519::Public>("Alice"),71				vec![72					get_from_seed::<AuraId>("Alice"),73					get_from_seed::<AuraId>("Bob"),74				],75				// Pre-funded accounts76				vec![77					get_account_id_from_seed::<sr25519::Public>("Alice"),78					get_account_id_from_seed::<sr25519::Public>("Bob"),79				],80				id,81			)82		},83		// Bootnodes84		vec![],85		// Telemetry86		None,87		// Protocol ID88		None,89		// Properties90		Some(properties),91		// Extensions92		Extensions {93			relay_chain: "rococo-dev".into(),94			para_id: id.into(),95		},96	)97}9899pub fn local_testnet_config(id: ParaId) -> ChainSpec {100	ChainSpec::from_genesis(101		// Name102		"Local Testnet",103		// ID104		"local_testnet",105		ChainType::Local,106		move || {107			testnet_genesis(108				// Sudo account109				get_account_id_from_seed::<sr25519::Public>("Alice"),110				vec![111					get_from_seed::<AuraId>("Alice"),112					get_from_seed::<AuraId>("Bob"),113				],114				// Pre-funded accounts115				vec![116					get_account_id_from_seed::<sr25519::Public>("Alice"),117					get_account_id_from_seed::<sr25519::Public>("Bob"),118					get_account_id_from_seed::<sr25519::Public>("Charlie"),119					get_account_id_from_seed::<sr25519::Public>("Dave"),120					get_account_id_from_seed::<sr25519::Public>("Eve"),121					get_account_id_from_seed::<sr25519::Public>("Ferdie"),122					get_account_id_from_seed::<sr25519::Public>("Alice//stash"),123					get_account_id_from_seed::<sr25519::Public>("Bob//stash"),124					get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),125					get_account_id_from_seed::<sr25519::Public>("Dave//stash"),126					get_account_id_from_seed::<sr25519::Public>("Eve//stash"),127					get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),128				],129				id,130			)131		},132		// Bootnodes133		vec![],134		// Telemetry135		None,136		// Protocol ID137		None,138		// Properties139		None,140		// Extensions141		Extensions {142			relay_chain: "rococo-local".into(),143			para_id: id.into(),144		},145	)146}147148fn testnet_genesis(149	root_key: AccountId,150	initial_authorities: Vec<AuraId>,151	endowed_accounts: Vec<AccountId>,152	id: ParaId,153) -> GenesisConfig {154	let vested_accounts = vec![get_account_id_from_seed::<sr25519::Public>("Bob")];155156	GenesisConfig {157		system: nft_runtime::SystemConfig {158			code: nft_runtime::WASM_BINARY159				.expect("WASM binary was not build, please build it!")160				.to_vec(),161			changes_trie_config: Default::default(),162		},163		balances: BalancesConfig {164			balances: endowed_accounts165				.iter()166				.cloned()167				.map(|k| (k, 1 << 70))168				.collect(),169		},170		treasury: Default::default(),171		sudo: SudoConfig { key: root_key },172		vesting: VestingConfig {173			vesting: vested_accounts174				.iter()175				.cloned()176				.map(|k| (k, 1000, 100, 1 << 98))177				.collect(),178		},179		nft: NftConfig {180			collection_id: vec![(181				1,182				Collection {183					owner: get_account_id_from_seed::<sr25519::Public>("Alice"),184					mode: CollectionMode::NFT,185					access: AccessMode::Normal,186					decimal_points: 0,187					name: vec![],188					description: vec![],189					token_prefix: vec![],190					mint_mode: false,191					offchain_schema: vec![],192					schema_version: SchemaVersion::default(),193					sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<194						sr25519::Public,195					>("Alice")),196					const_on_chain_schema: vec![],197					variable_on_chain_schema: vec![],198					limits: CollectionLimits::default(),199					meta_update_permission: MetaUpdatePermission::ItemOwner,200					transfers_enabled: true,201				},202			)],203			nft_item_id: vec![],204			fungible_item_id: vec![],205			refungible_item_id: vec![],206		},207		parachain_info: nft_runtime::ParachainInfoConfig { parachain_id: id },208		aura: nft_runtime::AuraConfig {209			authorities: initial_authorities,210		},211		aura_ext: Default::default(),212		evm: EVMConfig {213			accounts: BTreeMap::new(),214		},215		ethereum: EthereumConfig {},216	}217}
after · node/cli/src/chain_spec.rs
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56use cumulus_primitives_core::ParaId;7use nft_runtime::*;8use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};9use sc_service::ChainType;10use sp_core::{sr25519, Pair, Public};11use sp_runtime::traits::{IdentifyAccount, Verify};12use std::collections::BTreeMap;1314use serde::{Deserialize, Serialize};15use serde_json::map::Map;1617/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.18pub type ChainSpec = sc_service::GenericChainSpec<nft_runtime::GenesisConfig, Extensions>;1920/// Helper function to generate a crypto pair from seed21pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {22	TPublic::Pair::from_string(&format!("//{}", seed), None)23		.expect("static values are valid; qed")24		.public()25}2627/// The extensions for the [`ChainSpec`].28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]29#[serde(deny_unknown_fields)]30pub struct Extensions {31	/// The relay chain of the Parachain.32	pub relay_chain: String,33	/// The id of the Parachain.34	pub para_id: u32,35}3637impl Extensions {38	/// Try to get the extension from the given `ChainSpec`.39	pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> {40		sc_chain_spec::get_extension(chain_spec.extensions())41	}42}4344type AccountPublic = <Signature as Verify>::Signer;4546/// Helper function to generate an account ID from seed47pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId48where49	AccountPublic: From<<TPublic::Pair as Pair>::Public>,50{51	AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()52}5354pub fn development_config(id: ParaId) -> ChainSpec {55	let mut properties = Map::new();56	properties.insert("tokenSymbol".into(), "testUNQ".into());57	properties.insert("tokenDecimals".into(), 15.into());58	properties.insert("ss58Format".into(), 42.into()); // Generic Substrate wildcard (SS58 checksum preimage)5960	ChainSpec::from_genesis(61		// Name62		"Development",63		// ID64		"dev",65		ChainType::Local,66		move || {67			testnet_genesis(68				// Sudo account69				get_account_id_from_seed::<sr25519::Public>("Alice"),70				vec![71					get_from_seed::<AuraId>("Alice"),72					get_from_seed::<AuraId>("Bob"),73				],74				// Pre-funded accounts75				vec![76					get_account_id_from_seed::<sr25519::Public>("Alice"),77					get_account_id_from_seed::<sr25519::Public>("Bob"),78				],79				id,80			)81		},82		// Bootnodes83		vec![],84		// Telemetry85		None,86		// Protocol ID87		None,88		// Properties89		Some(properties),90		// Extensions91		Extensions {92			relay_chain: "rococo-dev".into(),93			para_id: id.into(),94		},95	)96}9798pub fn local_testnet_config(id: ParaId) -> ChainSpec {99	ChainSpec::from_genesis(100		// Name101		"Local Testnet",102		// ID103		"local_testnet",104		ChainType::Local,105		move || {106			testnet_genesis(107				// Sudo account108				get_account_id_from_seed::<sr25519::Public>("Alice"),109				vec![110					get_from_seed::<AuraId>("Alice"),111					get_from_seed::<AuraId>("Bob"),112				],113				// Pre-funded accounts114				vec![115					get_account_id_from_seed::<sr25519::Public>("Alice"),116					get_account_id_from_seed::<sr25519::Public>("Bob"),117					get_account_id_from_seed::<sr25519::Public>("Charlie"),118					get_account_id_from_seed::<sr25519::Public>("Dave"),119					get_account_id_from_seed::<sr25519::Public>("Eve"),120					get_account_id_from_seed::<sr25519::Public>("Ferdie"),121					get_account_id_from_seed::<sr25519::Public>("Alice//stash"),122					get_account_id_from_seed::<sr25519::Public>("Bob//stash"),123					get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),124					get_account_id_from_seed::<sr25519::Public>("Dave//stash"),125					get_account_id_from_seed::<sr25519::Public>("Eve//stash"),126					get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),127				],128				id,129			)130		},131		// Bootnodes132		vec![],133		// Telemetry134		None,135		// Protocol ID136		None,137		// Properties138		None,139		// Extensions140		Extensions {141			relay_chain: "rococo-local".into(),142			para_id: id.into(),143		},144	)145}146147fn testnet_genesis(148	root_key: AccountId,149	initial_authorities: Vec<AuraId>,150	endowed_accounts: Vec<AccountId>,151	id: ParaId,152) -> GenesisConfig {153	let vested_accounts = vec![get_account_id_from_seed::<sr25519::Public>("Bob")];154155	GenesisConfig {156		system: nft_runtime::SystemConfig {157			code: nft_runtime::WASM_BINARY158				.expect("WASM binary was not build, please build it!")159				.to_vec(),160			changes_trie_config: Default::default(),161		},162		balances: BalancesConfig {163			balances: endowed_accounts164				.iter()165				.cloned()166				.map(|k| (k, 1 << 70))167				.collect(),168		},169		treasury: Default::default(),170		sudo: SudoConfig { key: root_key },171		vesting: VestingConfig {172			vesting: vested_accounts173				.iter()174				.cloned()175				.map(|k| (k, 1000, 100, 1 << 98))176				.collect(),177		},178		parachain_info: nft_runtime::ParachainInfoConfig { parachain_id: id },179		aura: nft_runtime::AuraConfig {180			authorities: initial_authorities,181		},182		aura_ext: Default::default(),183		evm: EVMConfig {184			accounts: BTreeMap::new(),185		},186		ethereum: EthereumConfig {},187	}188}
modifiedruntime/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',
@@ -67,6 +71,10 @@
     'parachain-info/std',
     'serde',
     'pallet-inflation/std',
+    'pallet-common/std',
+    'pallet-fungible/std',
+    'pallet-refungible/std',
+    'pallet-nonfungible/std',
     'pallet-nft/std',
     'pallet-scheduler/std',
     'pallet-nft-charge-transaction/std',
@@ -163,19 +171,19 @@
 # [dependencies.pallet-contracts]
 # git = 'https://github.com/paritytech/substrate.git'
 # default-features = false
-# branch = 'polkadot-v0.9.9'
+# branch = 'polkadot-v0.9.10'
 # 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.10'
 # 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.10'
 # version = '4.0.0-dev'
 
 [dependencies.pallet-randomness-collective-flip]
@@ -385,9 +393,14 @@
 [dependencies]
 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-scheduler = { path = '../pallets/scheduler', default-features = false, version = '3.0.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-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' }
 pallet-nft-charge-transaction = { path = '../pallets/nft-charge-transaction', default-features = false, version = '3.0.0' }
modifiedruntime/src/lib.rsdiffbeforeafterboth
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -102,6 +102,8 @@
 /// to the public key of our transaction signing scheme.
 pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
 
+pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;
+
 /// The type for looking up accounts. We don't expect more than 4 billion of them, but you
 /// never know...
 pub type AccountIndex = u32;
@@ -701,20 +703,32 @@
 	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;
 }
 
-/// Used for the pallet nft in `./nft.rs`
-impl pallet_nft::Config for Runtime {
+impl pallet_common::Config for Runtime {
 	type Event = Event;
-	type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;
-
-	type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;
+	type EvmBackwardsAddressMapping = pallet_common::account::MapBackwardsAddressTruncated;
 	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;
-	type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;
+	type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;
 
 	type Currency = Balances;
 	type CollectionCreationPrice = CollectionCreationPrice;
 	type TreasuryAccountId = TreasuryAccountId;
 }
 
+impl pallet_fungible::Config for Runtime {
+	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;
+}
+impl pallet_refungible::Config for Runtime {
+	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;
+}
+impl pallet_nonfungible::Config for Runtime {
+	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;
+}
+
+/// Used for the pallet nft in `./nft.rs`
+impl pallet_nft::Config for Runtime {
+	type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;
+}
+
 parameter_types! {
 	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied
 }
@@ -820,11 +834,15 @@
 
 		// Unique Pallets
 		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
-		Nft: pallet_nft::{Pallet, Call, Config<T>, Storage, Event<T>} = 61,
+		Nft: pallet_nft::{Pallet, Call, Storage} = 61,
 		Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
 		NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,
 		Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,
 		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
+		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,
+		Fungible: pallet_fungible::{Pallet, Storage} = 67,
+		Refungible: pallet_refungible::{Pallet, Storage} = 68,
+		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,
 
 		// Frontier
 		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,
@@ -901,10 +919,56 @@
 	}
 }
 
+macro_rules! dispatch_nft_runtime {
+	($collection:ident.$method:ident($($name:ident),*)) => {{
+		use pallet_nft::dispatch::Dispatched;
+
+		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());
+		let dispatch = collection.as_dyn();
+
+		dispatch.$method($($name),*)
+	}};
+}
+
 impl_runtime_apis! {
-	impl pallet_nft::NftApi<Block>
+	impl up_rpc::NftApi<Block, CrossAccountId, AccountId>
 		for Runtime
 	{
+		fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {
+			dispatch_nft_runtime!(collection.account_tokens(account))
+		}
+		fn token_exists(collection: CollectionId, token: TokenId) -> bool {
+			dispatch_nft_runtime!(collection.token_exists(token))
+		}
+
+		fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {
+			dispatch_nft_runtime!(collection.token_owner(token))
+		}
+		fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {
+			dispatch_nft_runtime!(collection.const_metadata(token))
+		}
+		fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {
+			dispatch_nft_runtime!(collection.variable_metadata(token))
+		}
+
+		fn collection_tokens(collection: CollectionId) -> u32 {
+			dispatch_nft_runtime!(collection.collection_tokens())
+		}
+		fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {
+			dispatch_nft_runtime!(collection.account_balance(account))
+		}
+		fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {
+			dispatch_nft_runtime!(collection.balance(account, token))
+		}
+		fn allowance(
+			collection: CollectionId,
+			sender: CrossAccountId,
+			spender: CrossAccountId,
+			token: TokenId,
+		) -> u128 {
+			dispatch_nft_runtime!(collection.allowance(sender, spender, token))
+		}
+
 		fn eth_contract_code(account: H160) -> Option<Vec<u8>> {
 			<pallet_nft::NftErcSupport<Runtime>>::get_code(&account)
 		}