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

difftreelog

NFTPAR-231 Smart Contract White List. Integration tests for smart contract white list. Also changed white list to double map.

sotmorskiy2020-12-24parent: #c3c0503.patch.diff
in: master

4 files changed

modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
412 // Basic collections412 // Basic collections
413 pub Collection get(fn collection) config(): map hasher(identity) CollectionId => CollectionType<T::AccountId>;413 pub Collection get(fn collection) config(): map hasher(identity) CollectionId => CollectionType<T::AccountId>;
414 pub AdminList get(fn admin_list_collection): map hasher(identity) CollectionId => Vec<T::AccountId>;414 pub AdminList get(fn admin_list_collection): map hasher(identity) CollectionId => Vec<T::AccountId>;
415 pub WhiteList get(fn white_list): map hasher(identity) CollectionId => Vec<T::AccountId>;415 pub WhiteList get(fn white_list): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => bool;
416416
417 /// Balance owner per collection map417 /// Balance owner per collection map
418 pub Balance get(fn balance_count): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => u128;418 pub Balance get(fn balance_count): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => u128;
438 pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;438 pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;
439 pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;439 pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;
440 pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;440 pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;
441 pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool;
442 pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(twox_64_concat) T::AccountId => bool;
441 }443 }
442 add_extra_genesis {444 add_extra_genesis {
443 build(|config: &GenesisConfig<T>| {445 build(|config: &GenesisConfig<T>| {
627 <ItemListIndex>::remove(collection_id);629 <ItemListIndex>::remove(collection_id);
628 <AdminList<T>>::remove(collection_id);630 <AdminList<T>>::remove(collection_id);
629 <Collection<T>>::remove(collection_id);631 <Collection<T>>::remove(collection_id);
630 <WhiteList<T>>::remove(collection_id);632 <WhiteList<T>>::remove_prefix(collection_id);
631633
632 <NftItemList<T>>::remove_prefix(collection_id);634 <NftItemList<T>>::remove_prefix(collection_id);
633 <FungibleItemList<T>>::remove_prefix(collection_id);635 <FungibleItemList<T>>::remove_prefix(collection_id);
668 let sender = ensure_signed(origin)?;670 let sender = ensure_signed(origin)?;
669 Self::check_owner_or_admin_permissions(collection_id, sender)?;671 Self::check_owner_or_admin_permissions(collection_id, sender)?;
670672
671 let mut white_list_collection: Vec<T::AccountId>;673 <WhiteList<T>>::insert(collection_id, address, true);
672 if <WhiteList<T>>::contains_key(collection_id) {
673 white_list_collection = <WhiteList<T>>::get(collection_id);
674 if !white_list_collection.contains(&address.clone())
675 {
676 white_list_collection.push(address.clone());
677 }674
678 }
679 else {
680 white_list_collection = Vec::new();
681 white_list_collection.push(address.clone());
682 }
683
684 <WhiteList<T>>::insert(collection_id, white_list_collection);
685 Ok(())675 Ok(())
686 }676 }
687677
703 let sender = ensure_signed(origin)?;693 let sender = ensure_signed(origin)?;
704 Self::check_owner_or_admin_permissions(collection_id, sender)?;694 Self::check_owner_or_admin_permissions(collection_id, sender)?;
705695
706 if <WhiteList<T>>::contains_key(collection_id) {696 <WhiteList<T>>::remove(collection_id, address);
707 let mut white_list_collection = <WhiteList<T>>::get(collection_id);
708 if white_list_collection.contains(&address.clone())
709 {
710 white_list_collection.retain(|i| *i != address.clone());
711 <WhiteList<T>>::insert(collection_id, white_list_collection);
712 }
713 }
714697
715 Ok(())698 Ok(())
716 }699 }
1426 #[cfg(feature = "runtime-benchmarks")]1409 #[cfg(feature = "runtime-benchmarks")]
1427 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());1410 <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());
14281411
1429 let mut is_owner = false;1412 Self::ensure_contract_owned(sender, &contract_address)?;
1430 if <ContractOwner<T>>::contains_key(contract_address.clone()) {
1431 let owner = <ContractOwner<T>>::get(&contract_address);
1432 is_owner = sender == owner;
1433 }
1434 ensure!(is_owner, Error::<T>::NoPermission);
14351413
1436 <ContractSelfSponsoring<T>>::insert(contract_address, enable);1414 <ContractSelfSponsoring<T>>::insert(contract_address, enable);
1437 Ok(())1415 Ok(())
1461 rate_limit: T::BlockNumber1439 rate_limit: T::BlockNumber
1462 ) -> DispatchResult {1440 ) -> DispatchResult {
1463 let sender = ensure_signed(origin)?;1441 let sender = ensure_signed(origin)?;
1464 let mut is_owner = false;1442 Self::ensure_contract_owned(sender, &contract_address)?;
1465 if <ContractOwner<T>>::contains_key(contract_address.clone()) {
1466 let owner = <ContractOwner<T>>::get(&contract_address);
1467 is_owner = sender == owner;
1468 }
1469 ensure!(is_owner, Error::<T>::NoPermission);
14701443
1471 <ContractSponsoringRateLimit<T>>::insert(contract_address, rate_limit);1444 <ContractSponsoringRateLimit<T>>::insert(contract_address, rate_limit);
1472 Ok(())1445 Ok(())
1473 }1446 }
14741447
1448 /// Enable the white list for a contract. Only addresses added to the white list with addToContractWhiteList will be able to call this smart contract.
1449 ///
1450 /// # Permissions
1451 ///
1452 /// * Address that deployed smart contract.
1453 ///
1454 /// # Arguments
1455 ///
1456 /// -`contract_address`: Address of the contract.
1457 ///
1458 /// - `enable`: .
1475 #[weight = 0]1459 #[weight = 0]
1460 pub fn toggle_contract_white_list(
1461 origin,
1462 contract_address: T::AccountId,
1463 enable: bool
1464 ) -> DispatchResult {
1465 let sender = ensure_signed(origin)?;
1466 Self::ensure_contract_owned(sender, &contract_address)?;
1467
1468 <ContractWhiteListEnabled<T>>::insert(contract_address, enable);
1469 Ok(())
1470 }
1471
1472 /// Add an address to smart contract white list.
1473 ///
1474 /// # Permissions
1475 ///
1476 /// * Address that deployed smart contract.
1477 ///
1478 /// # Arguments
1479 ///
1480 /// -`contract_address`: Address of the contract.
1481 ///
1482 /// -`account_address`: Address to add.
1483 #[weight = 0]
1484 pub fn add_to_contract_white_list(
1485 origin,
1486 contract_address: T::AccountId,
1487 account_address: T::AccountId
1488 ) -> DispatchResult {
1489 let sender = ensure_signed(origin)?;
1490 Self::ensure_contract_owned(sender, &contract_address)?;
1491
1492 <ContractWhiteList<T>>::insert(contract_address, account_address, true);
1493 Ok(())
1494 }
1495
1496 /// Remove an address from smart contract white list.
1497 ///
1498 /// # Permissions
1499 ///
1500 /// * Address that deployed smart contract.
1501 ///
1502 /// # Arguments
1503 ///
1504 /// -`contract_address`: Address of the contract.
1505 ///
1506 /// -`account_address`: Address to remove.
1507 #[weight = 0]
1508 pub fn remove_from_contract_white_list(
1509 origin,
1510 contract_address: T::AccountId,
1511 account_address: T::AccountId
1512 ) -> DispatchResult {
1513 let sender = ensure_signed(origin)?;
1514 Self::ensure_contract_owned(sender, &contract_address)?;
1515
1516 <ContractWhiteList<T>>::remove(contract_address, account_address);
1517 Ok(())
1518 }
1519
1520 #[weight = 0]
1476 pub fn set_collection_limits(1521 pub fn set_collection_limits(
1477 origin,1522 origin,
1478 collection_id: u32,1523 collection_id: u32,
18301875
1831 fn check_white_list(collection_id: CollectionId, address: &T::AccountId) -> DispatchResult {1876 fn check_white_list(collection_id: CollectionId, address: &T::AccountId) -> DispatchResult {
1832 let mes = Error::<T>::AddresNotInWhiteList;1877 let mes = Error::<T>::AddresNotInWhiteList;
1833 ensure!(<WhiteList<T>>::contains_key(collection_id), mes);1878 ensure!(<WhiteList<T>>::contains_key(collection_id, address), mes);
1834 let wl = <WhiteList<T>>::get(collection_id);
1835 ensure!(wl.contains(address), mes);
18361879
1837 Ok(())1880 Ok(())
1838 }1881 }
22502293
2251 Ok(())2294 Ok(())
2252 }2295 }
2296
2297 fn ensure_contract_owned(account: T::AccountId, contract: &T::AccountId) -> DispatchResult {
2298 if <ContractOwner<T>>::contains_key(contract.clone()) {
2299 let owner = <ContractOwner<T>>::get(contract);
2300 ensure!(account == owner, Error::<T>::NoPermission);
2301 } else {
2302 fail!(Error::<T>::NoPermission);
2303 }
2304
2305 Ok(())
2306 }
2253}2307}
22542308
2255////////////////////////////////////////////////////////////////////////////////////////////////////2309////////////////////////////////////////////////////////////////////////////////////////////////////
2456 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {2510 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {
24572511
2458 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());2512 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());
2513
2514 let owned_contract = <ContractOwner<T>>::contains_key(called_contract.clone())
2515 && <ContractOwner<T>>::get(called_contract.clone()) == *who;
2516
2517 if !owned_contract {
2518 let white_list_enabled = <ContractWhiteListEnabled<T>>::contains_key(called_contract.clone()) && <ContractWhiteListEnabled<T>>::get(called_contract.clone());
2519 if !white_list_enabled || !<ContractWhiteList<T>>::contains_key(called_contract.clone(), who) {
2520 return Err(InvalidTransaction::Call.into());
2521 }
2522 }
24592523
2460 let mut sponsor_transfer = false;2524 let mut sponsor_transfer = false;
2461 if <ContractSponsoringRateLimit<T>>::contains_key(called_contract.clone()) {2525 if <ContractSponsoringRateLimit<T>>::contains_key(called_contract.clone()) {
modifiedpallets/nft/src/tests.rsdiffbeforeafterboth
960960
961 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}
966966
975975
976 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}
981981
1035 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}
10421041
1054 collection_id,1053 collection_id,
1055 21054 2
1056 ));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}
10601059
1075 collection_id,1074 collection_id,
1076 31075 3
1077 ));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}
10811080
1093 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>::NoPermission
1095 );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}
10991098
1125 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>::CollectionNotFound
1127 );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}
11311130
1149 collection_id,1148 collection_id,
1150 21149 2
1151 ));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}
11551154
modifiedtests/src/contracts.test.tsdiffbeforeafterboth
1//
2// This file is subject to the terms and conditions defined in
3// file 'LICENSE', which is part of this source code package.
4//
5
6import { 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";
10
11chai.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'
1615
17const value = 0;16const value = 0;
18const gasLimit = 3000n * 1000000n;17const gasLimit = 3000n * 1000000n;
19const endowment = `1000000000000000`;18const endowment = `1000000000000000`;
2019
21function 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 code
24 .createBlueprint()23 .createBlueprint()
25 .signAndSend(alice, (result) => {24 .signAndSend(alice, (result) => {
32 });31 });
33}32}
3433
35function 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;
3837
62 return deployer;61 return deployer;
63}62}
63
64async 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);
67
68 const deployer = await prepareDeployer(api);
69
70 const wasm = fs.readFileSync('./src/flipper/flipper.wasm');
71
72 const code = new CodePromise(api, abi, wasm);
73
74 const blueprint = await deployBlueprint(deployer, code);
75 const contract = (await deployContract(deployer, blueprint))['contract'] as Contract;
76
77 const initialGetResponse = await getFlipValue(contract, deployer);
78 expect(initialGetResponse).to.be.true;
79
80 return [contract, deployer];
81}
82
83async function getFlipValue(contract: Contract, deployer: IKeyringPair) {
84 const result = await contract.query.get(deployer.address, value, gasLimit);
85
86 if(!result.result.isSuccess) {
87 throw `Failed to get flipper value`;
88 }
89 return (result.result.asSuccess.data[0] == 0x00) ? false : true;
90}
6491
65describe('Contracts smoke test', () => {92describe('Contracts smoke test', () => {
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);
97
98 const flip = contract.exec('flip', value, gasLimit);
99 await submitTransactionAsync(deployer, flip);
100
101 const afterFlipGetResponse = await getFlipValue(contract, deployer);
102 expect(afterFlipGetResponse).not.to.be.eq(initialGetResponse, 'Flipping should change value.');
103 });
104 });
105
66 it(`Can deploy smart contract Flipper, instantiate it and call it's get and flip messages.`, async () => {106 it(`Whitelisted account can call contract.`, async () => {
67 await usingApi(async api => {107 await usingApi(async api => {
108 const bob = privateKey("//Bob");
109
68 const deployer = await prepareDeployer(api);110 const [contract, deployer] = await deployFlipper(api);
69
70 const wasm = fs.readFileSync('./src/flipper/flipper.wasm');111 const consoleError = console.error;
71
72 const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));112 console.error = (...data: any[]) => {
113 };
114
73 const abi = new Abi(metadata);115 let expectedFlipValue = await getFlipValue(contract, deployer);
74116
75 const code = new CodePromise(api, abi, wasm);117 const flip = contract.exec('flip', value, gasLimit);
76118 await expect(submitTransactionExpectFailAsync(bob, flip)).to.be.rejected;
77 const blueprint = await deployBlueprint(deployer, code);119 const firstFailResponse = await getFlipValue(contract, deployer);
78 const contract = (await deployContract(deployer, blueprint))['contract'];120 expect(firstFailResponse).to.be.eq(expectedFlipValue, `Only account who deployed contract can flip value.`);
79121
80 const getFlipValue = async () => {122 const deployerCanFlip = async () => {
123 expectedFlipValue = !expectedFlipValue;
81 const result = await contract.query.get(deployer.address, value, gasLimit);124 const deployerFlip = contract.exec('flip', value, gasLimit);
82125 await submitTransactionAsync(deployer, deployerFlip);
83 if(!result.result.isSuccess) {
84 throw `Failed to get flipper value`;126 const aliceFlip1Response = await getFlipValue(contract, deployer);
85 }
86 return (result.result.asSuccess.data[0] == 0x00) ? false : true;127 expect(aliceFlip1Response).to.be.eq(expectedFlipValue, `Deployer always can flip.`);
87 }128 };
88129 await deployerCanFlip();
130
131 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);
132 const enableResult = await submitTransactionAsync(deployer, enableWhiteListTx);
133 const flipWithEnabledWhiteList = contract.exec('flip', value, gasLimit);
134 await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledWhiteList)).to.be.rejected;
89 const initialGetResponse = await getFlipValue();135 const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);
90 expect(initialGetResponse).to.be.true;136 expect(flipValueAfterEnableWhiteList).to.be.eq(expectedFlipValue, `Enabling whitelist doesn't make it possible to call contract for everyone.`);
91137
138 await deployerCanFlip();
139
140 const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);
141 const addBobResult = await submitTransactionAsync(deployer, addBobToWhiteListTx);
92 const flip = contract.exec('flip', value, gasLimit);142 const flipWithWhitelistedBob = contract.exec('flip', value, gasLimit);
143 await submitTransactionAsync(bob, flipWithWhitelistedBob);
144 expectedFlipValue = !expectedFlipValue;
145 const flipAfterWhiteListed = await getFlipValue(contract,deployer);
146 expect(flipAfterWhiteListed).to.be.eq(expectedFlipValue, `Bob was whitelisted, now he can flip.`);
147
148 await deployerCanFlip();
149
150 const disableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, false);
93 await submitTransactionAsync(deployer, flip);151 const disableeResult = await submitTransactionAsync(deployer, disableWhiteListTx);
94152 const flipWithDisabledWhitelist = contract.exec('flip', value, gasLimit);
153 await expect(submitTransactionExpectFailAsync(bob, flipWithDisabledWhitelist)).to.be.rejected;
95 const afterFlipGetResponse = await getFlipValue();154 const flipWithDisabledWhiteList = await getFlipValue(contract, deployer);
96
97 expect(afterFlipGetResponse).to.be.false;155 expect(flipWithDisabledWhiteList).to.be.eq(expectedFlipValue, `Bob can't flip when whitelist is disabled, even tho he is in whitelist.`);
156
157 await deployerCanFlip();
158
159 const enableWhiteListOneMoreTimeTx = api.tx.nft.toggleContractWhiteList(contract.address, true);
160 const enableOneMoreTimeResult = await submitTransactionAsync(deployer, enableWhiteListOneMoreTimeTx);
161
162 await deployerCanFlip();
163
164 const removeBobFromWhiteListTx = api.tx.nft.removeFromContractWhiteList(contract.address, bob.address);
165 const removeBobResult = await submitTransactionAsync(deployer, removeBobFromWhiteListTx);
166 const bobRemoved = contract.exec('flip', value, gasLimit);
167 await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;
168 const afterBobRemoved = await getFlipValue(contract, deployer);
169 expect(afterBobRemoved).to.be.eq(expectedFlipValue, `Enabling whitelist doesn't make it possible to call contract for everyone.`);
170
171 await deployerCanFlip();
172
173 const cleanupTx = api.tx.nft.toggleContractWhiteList(contract.address, false);
174 const cleanupResult = await submitTransactionAsync(deployer, cleanupTx);
175
176 console.error = consoleError;
98 });177 });
99 });178 });
100179
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
57 });57 });
58}58}
5959
60export 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 do
66 // console.log(`Current tx status is Ready`);
67 } else if (status.isBroadcast) {
68 // nothing to do
69 // 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}