difftreelog
Merge branch 'develop' into feature/NFTPAR-250
in: master
4 files changed
pallets/nft/src/lib.rsdiffbeforeafterboth395 // Basic collections395 // Basic collections396 pub Collection get(fn collection) config(): map hasher(identity) CollectionId => CollectionType<T::AccountId>;396 pub Collection get(fn collection) config(): map hasher(identity) CollectionId => CollectionType<T::AccountId>;397 pub AdminList get(fn admin_list_collection): map hasher(identity) CollectionId => Vec<T::AccountId>;397 pub AdminList get(fn admin_list_collection): map hasher(identity) CollectionId => Vec<T::AccountId>;398 pub WhiteList get(fn white_list): map hasher(identity) CollectionId => Vec<T::AccountId>;398 pub WhiteList get(fn white_list): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => bool;399399400 /// Balance owner per collection map400 /// Balance owner per collection map401 pub Balance get(fn balance_count): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => u128;401 pub Balance get(fn balance_count): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => u128;421 pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;421 pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;422 pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;422 pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;423 pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;423 pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;424 pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool; 425 pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(twox_64_concat) T::AccountId => bool; 424 }426 }425 add_extra_genesis {427 add_extra_genesis {426 build(|config: &GenesisConfig<T>| {428 build(|config: &GenesisConfig<T>| {610 <ItemListIndex>::remove(collection_id);612 <ItemListIndex>::remove(collection_id);611 <AdminList<T>>::remove(collection_id);613 <AdminList<T>>::remove(collection_id);612 <Collection<T>>::remove(collection_id);614 <Collection<T>>::remove(collection_id);613 <WhiteList<T>>::remove(collection_id);615 <WhiteList<T>>::remove_prefix(collection_id);614616615 <NftItemList<T>>::remove_prefix(collection_id);617 <NftItemList<T>>::remove_prefix(collection_id);616 <FungibleItemList<T>>::remove_prefix(collection_id);618 <FungibleItemList<T>>::remove_prefix(collection_id);651 let sender = ensure_signed(origin)?;653 let sender = ensure_signed(origin)?;652 Self::check_owner_or_admin_permissions(collection_id, sender)?;654 Self::check_owner_or_admin_permissions(collection_id, sender)?;653655654 let mut white_list_collection: Vec<T::AccountId>;656 <WhiteList<T>>::insert(collection_id, address, true);655 if <WhiteList<T>>::contains_key(collection_id) {656 white_list_collection = <WhiteList<T>>::get(collection_id);657 if !white_list_collection.contains(&address.clone())658 {659 white_list_collection.push(address.clone());660 }657 661 }662 else {663 white_list_collection = Vec::new();664 white_list_collection.push(address.clone());665 }666667 <WhiteList<T>>::insert(collection_id, white_list_collection);668 Ok(())658 Ok(())669 }659 }670660686 let sender = ensure_signed(origin)?;676 let sender = ensure_signed(origin)?;687 Self::check_owner_or_admin_permissions(collection_id, sender)?;677 Self::check_owner_or_admin_permissions(collection_id, sender)?;688678689 if <WhiteList<T>>::contains_key(collection_id) {679 <WhiteList<T>>::remove(collection_id, address);690 let mut white_list_collection = <WhiteList<T>>::get(collection_id);691 if white_list_collection.contains(&address.clone())692 {693 white_list_collection.retain(|i| *i != address.clone());694 <WhiteList<T>>::insert(collection_id, white_list_collection);695 }696 }697680698 Ok(())681 Ok(())699 }682 }1396 #[cfg(feature = "runtime-benchmarks")]1379 #[cfg(feature = "runtime-benchmarks")]1397 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());1380 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());139813811399 let mut is_owner = false;1382 Self::ensure_contract_owned(sender, &contract_address)?;1400 if <ContractOwner<T>>::contains_key(contract_address.clone()) {1401 let owner = <ContractOwner<T>>::get(&contract_address);1402 is_owner = sender == owner;1403 }1404 ensure!(is_owner, Error::<T>::NoPermission);140513831406 <ContractSelfSponsoring<T>>::insert(contract_address, enable);1384 <ContractSelfSponsoring<T>>::insert(contract_address, enable);1407 Ok(())1385 Ok(())1431 rate_limit: T::BlockNumber1409 rate_limit: T::BlockNumber1432 ) -> DispatchResult {1410 ) -> DispatchResult {1433 let sender = ensure_signed(origin)?;1411 let sender = ensure_signed(origin)?;1434 let mut is_owner = false;1412 Self::ensure_contract_owned(sender, &contract_address)?;1435 if <ContractOwner<T>>::contains_key(contract_address.clone()) {1436 let owner = <ContractOwner<T>>::get(&contract_address);1437 is_owner = sender == owner;1438 }1439 ensure!(is_owner, Error::<T>::NoPermission);144014131441 <ContractSponsoringRateLimit<T>>::insert(contract_address, rate_limit);1414 <ContractSponsoringRateLimit<T>>::insert(contract_address, rate_limit);1442 Ok(())1415 Ok(())1443 }1416 }144414171418 /// Enable the white list for a contract. Only addresses added to the white list with addToContractWhiteList will be able to call this smart contract.1419 /// 1420 /// # Permissions1421 /// 1422 /// * Address that deployed smart contract.1423 /// 1424 /// # Arguments1425 /// 1426 /// -`contract_address`: Address of the contract.1427 /// 1428 /// - `enable`: . 1445 #[weight = 0]1429 #[weight = 0]1430 pub fn toggle_contract_white_list(1431 origin,1432 contract_address: T::AccountId,1433 enable: bool1434 ) -> DispatchResult {1435 let sender = ensure_signed(origin)?;1436 Self::ensure_contract_owned(sender, &contract_address)?;14371438 <ContractWhiteListEnabled<T>>::insert(contract_address, enable);1439 Ok(())1440 }1441 1442 /// Add an address to smart contract white list.1443 /// 1444 /// # Permissions1445 /// 1446 /// * Address that deployed smart contract.1447 /// 1448 /// # Arguments1449 /// 1450 /// -`contract_address`: Address of the contract.1451 ///1452 /// -`account_address`: Address to add.1453 #[weight = 0]1454 pub fn add_to_contract_white_list(1455 origin,1456 contract_address: T::AccountId,1457 account_address: T::AccountId1458 ) -> DispatchResult {1459 let sender = ensure_signed(origin)?;1460 Self::ensure_contract_owned(sender, &contract_address)?;1461 1462 <ContractWhiteList<T>>::insert(contract_address, account_address, true);1463 Ok(())1464 }14651466 /// Remove an address from smart contract white list.1467 /// 1468 /// # Permissions1469 /// 1470 /// * Address that deployed smart contract.1471 /// 1472 /// # Arguments1473 /// 1474 /// -`contract_address`: Address of the contract.1475 ///1476 /// -`account_address`: Address to remove.1477 #[weight = 0]1478 pub fn remove_from_contract_white_list(1479 origin,1480 contract_address: T::AccountId,1481 account_address: T::AccountId1482 ) -> DispatchResult {1483 let sender = ensure_signed(origin)?;1484 Self::ensure_contract_owned(sender, &contract_address)?;1485 1486 <ContractWhiteList<T>>::remove(contract_address, account_address);1487 Ok(())1488 }14891490 #[weight = 0]1446 pub fn set_collection_limits(1491 pub fn set_collection_limits(1447 origin,1492 origin,1448 collection_id: u32,1493 collection_id: u32,177818231779 fn check_white_list(collection_id: CollectionId, address: &T::AccountId) -> DispatchResult {1824 fn check_white_list(collection_id: CollectionId, address: &T::AccountId) -> DispatchResult {1780 let mes = Error::<T>::AddresNotInWhiteList;1825 let mes = Error::<T>::AddresNotInWhiteList;1781 ensure!(<WhiteList<T>>::contains_key(collection_id), mes);1826 ensure!(<WhiteList<T>>::contains_key(collection_id, address), mes);1782 let wl = <WhiteList<T>>::get(collection_id);1783 ensure!(wl.contains(address), mes);178418271785 Ok(())1828 Ok(())1786 }1829 }213821812139 Ok(())2182 Ok(())2140 }2183 }2184 2185 fn ensure_contract_owned(account: T::AccountId, contract: &T::AccountId) -> DispatchResult {2186 if <ContractOwner<T>>::contains_key(contract.clone()) {2187 let owner = <ContractOwner<T>>::get(contract);2188 ensure!(account == owner, Error::<T>::NoPermission);2189 } else {2190 fail!(Error::<T>::NoPermission);2191 }21922193 Ok(())2194 }2141}2195}214221962143////////////////////////////////////////////////////////////////////////////////////////////////////2197////////////////////////////////////////////////////////////////////////////////////////////////////2356 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {2410 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {235724112358 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());2412 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());24132414 let owned_contract = <ContractOwner<T>>::contains_key(called_contract.clone())2415 && <ContractOwner<T>>::get(called_contract.clone()) == *who;2416 let white_list_enabled = <ContractWhiteListEnabled<T>>::contains_key(called_contract.clone()) && <ContractWhiteListEnabled<T>>::get(called_contract.clone());2417 2418 if !owned_contract && white_list_enabled {2419 if !<ContractWhiteList<T>>::contains_key(called_contract.clone(), who) {2420 return Err(InvalidTransaction::Call.into());2421 }2422 }235924232360 let mut sponsor_transfer = false;2424 let mut sponsor_transfer = false;2361 if <ContractSponsoringRateLimit<T>>::contains_key(called_contract.clone()) {2425 if <ContractSponsoringRateLimit<T>>::contains_key(called_contract.clone()) {pallets/nft/src/tests.rsdiffbeforeafterboth960960961 let origin1 = Origin::signed(1);961 let origin1 = Origin::signed(1);962 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));962 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));963 assert_eq!(TemplateModule::white_list(collection_id)[0], 2);963 assert_eq!(TemplateModule::white_list(collection_id, 2), true);964 });964 });965}965}966966975975976 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));976 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));977 assert_ok!(TemplateModule::add_to_white_list(origin2.clone(), collection_id, 3));977 assert_ok!(TemplateModule::add_to_white_list(origin2.clone(), collection_id, 3));978 assert_eq!(TemplateModule::white_list(collection_id)[0], 3);978 assert_eq!(TemplateModule::white_list(collection_id, 3), true);979 });979 });980}980}9819811035 1035 1036 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1036 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1037 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1037 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1038 assert_eq!(TemplateModule::white_list(collection_id)[0], 2);1038 assert_eq!(TemplateModule::white_list(collection_id, 2), true);1039 assert_eq!(TemplateModule::white_list(collection_id).len(), 1);1040 });1039 });1041}1040}104210411054 collection_id,1053 collection_id,1055 21054 21056 ));1055 ));1057 assert_eq!(TemplateModule::white_list(collection_id).len(), 0);1056 assert_eq!(TemplateModule::white_list(collection_id, 2), false);1058 });1057 });1059}1058}106010591075 collection_id,1074 collection_id,1076 31075 31077 ));1076 ));1078 assert_eq!(TemplateModule::white_list(collection_id).len(), 0);1077 assert_eq!(TemplateModule::white_list(collection_id, 3), false);1079 });1078 });1080}1079}108110801093 TemplateModule::remove_from_white_list(origin2.clone(), collection_id, 2),1092 TemplateModule::remove_from_white_list(origin2.clone(), collection_id, 2),1094 Error::<Test>::NoPermission1093 Error::<Test>::NoPermission1095 );1094 );1096 assert_eq!(TemplateModule::white_list(collection_id)[0], 2);1095 assert_eq!(TemplateModule::white_list(collection_id, 2), true);1097 });1096 });1098}1097}109910981125 TemplateModule::remove_from_white_list(origin2.clone(), collection_id, 2),1124 TemplateModule::remove_from_white_list(origin2.clone(), collection_id, 2),1126 Error::<Test>::CollectionNotFound1125 Error::<Test>::CollectionNotFound1127 );1126 );1128 assert_eq!(TemplateModule::white_list(collection_id).len(), 0);1127 assert_eq!(TemplateModule::white_list(collection_id, 2), false);1129 });1128 });1130}1129}113111301149 collection_id,1148 collection_id,1150 21149 21151 ));1150 ));1152 assert_eq!(TemplateModule::white_list(collection_id).len(), 0);1151 assert_eq!(TemplateModule::white_list(collection_id, 2), false);1153 });1152 });1154}1153}11551154tests/src/contracts.test.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise } from "@polkadot/api";1import chai from "chai";7import { expect } from "chai";2import chaiAsPromised from 'chai-as-promised';8import { default as usingApi, submitTransactionAsync } from "./substrate/substrate-api";3import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";9import fs from "fs";4import fs from "fs";10import { Abi, BlueprintPromise, CodePromise } from "@polkadot/api-contract";5import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";11import { IKeyringPair } from "@polkadot/types/types";6import { IKeyringPair } from "@polkadot/types/types";12import { Keyring } from "@polkadot/api";7import { ApiPromise, Keyring } from "@polkadot/api";13import { ApiTypes, SubmittableExtrinsic } from "@polkadot/api/types";8import { ApiTypes, SubmittableExtrinsic } from "@polkadot/api/types";9import privateKey from "./substrate/privateKey";1011chai.use(chaiAsPromised);12const expect = chai.expect;14import { BigNumber } from 'bignumber.js';13import { BigNumber } from 'bignumber.js';15import { findUnusedAddress } from './util/helpers'14import { findUnusedAddress } from './util/helpers'161517const value = 0;16const value = 0;18const gasLimit = 3000n * 1000000n;17const gasLimit = 3000n * 1000000n;19const endowment = `1000000000000000`;18const endowment = `1000000000000000`;201921function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<BlueprintPromise> {20function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {22 return new Promise<BlueprintPromise>(async (resolve, reject) => {21 return new Promise<Blueprint>(async (resolve, reject) => {23 const unsub = await code22 const unsub = await code24 .createBlueprint()23 .createBlueprint()25 .signAndSend(alice, (result) => {24 .signAndSend(alice, (result) => {32 });31 });33}32}343335function deployContract(alice: IKeyringPair, blueprint: BlueprintPromise) : Promise<any> {34function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {36 return new Promise<any>(async (resolve, reject) => {35 return new Promise<any>(async (resolve, reject) => {37 const initValue = true;36 const initValue = true;383762 return deployer;61 return deployer;63}62}6364async function deployFlipper(api: ApiPromise): Promise<[Contract, IKeyringPair]> {65 const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));66 const abi = new Abi(metadata);6768 const deployer = await prepareDeployer(api);6970 const wasm = fs.readFileSync('./src/flipper/flipper.wasm');7172 const code = new CodePromise(api, abi, wasm);7374 const blueprint = await deployBlueprint(deployer, code);75 const contract = (await deployContract(deployer, blueprint))['contract'] as Contract;7677 const initialGetResponse = await getFlipValue(contract, deployer);78 expect(initialGetResponse).to.be.true;7980 return [contract, deployer];81}8283async function getFlipValue(contract: Contract, deployer: IKeyringPair) {84 const result = await contract.query.get(deployer.address, value, gasLimit);8586 if(!result.result.isSuccess) {87 throw `Failed to get flipper value`;88 }89 return (result.result.asSuccess.data[0] == 0x00) ? false : true;90}649165describe('Contracts smoke test', () => {92describe('Contracts', () => {93 it(`Can deploy smart contract Flipper, instantiate it and call it's get and flip messages.`, async () => {94 await usingApi(async api => {95 const [contract, deployer] = await deployFlipper(api);96 const initialGetResponse = await getFlipValue(contract, deployer);9798 const bob = privateKey("//Bob");99 const flip = contract.exec('flip', value, gasLimit);100 await submitTransactionAsync(bob, flip);101102 const afterFlipGetResponse = await getFlipValue(contract, deployer);103 expect(afterFlipGetResponse).not.to.be.eq(initialGetResponse, 'Flipping should change value.');104 });105 });10666 it(`Can deploy smart contract Flipper, instantiate it and call it's get and flip messages.`, async () => {107 it(`Whitelisted account can call contract.`, async () => {67 await usingApi(async api => {108 await usingApi(async api => {109 const bob = privateKey("//Bob");110 68 const deployer = await prepareDeployer(api);111 const [contract, deployer] = await deployFlipper(api);69 70 const wasm = fs.readFileSync('./src/flipper/flipper.wasm');112 const consoleError = console.error;71 72 const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));113 console.error = (...data: any[]) => {114 };11573 const abi = new Abi(metadata);116 let expectedFlipValue = await getFlipValue(contract, deployer);7411775 const code = new CodePromise(api, abi, wasm);118 const flip = contract.exec('flip', value, gasLimit);76119 await submitTransactionAsync(bob, flip);120 expectedFlipValue = !expectedFlipValue;77 const blueprint = await deployBlueprint(deployer, code);121 const afterFlip = await getFlipValue(contract,deployer);78 const contract = (await deployContract(deployer, blueprint))['contract'];122 expect(afterFlip).to.be.eq(expectedFlipValue, `Anyone can call new contract.`);7912380 const getFlipValue = async () => {124 const deployerCanFlip = async () => {125 expectedFlipValue = !expectedFlipValue;81 const result = await contract.query.get(deployer.address, value, gasLimit);126 const deployerFlip = contract.exec('flip', value, gasLimit);82127 await submitTransactionAsync(deployer, deployerFlip);83 if(!result.result.isSuccess) {84 throw `Failed to get flipper value`;128 const aliceFlip1Response = await getFlipValue(contract, deployer);85 }86 return (result.result.asSuccess.data[0] == 0x00) ? false : true;129 expect(aliceFlip1Response).to.be.eq(expectedFlipValue, `Deployer always can flip.`);87 }130 };88131 await deployerCanFlip();132133 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);134 const enableResult = await submitTransactionAsync(deployer, enableWhiteListTx);135 const flipWithEnabledWhiteList = contract.exec('flip', value, gasLimit);136 await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledWhiteList)).to.be.rejected;89 const initialGetResponse = await getFlipValue();137 const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);90 expect(initialGetResponse).to.be.true;138 expect(flipValueAfterEnableWhiteList).to.be.eq(expectedFlipValue, `Enabling whitelist doesn't make it possible to call contract for everyone.`);91139140 await deployerCanFlip();141142 const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);143 const addBobResult = await submitTransactionAsync(deployer, addBobToWhiteListTx);92 const flip = contract.exec('flip', value, gasLimit);144 const flipWithWhitelistedBob = contract.exec('flip', value, gasLimit);145 await submitTransactionAsync(bob, flipWithWhitelistedBob);146 expectedFlipValue = !expectedFlipValue;147 const flipAfterWhiteListed = await getFlipValue(contract,deployer);148 expect(flipAfterWhiteListed).to.be.eq(expectedFlipValue, `Bob was whitelisted, now he can flip.`);149150 await deployerCanFlip();151152 const removeBobFromWhiteListTx = api.tx.nft.removeFromContractWhiteList(contract.address, bob.address);93 await submitTransactionAsync(deployer, flip);153 const removeBobResult = await submitTransactionAsync(deployer, removeBobFromWhiteListTx);94154 const bobRemoved = contract.exec('flip', value, gasLimit);155 await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;95 const afterFlipGetResponse = await getFlipValue();156 const afterBobRemoved = await getFlipValue(contract, deployer);9697 expect(afterFlipGetResponse).to.be.false;157 expect(afterBobRemoved).to.be.eq(expectedFlipValue, `Bob can't call contract, now when he is removeed from white list.`);158159 await deployerCanFlip();160161 const disableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, false);162 const disableWhiteListResult = await submitTransactionAsync(deployer, disableWhiteListTx);163 const whiteListDisabledFlip = contract.exec('flip', value, gasLimit);164 await submitTransactionAsync(bob, whiteListDisabledFlip);165 expectedFlipValue = !expectedFlipValue;166 const afterWhiteListDisabled = await getFlipValue(contract,deployer);167 expect(afterWhiteListDisabled).to.be.eq(expectedFlipValue, `Anyone can call contract with disabled whitelist.`);168169 console.error = consoleError;98 });170 });99 });171 });100172tests/src/substrate/substrate-api.tsdiffbeforeafterboth57 });57 });58}58}595960export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {61 return new Promise(async function(resolve, reject) {62 try {63 await transaction.signAndSend(sender, ({ events = [], status }) => {64 if (status.isReady) {65 // nothing to do66 // console.log(`Current tx status is Ready`);67 } else if (status.isBroadcast) {68 // nothing to do69 // console.log(`Current tx status is Broadcast`);70 } else if (status.isInBlock || status.isFinalized) {71 resolve(events);72 } else {73 reject("Transaction failed");74 }75 });76 } catch (e) {77 reject(e);78 }79 });80}