git.delta.rocks / unique-network / refs/commits / 6f2e0cc4002e

difftreelog

refactor combine sponsorship fields

Yaroslav Bolyukin2021-03-12parent: #bc76286.patch.diff
in: master

5 files changed

modifiednode/src/chain_spec.rsdiffbeforeafterboth
after · node/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//56// use nft_runtime::{7//     AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig,8//     SystemConfig, WASM_BINARY,9// };10// use nft_runtime::{ContractsConfig, ContractsSchedule, NftConfig, CollectionType};11use nft_runtime::*;12use sc_service::ChainType;13use sp_consensus_aura::sr25519::AuthorityId as AuraId;14use sp_core::{sr25519, Pair, Public};15use sp_finality_grandpa::AuthorityId as GrandpaId;16use sp_runtime::traits::{IdentifyAccount, Verify};17use serde_json::map::Map;18// use crate::chain_spec::api::chain_extension::*;1920// Note this is the URL for the telemetry server21//const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";2223/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.24pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;2526/// Helper function to generate a crypto pair from seed27pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {28    TPublic::Pair::from_string(&format!("//{}", seed), None)29        .expect("static values are valid; qed")30        .public()31}3233type AccountPublic = <Signature as Verify>::Signer;3435/// Helper function to generate an account ID from seed36pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId37where38    AccountPublic: From<<TPublic::Pair as Pair>::Public>,39{40    AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()41}4243/// Helper function to generate an authority key for Aura44pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {45    (get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))46}4748pub fn development_config() -> Result<ChainSpec, String> {49	let wasm_binary = WASM_BINARY.ok_or("Development wasm binary not available".to_string())?;5051	let mut properties = Map::new();52	properties.insert("tokenSymbol".into(), "UniqueTest".into());53	properties.insert("tokenDecimals".into(), 15.into());54	properties.insert("ss58Format".into(), 42.into()); // Generic Substrate wildcard (SS58 checksum preimage)5556	Ok(ChainSpec::from_genesis(57		// Name58		"Development",59		// ID60		"dev",61		ChainType::Development,62		move || testnet_genesis(63			wasm_binary,64			// Initial PoA authorities65			vec![66				authority_keys_from_seed("Alice"),67			],68			// Sudo account69			get_account_id_from_seed::<sr25519::Public>("Alice"),70			// Pre-funded accounts71			vec![72				get_account_id_from_seed::<sr25519::Public>("Alice"),73				get_account_id_from_seed::<sr25519::Public>("Bob"),74				get_account_id_from_seed::<sr25519::Public>("Alice//stash"),75				get_account_id_from_seed::<sr25519::Public>("Bob//stash"),76			],77			true,78		),79		// Bootnodes80		vec![],81		// Telemetry82		None,83		// Protocol ID84		None,85		// Properties86		Some(properties),87		// Extensions88		None,89	))90}9192pub fn local_testnet_config() -> Result<ChainSpec, String> {93	let wasm_binary = WASM_BINARY.ok_or("Development wasm binary not available".to_string())?;9495	Ok(ChainSpec::from_genesis(96		// Name97		"Local Testnet",98		// ID99		"local_testnet",100		ChainType::Local,101		move || testnet_genesis(102			wasm_binary,103			// Initial PoA authorities104			vec![105				authority_keys_from_seed("Alice"),106				authority_keys_from_seed("Bob"),107			],108			// Sudo account109			get_account_id_from_seed::<sr25519::Public>("Alice"),110			// Pre-funded accounts111			vec![112				get_account_id_from_seed::<sr25519::Public>("Alice"),113				get_account_id_from_seed::<sr25519::Public>("Bob"),114				get_account_id_from_seed::<sr25519::Public>("Charlie"),115				get_account_id_from_seed::<sr25519::Public>("Dave"),116				get_account_id_from_seed::<sr25519::Public>("Eve"),117				get_account_id_from_seed::<sr25519::Public>("Ferdie"),118				get_account_id_from_seed::<sr25519::Public>("Alice//stash"),119				get_account_id_from_seed::<sr25519::Public>("Bob//stash"),120				get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),121				get_account_id_from_seed::<sr25519::Public>("Dave//stash"),122				get_account_id_from_seed::<sr25519::Public>("Eve//stash"),123				get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),124			],125			true,126		),127		// Bootnodes128		vec![],129		// Telemetry130		None,131		// Protocol ID132		None,133		// Properties134		None,135		// Extensions136		None,137	))138}139140fn testnet_genesis(141    wasm_binary: &[u8],142    initial_authorities: Vec<(AuraId, GrandpaId)>,143    root_key: AccountId,144    endowed_accounts: Vec<AccountId>,145    enable_println: bool,146) -> GenesisConfig {147148	let vested_accounts = vec![149		get_account_id_from_seed::<sr25519::Public>("Bob"),150	];151152    GenesisConfig {153        system: Some(SystemConfig {154            code: wasm_binary.to_vec(),155            changes_trie_config: Default::default(),156        }),157        pallet_balances: Some(BalancesConfig {158            balances: endowed_accounts159                .iter()160                .cloned()161                .map(|k| (k, 1 << 100))162                .collect(),163        }),164        pallet_aura: Some(AuraConfig {165            authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),166        }),167		pallet_grandpa: Some(GrandpaConfig {168            authorities: initial_authorities169                .iter()170                .map(|x| (x.1.clone(), 1))171                .collect(),172		}),173		pallet_treasury: Some(Default::default()),174		pallet_sudo: Some(SudoConfig { key: root_key }),175		pallet_vesting: Some(VestingConfig {176            vesting: vested_accounts177                .iter()178                .cloned()179                .map(|k| (k, 1000, 100, 1 << 98))180                .collect(),181        }),182        pallet_nft: Some(NftConfig {183            collection: vec![(184                1,185                CollectionType {186                    owner: get_account_id_from_seed::<sr25519::Public>("Alice"),187                    mode: CollectionMode::NFT,188                    access: AccessMode::Normal,189                    decimal_points: 0,190                    name: vec![],191                    description: vec![],192                    token_prefix: vec![],193                    mint_mode: false,194					offchain_schema: vec![],195					schema_version: SchemaVersion::default(),196                    sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<sr25519::Public>("Alice")),197                    const_on_chain_schema: vec![],198					variable_on_chain_schema: vec![],199					limits: CollectionLimits::default()200                },201            )],202            nft_item_id: vec![],203            fungible_item_id: vec![],204            refungible_item_id: vec![],205            chain_limit: ChainLimits {206                collection_numbers_limit: 100000,207                account_token_ownership_limit: 1000000,208                collections_admins_limit: 5,209                custom_data_limit: 2048,210                nft_sponsor_transfer_timeout: 15,211                fungible_sponsor_transfer_timeout: 15,212				refungible_sponsor_transfer_timeout: 15,213				offchain_schema_limit: 1024,214				variable_on_chain_schema_limit: 1024,215				const_on_chain_schema_limit: 1024,216            },217        }),218        pallet_contracts: Some(ContractsConfig {219            current_schedule: ContractsSchedule {220                enable_println,221                ..Default::default()222            },223        }),224    }225}
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -123,6 +123,42 @@
     pub fraction: u128,
 }
 
+#[derive(Encode, Decode, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub enum SponsorshipState<AccountId> {
+    /// The fees are applied to the transaction sender
+    Disabled,
+    Unconfirmed(AccountId),
+    /// Transactions are sponsored by specified account
+    Confirmed(AccountId),
+}
+
+impl<AccountId> SponsorshipState<AccountId> {
+    fn sponsor(&self) -> Option<&AccountId> {
+        match self {
+            Self::Confirmed(sponsor) => Some(sponsor),
+            _ => None,
+        }
+    }
+
+    fn pending_sponsor(&self) -> Option<&AccountId> {
+        match self {
+            Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),
+            _ => None,
+        }
+    }
+
+    fn confirmed(&self) -> bool {
+        matches!(self, Self::Confirmed(_))
+    }
+}
+
+impl<T> Default for SponsorshipState<T> {
+    fn default() -> Self {
+        Self::Disabled
+    }
+}
+
 #[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
 #[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
 pub struct CollectionType<AccountId> {
@@ -136,8 +172,7 @@
     pub mint_mode: bool,
     pub offchain_schema: Vec<u8>,
     pub schema_version: SchemaVersion,
-    pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender
-    pub sponsor_confirmed: bool, // False if sponsor address has not yet confirmed sponsorship. True otherwise.
+    pub sponsorship: SponsorshipState<AccountId>,
     pub limits: CollectionLimits, // Collection private restrictions 
     pub variable_on_chain_schema: Vec<u8>, //
     pub const_on_chain_schema: Vec<u8>, //
@@ -665,8 +700,7 @@
                 token_prefix: token_prefix,
                 offchain_schema: Vec::new(),
                 schema_version: SchemaVersion::ImageURL,
-                sponsor: T::AccountId::default(),
-                sponsor_confirmed: false,
+                sponsorship: SponsorshipState::Disabled,
                 variable_on_chain_schema: Vec::new(),
                 const_on_chain_schema: Vec::new(),
                 limits,
@@ -922,8 +956,7 @@
             let mut target_collection = <Collection<T>>::get(collection_id);
             ensure!(sender == target_collection.owner, Error::<T>::NoPermission);
 
-            target_collection.sponsor = new_sponsor;
-            target_collection.sponsor_confirmed = false;
+            target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);
             <Collection<T>>::insert(collection_id, target_collection);
 
             Ok(())
@@ -943,9 +976,12 @@
             ensure!(<Collection<T>>::contains_key(collection_id), Error::<T>::CollectionNotFound);
 
             let mut target_collection = <Collection<T>>::get(collection_id);
-            ensure!(sender == target_collection.sponsor, Error::<T>::ConfirmUnsetSponsorFail);
+            ensure!(
+                target_collection.sponsorship.pending_sponsor() == Some(&sender),
+                Error::<T>::ConfirmUnsetSponsorFail
+            );
 
-            target_collection.sponsor_confirmed = true;
+            target_collection.sponsorship = SponsorshipState::Confirmed(sender);
             <Collection<T>>::insert(collection_id, target_collection);
 
             Ok(())
@@ -969,8 +1005,7 @@
             let mut target_collection = <Collection<T>>::get(collection_id);
             ensure!(sender == target_collection.owner, Error::<T>::NoPermission);
 
-            target_collection.sponsor = T::AccountId::default();
-            target_collection.sponsor_confirmed = false;
+            target_collection.sponsorship = SponsorshipState::Disabled;
             <Collection<T>>::insert(collection_id, target_collection);
 
             Ok(())
@@ -2485,7 +2520,9 @@
                 // sponsor timeout
                 let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
 
-                let limit = <Collection<T>>::get(collection_id).limits.sponsor_transfer_timeout;
+                let collection = <Collection<T>>::get(collection_id);
+
+                let limit = collection.limits.sponsor_transfer_timeout;
                 let mut sponsored = true;
                 if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {
                     let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));
@@ -2499,11 +2536,12 @@
                 }
 
                 // check free create limit
-                if (<Collection<T>>::get(collection_id).limits.sponsored_data_size >= (_properties.len() as u32)) &&
-                   (<Collection<T>>::get(collection_id).sponsor_confirmed) &&
+                if (collection.limits.sponsored_data_size >= (_properties.len() as u32)) &&
                    (sponsored)
                 {
-                    <Collection<T>>::get(collection_id).sponsor
+                    collection.sponsorship.sponsor()
+                        .cloned()
+                        .unwrap_or_default()
                 } else {
                     T::AccountId::default()
                 }
@@ -2511,7 +2549,7 @@
             Some(Call::transfer(_new_owner, collection_id, item_id, _value)) => {
                 
                 let mut sponsor_transfer = false;
-                if <Collection<T>>::get(collection_id).sponsor_confirmed {
+                if <Collection<T>>::get(collection_id).sponsorship.confirmed() {
 
                     let collection_limits = <Collection<T>>::get(collection_id).limits;
                     let collection_mode = <Collection<T>>::get(collection_id).mode;
@@ -2598,7 +2636,9 @@
                 if !sponsor_transfer {
                     T::AccountId::default()
                 } else {
-                    <Collection<T>>::get(collection_id).sponsor
+                    <Collection<T>>::get(collection_id).sponsorship.sponsor()
+                        .cloned()
+                        .unwrap_or_default()
                 }
             }
 
modifiedruntime_types.jsondiffbeforeafterboth
--- a/runtime_types.json
+++ b/runtime_types.json
@@ -31,6 +31,13 @@
       "ConstData": "Vec<u8>",
       "VariableData": "Vec<u8>"
     },
+    "SponsorshipState": {
+      "_enum": {
+        "Disabled": null,
+        "Unconfirmed": "AccountId",
+        "Confirmed": "AccountId"
+      }
+    },
     "CollectionType": {
       "Owner": "AccountId",
       "Mode": "CollectionMode",
@@ -42,8 +49,7 @@
       "MintMode": "bool",
       "OffchainSchema": "Vec<u8>",
       "SchemaVersion": "SchemaVersion",
-      "Sponsor": "AccountId",
-      "SponsorConfirmed": "bool",
+      "Sponsorship": "SponsorshipState",
       "Limits": "CollectionLimits",
       "VariableOnChainSchema": "Vec<u8>",
       "ConstOnChainSchema": "Vec<u8>"
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -26,6 +26,7 @@
     "testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",
     "testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
     "testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",
+    "testRemoveCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionSponsor.test.ts",
     "testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",
     "testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
     "testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -396,8 +396,7 @@
 
     // What to expect
     expect(result.success).to.be.true;
-    expect(collection.Sponsor).to.be.equal(nullPublicKey);
-    expect(collection.SponsorConfirmed).to.be.false;
+    expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });
   });
 }