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

difftreelog

Merge branch 'master' of github.com:usetech-llc/nft_parachain

Greg Zaitsev2020-07-10parents: #7a687a0 #23062aa.patch.diff
in: master

7 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2553,6 +2553,7 @@
  "pallet-balances",
  "pallet-contracts",
  "pallet-contracts-primitives",
+ "pallet-contracts-rpc-runtime-api",
  "pallet-grandpa",
  "pallet-nft",
  "pallet-randomness-collective-flip",
modifiednode/src/chain_spec.rsdiffbeforeafterboth
--- a/node/src/chain_spec.rs
+++ b/node/src/chain_spec.rs
@@ -103,7 +103,8 @@
 fn testnet_genesis(initial_authorities: Vec<(AuraId, GrandpaId)>,
 	root_key: AccountId,
 	endowed_accounts: Vec<AccountId>,
-	_enable_println: bool) -> GenesisConfig {
+	_enable_println: bool
+	) -> GenesisConfig {
 	GenesisConfig {
 		system: Some(SystemConfig {
 			code: WASM_BINARY.to_vec(),
@@ -122,9 +123,9 @@
 			key: root_key,
 		}),
 		contracts: Some(ContractsConfig {
-			gas_price: 1_000_000_000,
+			gas_price: 1_000,
             current_schedule: ContractsSchedule {
-                 //   enable_println,
+            		// enable_println,
                     ..Default::default()
             },
         }),
modifiednode/src/service.rsdiffbeforeafterboth
--- a/node/src/service.rs
+++ b/node/src/service.rs
@@ -25,6 +25,7 @@
 /// be able to perform chain operations.
 macro_rules! new_full_start {
 	($config:expr) => {{
+		use jsonrpc_core::IoHandler;
 		use std::sync::Arc;
 		let mut import_setup = None;
 		let inherent_data_providers = sp_inherents::InherentDataProviders::new();
@@ -62,7 +63,15 @@
 				import_setup = Some((grandpa_block_import, grandpa_link));
 
 				Ok(import_queue)
-			})?;
+			})?
+			.with_rpc_extensions(|builder| -> Result<IoHandler<sc_rpc::Metadata>, _> {
+                let handler = pallet_contracts_rpc::Contracts::new(builder.client().clone());
+                let delegate = pallet_contracts_rpc::ContractsApi::to_delegate(handler);
+
+                let mut io = IoHandler::default();
+                io.extend_with(delegate);
+                Ok(io)
+            })?;
 
 		(builder, import_setup, inherent_data_providers)
 	}}
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -24,6 +24,9 @@
 pub struct CollectionType<AccountId> {
     pub owner: AccountId,
     pub next_item_id: u64,
+    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
     pub custom_data_size: u32,
 }
 
@@ -58,21 +61,17 @@
 
         /// Next available collection ID
         pub NextCollectionID get(fn next_collection_id): u64;
-
-        pub Collection get(collection): map hasher(identity) u64 => CollectionType<T::AccountId>;
-        //pub Collection get(collection): map hasher(identity) u64 => CollectionType<T::AccountId>;
-
-        pub AdminList get(admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;
+        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;
+        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;
 
         /// Balance owner per collection map
-        pub Balance get(balance_count): map hasher(blake2_128_concat) (u64, T::AccountId) => u64;
-        pub ApprovedList get(approved): map hasher(blake2_128_concat) (u64, u64) => Vec<T::AccountId>;
+        pub Balance get(fn balance_count): map hasher(blake2_128_concat) (u64, T::AccountId) => u64;
+        pub ApprovedList get(fn approved): map hasher(blake2_128_concat) (u64, u64) => Vec<T::AccountId>;
 
-        pub ItemList get(item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;
-        // pub ItemList get(item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;
+        pub ItemList get(fn item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;
+        pub ItemListIndex get(fn item_index): map hasher(blake2_128_concat) u64 => u64;
 
-        pub ItemListIndex get(item_index): map hasher(blake2_128_concat) u64 => u64;
-        // pub ItemListIndex get(item_index): map hasher(blake2_128_concat) u64 => u64;
+        pub AddressTokens get(fn address_tokens): map hasher(blake2_128_concat) (u64, T::AccountId) => Vec<u64>;
     }
 }
 
@@ -82,7 +81,9 @@
     where
         AccountId = <T as system::Trait>::AccountId,
     {
-        Created(u32, AccountId),
+        Created(u64, AccountId),
+        ItemCreated(u64),
+        ItemDestroyed(u64, u64),
     }
 );
 
@@ -109,18 +110,41 @@
         // @param customDataSz size of custom data in each collection item
         // returns collection ID
         #[weight = frame_support::weights::SimpleDispatchInfo::default()]
-        pub fn create_collection(origin, custom_data_sz: u32) -> DispatchResult {
+        pub fn create_collection(   origin, 
+                                    collection_name: Vec<u16>, 
+                                    collection_description: Vec<u16>, 
+                                    token_prefix: Vec<u8>, 
+                                    custom_data_sz: u32) -> DispatchResult {
+
             // Anyone can create a collection
             let who = ensure_signed(origin)?;
 
+            // check params 
+            let mut name = collection_name.to_vec();
+            name.push(0);
+            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");
+
+            let mut description = collection_description.to_vec();
+            description.push(0);
+            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");
+
+            let mut prefix = token_prefix.to_vec();
+            prefix.push(0);
+            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");
+
             // Generate next collection ID
-            let next_id = NextCollectionID::get();
+            let next_id = NextCollectionID::get()
+                .checked_add(1)
+                .expect("collection id error");
 
             NextCollectionID::put(next_id);
 
             // Create new collection
             let new_collection = CollectionType {
-                owner: who,
+                owner: who.clone(),
+                name: name,
+                description: description,
+                token_prefix: prefix,
                 next_item_id: next_id,
                 custom_data_size: custom_data_sz,
             };
@@ -128,6 +152,9 @@
             // Add new collection to map
             <Collection<T>>::insert(next_id, new_collection);
 
+            // call event
+            Self::deposit_event(RawEvent::Created(next_id, who.clone()));
+
             Ok(())
         }
 
@@ -247,10 +274,19 @@
                 data: properties,
             };
 
-            let current_index = <ItemListIndex>::get(collection_id);
+
+            let current_index = <ItemListIndex>::get(collection_id)
+                .checked_add(1)
+                .expect("Item list index id error");
+
+            Self::add_token_index(collection_id, current_index, new_item.owner.clone())?;
+
             <ItemListIndex>::insert(collection_id, current_index);
             <ItemList<T>>::insert((collection_id, current_index), new_item);
 
+            // call event
+            Self::deposit_event(RawEvent::ItemCreated(collection_id));
+
             Ok(())
         }
 
@@ -279,10 +315,15 @@
             }
             <ItemList<T>>::remove((collection_id, item_id));
 
+            Self::remove_token_index(collection_id, item_id, item.owner.clone())?;
+
             // update balance
             let new_balance = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;
             <Balance<T>>::insert((collection_id, item.owner.clone()), new_balance);
 
+            // call event
+            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));
+
             Ok(())
         }
 
@@ -319,9 +360,13 @@
             <Balance<T>>::insert((collection_id, new_owner.clone()), balance_new_owner);
 
             // change owner
-            item.owner = new_owner;
+            let old_owner = item.owner.clone();
+            item.owner = new_owner.clone();
             <ItemList<T>>::insert((collection_id, item_id), item);
 
+            // update index collection
+            Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;
+
             // reset approved list
             let itm: Vec<T::AccountId> = Vec::new();
             <ApprovedList<T>>::insert((collection_id, item_id), itm);
@@ -401,3 +446,55 @@
         }
     }
 }
+
+
+impl<T: Trait> Module<T> {
+    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {
+        
+        let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));
+        if list_exists {
+
+            let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));
+            let item_contains = list.contains(&item_index.clone());
+
+            if !item_contains {
+                list.push(item_index.clone());
+            }
+
+            <AddressTokens<T>>::insert((collection_id, owner.clone()), list);
+
+        } else {
+
+            let mut itm = Vec::new();
+            itm.push(item_index.clone());
+            <AddressTokens<T>>::insert((collection_id, owner), itm);
+        }
+
+        Ok(())
+    }
+
+    fn remove_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {
+        
+        let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));
+        if list_exists {
+
+            let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));
+            let item_contains = list.contains(&item_index.clone());
+
+            if item_contains {
+                list.retain(|&item| item != item_index);
+                <AddressTokens<T>>::insert((collection_id, owner), list);
+            }
+        }
+
+        Ok(())
+    }
+
+    fn move_token_index(collection_id: u64, item_index: u64, old_owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {
+        
+        Self::remove_token_index(collection_id, item_index, old_owner)?;
+        Self::add_token_index(collection_id, item_index, new_owner)?;
+        
+        Ok(())
+    }
+}
\ No newline at end of file
modifiedpallets/nft/src/tests.rsdiffbeforeafterboth
--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -5,9 +5,14 @@
 #[test]
 fn create_collection_test() {
     new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
         assert_eq!(TemplateModule::collection(1).owner, 1);
     });
 }
@@ -15,10 +20,15 @@
 #[test]
 fn change_collection_owner() {
     new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
 
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
         assert_ok!(TemplateModule::change_collection_owner(
             origin1.clone(),
             1,
@@ -31,10 +41,15 @@
 #[test]
 fn destroy_collection() {
     new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
 
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
         assert_ok!(TemplateModule::destroy_collection(origin1.clone(), 1));
     });
 }
@@ -42,11 +57,16 @@
 #[test]
 fn create_item() {
     new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
         let origin2 = Origin::signed(2);
 
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
         assert_ok!(TemplateModule::create_item(
             origin2.clone(),
@@ -62,11 +82,16 @@
 #[test]
 fn burn_item() {
     new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
         let origin2 = Origin::signed(2);
 
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
         assert_ok!(TemplateModule::create_item(
             origin2.clone(),
@@ -91,14 +116,19 @@
 #[test]
 fn add_collection_admin() {
     new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
         let origin2 = Origin::signed(2);
         let origin3 = Origin::signed(3);
 
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin2.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin3.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin2.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin3.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
 
         assert_eq!(TemplateModule::collection(1).owner, 1);
         assert_eq!(TemplateModule::collection(2).owner, 2);
@@ -116,14 +146,19 @@
 #[test]
 fn remove_collection_admin() {
     new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
         let origin2 = Origin::signed(2);
         let origin3 = Origin::signed(3);
 
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin2.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin3.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin2.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin3.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
 
         assert_eq!(TemplateModule::collection(1).owner, 1);
         assert_eq!(TemplateModule::collection(2).owner, 2);
@@ -149,14 +184,19 @@
 #[test]
 fn balance_of() {
     new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
         let origin2 = Origin::signed(2);
         let origin3 = Origin::signed(3);
 
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin2.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin3.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin2.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin3.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
 
         assert_eq!(TemplateModule::collection(1).owner, 1);
         assert_eq!(TemplateModule::collection(2).owner, 2);
@@ -181,14 +221,19 @@
 #[test]
 fn transfer() {
     new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
         let origin2 = Origin::signed(2);
         let origin3 = Origin::signed(3);
 
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin2.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin3.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin2.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin3.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
 
         assert_eq!(TemplateModule::collection(1).owner, 1);
         assert_eq!(TemplateModule::collection(2).owner, 2);
@@ -214,14 +259,19 @@
 #[test]
 fn approve() {
     new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
         let origin2 = Origin::signed(2);
         let origin3 = Origin::signed(3);
 
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin2.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin3.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin2.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin3.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
 
         assert_eq!(TemplateModule::collection(1).owner, 1);
         assert_eq!(TemplateModule::collection(2).owner, 2);
@@ -243,14 +293,19 @@
 #[test]
 fn get_approved() {
     new_test_ext().execute_with(|| {
+        
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
         let origin2 = Origin::signed(2);
         let origin3 = Origin::signed(3);
 
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin2.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin3.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin2.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin3.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
 
         assert_eq!(TemplateModule::collection(1).owner, 1);
         assert_eq!(TemplateModule::collection(2).owner, 2);
@@ -272,14 +327,19 @@
 #[test]
 fn transfer_from() {
     new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
         let size = 1024;
         let origin1 = Origin::signed(1);
         let origin2 = Origin::signed(2);
         let origin3 = Origin::signed(3);
 
-        assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin2.clone(), size));
-        assert_ok!(TemplateModule::create_collection(origin3.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin2.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin3.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
 
         assert_eq!(TemplateModule::collection(1).owner, 1);
         assert_eq!(TemplateModule::collection(2).owner, 2);
@@ -297,3 +357,50 @@
         assert_ok!(TemplateModule::transfer_from(origin1.clone(), 1, 1, 2));
     });
 }
+
+#[test]
+fn index_list() {
+    new_test_ext().execute_with(|| {
+
+        let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
+        let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
+        let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();
+
+        let size = 1024;
+        let origin1 = Origin::signed(1);
+        let origin2 = Origin::signed(2);
+        let origin3 = Origin::signed(3);
+
+        assert_ok!(TemplateModule::create_collection(origin1.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin2.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+        assert_ok!(TemplateModule::create_collection(origin3.clone(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), size));
+
+        assert_eq!(TemplateModule::collection(1).owner, 1);
+        assert_eq!(TemplateModule::collection(2).owner, 2);
+        assert_eq!(TemplateModule::collection(3).owner, 3);
+        // create items
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 1, 1].to_vec()
+        ));
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 1, 2].to_vec()
+        ));
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec()
+        ));
+        assert_eq!(TemplateModule::address_tokens((1, 1)).len(), 3);
+        // burn one
+        assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 2));
+        assert_eq!(TemplateModule::address_tokens((1, 1)).len(), 2);
+        // burn another one
+        assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 3));
+        assert_eq!(TemplateModule::address_tokens((1, 1))[0], 1);
+    });
+}
+
modifiedruntime/Cargo.tomldiffbeforeafterboth
--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -24,6 +24,11 @@
 package = 'pallet-contracts-primitives'
 version = '2.0.0-alpha.6'
 
+[dependencies.contracts-rpc-runtime-api]
+default-features = false
+package = 'pallet-contracts-rpc-runtime-api'
+version = '0.8.0-alpha.6'
+
 [dependencies.frame-executive]
 default-features = false
 version = '2.0.0-alpha.6'
@@ -143,8 +148,9 @@
     'aura/std',
     'balances/std',
     'codec/std',
-    'contracts/std',
-    'contracts-primitives/std',
+	"contracts/std",
+	"contracts-primitives/std",
+	"contracts-rpc-runtime-api/std",
     'frame-executive/std',
     'frame-support/std',
     'grandpa/std',
modifiedruntime/src/lib.rsdiffbeforeafterboth
before · runtime/src/lib.rs
1//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.23#![cfg_attr(not(feature = "std"), no_std)]4// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.5#![recursion_limit = "256"]67// Make the WASM binary available.8#[cfg(feature = "std")]9include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1011use grandpa::fg_primitives;12use grandpa::AuthorityList as GrandpaAuthorityList;13use sp_api::impl_runtime_apis;14use sp_consensus_aura::sr25519::AuthorityId as AuraId;15use sp_core::OpaqueMetadata;16use sp_runtime::traits::{17    BlakeTwo256, Block as BlockT, ConvertInto, IdentifyAccount, IdentityLookup, Verify,18};19use sp_runtime::{20    create_runtime_str, generic, impl_opaque_keys,21    transaction_validity::{TransactionSource, TransactionValidity},22    ApplyExtrinsicResult, MultiSignature,23};24use sp_std::prelude::*;25#[cfg(feature = "std")]26use sp_version::NativeVersion;27use sp_version::RuntimeVersion;2829// A few exports that help ease life for downstream crates.30pub use balances::Call as BalancesCall;31pub use frame_support::{32    construct_runtime, parameter_types, traits::Randomness, weights::Weight, StorageValue,33};34#[cfg(any(feature = "std", test))]35pub use sp_runtime::BuildStorage;36pub use sp_runtime::{Perbill, Permill};37pub use timestamp::Call as TimestampCall;38pub use contracts::Schedule as ContractsSchedule;3940/// Importing a template pallet41pub use nft;4243/// An index to a block.44pub type BlockNumber = u32;4546/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.47pub type Signature = MultiSignature;4849/// Some way of identifying an account on the chain. We intentionally make it equivalent50/// to the public key of our transaction signing scheme.51pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;5253/// The type for looking up accounts. We don't expect more than 4 billion of them, but you54/// never know...55pub type AccountIndex = u32;5657/// Balance of an account.58pub type Balance = u128;5960/// Index of a transaction in the chain.61pub type Index = u32;6263/// A hash of some data used by the chain.64pub type Hash = sp_core::H256;6566/// Digest item type.67pub type DigestItem = generic::DigestItem<Hash>;6869/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know70/// the specifics of the runtime. They can then be made to be agnostic over specific formats71/// of data like extrinsics, allowing for them to continue syncing the network through upgrades72/// to even the core data structures.73pub mod opaque {74    use super::*;7576    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;7778    /// Opaque block header type.79    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;80    /// Opaque block type.81    pub type Block = generic::Block<Header, UncheckedExtrinsic>;82    /// Opaque block identifier type.83    pub type BlockId = generic::BlockId<Block>;8485    impl_opaque_keys! {86        pub struct SessionKeys {87            pub aura: Aura,88            pub grandpa: Grandpa,89        }90    }91}9293/// This runtime version.94pub const VERSION: RuntimeVersion = RuntimeVersion {95    spec_name: create_runtime_str!("nft"),96    impl_name: create_runtime_str!("nft"),97    authoring_version: 1,98    spec_version: 1,99    impl_version: 1,100    apis: RUNTIME_API_VERSIONS,101};102103pub const MILLISECS_PER_BLOCK: u64 = 6000;104105pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;106107// These time units are defined in number of blocks.108pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);109pub const HOURS: BlockNumber = MINUTES * 60;110pub const DAYS: BlockNumber = HOURS * 24;111112/// The version information used to identify this runtime when compiled natively.113#[cfg(feature = "std")]114pub fn native_version() -> NativeVersion {115    NativeVersion {116        runtime_version: VERSION,117        can_author_with: Default::default(),118    }119}120121parameter_types! {122    pub const BlockHashCount: BlockNumber = 250;123    pub const MaximumBlockWeight: Weight = 1_000_000_000;124    pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);125    pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;126    pub const Version: RuntimeVersion = VERSION;127}128129impl system::Trait for Runtime {130    /// The identifier used to distinguish between accounts.131    type AccountId = AccountId;132    /// The aggregated dispatch type that is available for extrinsics.133    type Call = Call;134    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.135    type Lookup = IdentityLookup<AccountId>;136    /// The index type for storing how many extrinsics an account has signed.137    type Index = Index;138    /// The index type for blocks.139    type BlockNumber = BlockNumber;140    /// The type for hashing blocks and tries.141    type Hash = Hash;142    /// The hashing algorithm used.143    type Hashing = BlakeTwo256;144    /// The header type.145    type Header = generic::Header<BlockNumber, BlakeTwo256>;146    /// The ubiquitous event type.147    type Event = Event;148    /// The ubiquitous origin type.149    type Origin = Origin;150    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).151    type BlockHashCount = BlockHashCount;152    /// Maximum weight of each block.153    type MaximumBlockWeight = MaximumBlockWeight;154    /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.155    type MaximumBlockLength = MaximumBlockLength;156    /// Portion of the block weight that is available to all normal transactions.157    type AvailableBlockRatio = AvailableBlockRatio;158    /// Version of the runtime.159    type Version = Version;160    /// Converts a module to the index of the module in `construct_runtime!`.161    ///162    /// This type is being generated by `construct_runtime!`.163    type ModuleToIndex = ModuleToIndex;164    /// What to do if a new account is created.165    type OnNewAccount = ();166    /// What to do if an account is fully reaped from the system.167    type OnKilledAccount = ();168    /// The data to be stored in an account.169    type AccountData = balances::AccountData<Balance>;170}171172impl aura::Trait for Runtime {173    type AuthorityId = AuraId;174}175176impl grandpa::Trait for Runtime {177    type Event = Event;178}179180parameter_types! {181    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;182}183184impl timestamp::Trait for Runtime {185    /// A timestamp: milliseconds since the unix epoch.186    type Moment = u64;187    type OnTimestampSet = Aura;188    type MinimumPeriod = MinimumPeriod;189}190191parameter_types! {192    pub const ExistentialDeposit: u128 = 500;193}194195impl balances::Trait for Runtime {196    /// The type for recording an account's balance.197    type Balance = Balance;198    /// The ubiquitous event type.199    type Event = Event;200    type DustRemoval = ();201    type ExistentialDeposit = ExistentialDeposit;202    type AccountStore = System;203}204205// Contracts price units.206pub const MILLICENTS: Balance = 1_000_000_000;207pub const CENTS: Balance = 1_000 * MILLICENTS;208pub const DOLLARS: Balance = 100 * CENTS;209210parameter_types! {211    pub const TombstoneDeposit: Balance = 16 * MILLICENTS;212    pub const RentByteFee: Balance = 4 * MILLICENTS;213    pub const RentDepositOffset: Balance = 1000 * MILLICENTS;214	pub const SurchargeReward: Balance = 150 * MILLICENTS;215	pub const ContractTransactionBaseFee: Balance = 1 * CENTS;216	pub const ContractTransactionByteFee: Balance = 10 * MILLICENTS;217	pub const ContractFee: Balance = 1 * CENTS;218}219220impl contracts::Trait for Runtime {221	type Currency = Balances;222	type Time = Timestamp;223	type Randomness = RandomnessCollectiveFlip;224	type Call = Call;225	type Event = Event;226	type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;227	type ComputeDispatchFee = contracts::DefaultDispatchFeeComputor<Runtime>;228	type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;229	type GasPayment = ();230	type RentPayment = ();231	type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;232	type TombstoneDeposit = TombstoneDeposit;233	type StorageSizeOffset = contracts::DefaultStorageSizeOffset;234	type RentByteFee = RentByteFee;235	type RentDepositOffset = RentDepositOffset;236	type SurchargeReward = SurchargeReward;237	type TransactionBaseFee = ContractTransactionBaseFee;238	type TransactionByteFee = ContractTransactionByteFee;239	type ContractFee = ContractFee;240	type CallBaseFee = contracts::DefaultCallBaseFee;241	type InstantiateBaseFee = contracts::DefaultInstantiateBaseFee;242	type MaxDepth = contracts::DefaultMaxDepth;243	type MaxValueSize = contracts::DefaultMaxValueSize;244	type BlockGasLimit = contracts::DefaultBlockGasLimit;245}246247parameter_types! {248    pub const TransactionBaseFee: Balance = 0;249    pub const TransactionByteFee: Balance = 1;250}251252impl transaction_payment::Trait for Runtime {253    type Currency = balances::Module<Runtime>;254    type OnTransactionPayment = ();255    type TransactionBaseFee = TransactionBaseFee;256    type TransactionByteFee = TransactionByteFee;257    type WeightToFee = ConvertInto;258    type FeeMultiplierUpdate = ();259}260261impl sudo::Trait for Runtime {262    type Event = Event;263    type Call = Call;264}265266/// Used for the module template in `./template.rs`267impl nft::Trait for Runtime {268    type Event = Event;269}270271construct_runtime!(272    pub enum Runtime where273        Block = Block,274        NodeBlock = opaque::Block,275        UncheckedExtrinsic = UncheckedExtrinsic,276    {277        System: system::{Module, Call, Config, Storage, Event<T>},278        RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},279        Timestamp: timestamp::{Module, Call, Storage, Inherent},280        Aura: aura::{Module, Config<T>, Inherent(Timestamp)},281        Grandpa: grandpa::{Module, Call, Storage, Config, Event},282        Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},283        TransactionPayment: transaction_payment::{Module, Storage},284		Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},285		Contracts: contracts::{Module, Call, Config<T>, Storage, Event<T>},286        // Used for the module template in `./template.rs`287        Nft: nft::{Module, Call, Storage, Event<T>},288    }289);290291/// The address format for describing accounts.292pub type Address = AccountId;293/// Block header type as expected by this runtime.294pub type Header = generic::Header<BlockNumber, BlakeTwo256>;295/// Block type as expected by this runtime.296pub type Block = generic::Block<Header, UncheckedExtrinsic>;297/// A Block signed with a Justification298pub type SignedBlock = generic::SignedBlock<Block>;299/// BlockId type as expected by this runtime.300pub type BlockId = generic::BlockId<Block>;301/// The SignedExtension to the basic transaction logic.302pub type SignedExtra = (303    system::CheckVersion<Runtime>,304    system::CheckGenesis<Runtime>,305    system::CheckEra<Runtime>,306    system::CheckNonce<Runtime>,307    system::CheckWeight<Runtime>,308    transaction_payment::ChargeTransactionPayment<Runtime>,309);310/// Unchecked extrinsic type as expected by this runtime.311pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;312/// Extrinsic type that has already been checked.313pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;314/// Executive: handles dispatch to the various modules.315pub type Executive =316    frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;317318impl_runtime_apis! {319    impl sp_api::Core<Block> for Runtime {320        fn version() -> RuntimeVersion {321            VERSION322        }323324        fn execute_block(block: Block) {325            Executive::execute_block(block)326        }327328        fn initialize_block(header: &<Block as BlockT>::Header) {329            Executive::initialize_block(header)330        }331    }332333    impl sp_api::Metadata<Block> for Runtime {334        fn metadata() -> OpaqueMetadata {335            Runtime::metadata().into()336        }337    }338339    impl sp_block_builder::BlockBuilder<Block> for Runtime {340        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {341            Executive::apply_extrinsic(extrinsic)342        }343344        fn finalize_block() -> <Block as BlockT>::Header {345            Executive::finalize_block()346        }347348        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {349            data.create_extrinsics()350        }351352        fn check_inherents(353            block: Block,354            data: sp_inherents::InherentData,355        ) -> sp_inherents::CheckInherentsResult {356            data.check_extrinsics(&block)357        }358359        fn random_seed() -> <Block as BlockT>::Hash {360            RandomnessCollectiveFlip::random_seed()361        }362    }363364    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {365        fn validate_transaction(366            source: TransactionSource,367            tx: <Block as BlockT>::Extrinsic,368        ) -> TransactionValidity {369            Executive::validate_transaction(source, tx)370        }371    }372373    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {374        fn offchain_worker(header: &<Block as BlockT>::Header) {375            Executive::offchain_worker(header)376        }377    }378379    impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {380        fn slot_duration() -> u64 {381            Aura::slot_duration()382        }383384        fn authorities() -> Vec<AuraId> {385            Aura::authorities()386        }387    }388389    impl sp_session::SessionKeys<Block> for Runtime {390        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {391            opaque::SessionKeys::generate(seed)392        }393394        fn decode_session_keys(395            encoded: Vec<u8>,396        ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {397            opaque::SessionKeys::decode_into_raw_public_keys(&encoded)398        }399    }400401    impl fg_primitives::GrandpaApi<Block> for Runtime {402        fn grandpa_authorities() -> GrandpaAuthorityList {403            Grandpa::grandpa_authorities()404        }405    }406}