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

difftreelog

Merge branch 'develop' into feature/NFTPAR-250

Greg Zaitsev2020-12-25parents: #f7b41a8 #d430fcf.patch.diff
in: master

4 files changed

modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -395,7 +395,7 @@
         // Basic collections
         pub Collection get(fn collection) config(): map hasher(identity) CollectionId => CollectionType<T::AccountId>;
         pub AdminList get(fn admin_list_collection): map hasher(identity) CollectionId => Vec<T::AccountId>;
-        pub WhiteList get(fn white_list): map hasher(identity) CollectionId => Vec<T::AccountId>;
+        pub WhiteList get(fn white_list): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => bool;
 
         /// Balance owner per collection map
         pub Balance get(fn balance_count): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => u128;
@@ -421,6 +421,8 @@
         pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;
         pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;
         pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;
+        pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool; 
+        pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(twox_64_concat) T::AccountId => bool; 
     }
     add_extra_genesis {
         build(|config: &GenesisConfig<T>| {
@@ -610,7 +612,7 @@
             <ItemListIndex>::remove(collection_id);
             <AdminList<T>>::remove(collection_id);
             <Collection<T>>::remove(collection_id);
-            <WhiteList<T>>::remove(collection_id);
+            <WhiteList<T>>::remove_prefix(collection_id);
 
             <NftItemList<T>>::remove_prefix(collection_id);
             <FungibleItemList<T>>::remove_prefix(collection_id);
@@ -651,20 +653,8 @@
             let sender = ensure_signed(origin)?;
             Self::check_owner_or_admin_permissions(collection_id, sender)?;
 
-            let mut white_list_collection: Vec<T::AccountId>;
-            if <WhiteList<T>>::contains_key(collection_id) {
-                white_list_collection = <WhiteList<T>>::get(collection_id);
-                if !white_list_collection.contains(&address.clone())
-                {
-                    white_list_collection.push(address.clone());
-                }
-            }
-            else {
-                white_list_collection = Vec::new();
-                white_list_collection.push(address.clone());
-            }
-
-            <WhiteList<T>>::insert(collection_id, white_list_collection);
+            <WhiteList<T>>::insert(collection_id, address, true);
+            
             Ok(())
         }
 
@@ -686,14 +676,7 @@
             let sender = ensure_signed(origin)?;
             Self::check_owner_or_admin_permissions(collection_id, sender)?;
 
-            if <WhiteList<T>>::contains_key(collection_id) {
-                let mut white_list_collection = <WhiteList<T>>::get(collection_id);
-                if white_list_collection.contains(&address.clone())
-                {
-                    white_list_collection.retain(|i| *i != address.clone());
-                    <WhiteList<T>>::insert(collection_id, white_list_collection);
-                }
-            }
+            <WhiteList<T>>::remove(collection_id, address);
 
             Ok(())
         }
@@ -1396,12 +1379,7 @@
             #[cfg(feature = "runtime-benchmarks")]
             <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());
 
-            let mut is_owner = false;
-            if <ContractOwner<T>>::contains_key(contract_address.clone()) {
-                let owner = <ContractOwner<T>>::get(&contract_address);
-                is_owner = sender == owner;
-            }
-            ensure!(is_owner, Error::<T>::NoPermission);
+            Self::ensure_contract_owned(sender, &contract_address)?;
 
             <ContractSelfSponsoring<T>>::insert(contract_address, enable);
             Ok(())
@@ -1431,18 +1409,85 @@
             rate_limit: T::BlockNumber
         ) -> DispatchResult {
             let sender = ensure_signed(origin)?;
-            let mut is_owner = false;
-            if <ContractOwner<T>>::contains_key(contract_address.clone()) {
-                let owner = <ContractOwner<T>>::get(&contract_address);
-                is_owner = sender == owner;
-            }
-            ensure!(is_owner, Error::<T>::NoPermission);
+            Self::ensure_contract_owned(sender, &contract_address)?;
 
             <ContractSponsoringRateLimit<T>>::insert(contract_address, rate_limit);
             Ok(())
         }
 
+        /// Enable the white list for a contract. Only addresses added to the white list with addToContractWhiteList will be able to call this smart contract.
+        /// 
+        /// # Permissions
+        /// 
+        /// * Address that deployed smart contract.
+        /// 
+        /// # Arguments
+        /// 
+        /// -`contract_address`: Address of the contract.
+        /// 
+        /// - `enable`: .  
+        #[weight = 0]
+        pub fn toggle_contract_white_list(
+            origin,
+            contract_address: T::AccountId,
+            enable: bool
+        ) -> DispatchResult {
+            let sender = ensure_signed(origin)?;
+            Self::ensure_contract_owned(sender, &contract_address)?;
+
+            <ContractWhiteListEnabled<T>>::insert(contract_address, enable);
+            Ok(())
+        }
+        
+        /// Add an address to smart contract white list.
+        /// 
+        /// # Permissions
+        /// 
+        /// * Address that deployed smart contract.
+        /// 
+        /// # Arguments
+        /// 
+        /// -`contract_address`: Address of the contract.
+        ///
+        /// -`account_address`: Address to add.
+        #[weight = 0]
+        pub fn add_to_contract_white_list(
+            origin,
+            contract_address: T::AccountId,
+            account_address: T::AccountId
+        ) -> DispatchResult {
+            let sender = ensure_signed(origin)?;
+            Self::ensure_contract_owned(sender, &contract_address)?;
+            
+            <ContractWhiteList<T>>::insert(contract_address, account_address, true);
+            Ok(())
+        }
+
+        /// Remove an address from smart contract white list.
+        /// 
+        /// # Permissions
+        /// 
+        /// * Address that deployed smart contract.
+        /// 
+        /// # Arguments
+        /// 
+        /// -`contract_address`: Address of the contract.
+        ///
+        /// -`account_address`: Address to remove.
         #[weight = 0]
+        pub fn remove_from_contract_white_list(
+            origin,
+            contract_address: T::AccountId,
+            account_address: T::AccountId
+        ) -> DispatchResult {
+            let sender = ensure_signed(origin)?;
+            Self::ensure_contract_owned(sender, &contract_address)?;
+            
+            <ContractWhiteList<T>>::remove(contract_address, account_address);
+            Ok(())
+        }
+
+        #[weight = 0]
         pub fn set_collection_limits(
             origin,
             collection_id: u32,
@@ -1778,9 +1823,7 @@
 
     fn check_white_list(collection_id: CollectionId, address: &T::AccountId) -> DispatchResult {
         let mes = Error::<T>::AddresNotInWhiteList;
-        ensure!(<WhiteList<T>>::contains_key(collection_id), mes);
-        let wl = <WhiteList<T>>::get(collection_id);
-        ensure!(wl.contains(address), mes);
+        ensure!(<WhiteList<T>>::contains_key(collection_id, address), mes);
 
         Ok(())
     }
@@ -2138,6 +2181,17 @@
 
         Ok(())
     }
+    
+    fn ensure_contract_owned(account: T::AccountId, contract: &T::AccountId) -> DispatchResult {
+        if <ContractOwner<T>>::contains_key(contract.clone()) {
+            let owner = <ContractOwner<T>>::get(contract);
+            ensure!(account == owner, Error::<T>::NoPermission);
+        } else {
+            fail!(Error::<T>::NoPermission);
+        }
+
+        Ok(())
+    }
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -2357,6 +2411,16 @@
 
                 let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());
 
+                let owned_contract = <ContractOwner<T>>::contains_key(called_contract.clone())
+                  && <ContractOwner<T>>::get(called_contract.clone()) == *who;
+                let white_list_enabled = <ContractWhiteListEnabled<T>>::contains_key(called_contract.clone()) && <ContractWhiteListEnabled<T>>::get(called_contract.clone());
+                  
+                if !owned_contract && white_list_enabled {
+                    if !<ContractWhiteList<T>>::contains_key(called_contract.clone(), who) {
+                        return Err(InvalidTransaction::Call.into());
+                    }
+                }
+
                 let mut sponsor_transfer = false;
                 if <ContractSponsoringRateLimit<T>>::contains_key(called_contract.clone()) {
                     let last_tx_block = <ContractSponsorBasket<T>>::get((&called_contract, &who));
modifiedpallets/nft/src/tests.rsdiffbeforeafterboth
--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -960,7 +960,7 @@
 
         let origin1 = Origin::signed(1);
         assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));
-        assert_eq!(TemplateModule::white_list(collection_id)[0], 2);
+        assert_eq!(TemplateModule::white_list(collection_id, 2), true);
     });
 }
 
@@ -975,7 +975,7 @@
 
         assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));
         assert_ok!(TemplateModule::add_to_white_list(origin2.clone(), collection_id, 3));
-        assert_eq!(TemplateModule::white_list(collection_id)[0], 3);
+        assert_eq!(TemplateModule::white_list(collection_id, 3), true);
     });
 }
 
@@ -1035,8 +1035,7 @@
         
         assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));
         assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));
-        assert_eq!(TemplateModule::white_list(collection_id)[0], 2);
-        assert_eq!(TemplateModule::white_list(collection_id).len(), 1);
+        assert_eq!(TemplateModule::white_list(collection_id, 2), true);
     });
 }
 
@@ -1054,7 +1053,7 @@
             collection_id,
             2
         ));
-        assert_eq!(TemplateModule::white_list(collection_id).len(), 0);
+        assert_eq!(TemplateModule::white_list(collection_id, 2), false);
     });
 }
 
@@ -1075,7 +1074,7 @@
             collection_id,
             3
         ));
-        assert_eq!(TemplateModule::white_list(collection_id).len(), 0);
+        assert_eq!(TemplateModule::white_list(collection_id, 3), false);
     });
 }
 
@@ -1093,7 +1092,7 @@
             TemplateModule::remove_from_white_list(origin2.clone(), collection_id, 2),
             Error::<Test>::NoPermission
         );
-        assert_eq!(TemplateModule::white_list(collection_id)[0], 2);
+        assert_eq!(TemplateModule::white_list(collection_id, 2), true);
     });
 }
 
@@ -1125,7 +1124,7 @@
             TemplateModule::remove_from_white_list(origin2.clone(), collection_id, 2),
             Error::<Test>::CollectionNotFound
         );
-        assert_eq!(TemplateModule::white_list(collection_id).len(), 0);
+        assert_eq!(TemplateModule::white_list(collection_id, 2), false);
     });
 }
 
@@ -1149,7 +1148,7 @@
             collection_id,
             2
         ));
-        assert_eq!(TemplateModule::white_list(collection_id).len(), 0);
+        assert_eq!(TemplateModule::white_list(collection_id, 2), false);
     });
 }
 
modifiedtests/src/contracts.test.tsdiffbeforeafterboth
before · tests/src/contracts.test.ts
1//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";7import { expect } from "chai";8import { default as usingApi, submitTransactionAsync } from "./substrate/substrate-api";9import fs from "fs";10import { Abi, BlueprintPromise, CodePromise } from "@polkadot/api-contract";11import { IKeyringPair } from "@polkadot/types/types";12import { Keyring } from "@polkadot/api";13import { ApiTypes, SubmittableExtrinsic } from "@polkadot/api/types";14import { BigNumber } from 'bignumber.js';15import { findUnusedAddress } from './util/helpers'1617const value = 0;18const gasLimit = 3000n * 1000000n;19const endowment = `1000000000000000`;2021function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<BlueprintPromise> {22  return new Promise<BlueprintPromise>(async (resolve, reject) => {23    const unsub = await code24      .createBlueprint()25      .signAndSend(alice, (result) => {26        if (result.status.isInBlock || result.status.isFinalized) {27          // here we have an additional field in the result, containing the blueprint28          resolve(result.blueprint);29          unsub();30        }31      })32  });33}3435function deployContract(alice: IKeyringPair, blueprint: BlueprintPromise) : Promise<any> {36  return new Promise<any>(async (resolve, reject) => {37    const initValue = true;3839    const unsub = await blueprint.tx40    .new(endowment, gasLimit, initValue)41    .signAndSend(alice, (result) => {42      if (result.status.isInBlock || result.status.isFinalized) {43        unsub();44        resolve(result);45      }46    });    47  });48}4950async function prepareDeployer(api: ApiPromise) {51  // Find unused address52  const deployer = await findUnusedAddress(api);5354  // Transfer balance to it55  const keyring = new Keyring({ type: 'sr25519' });56  const alice = keyring.addFromUri(`//Alice`);57  let amount = new BigNumber(endowment);58  amount = amount.plus(1e15);59  const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());60  await submitTransactionAsync(alice, tx);6162  return deployer;63}6465describe('Contracts smoke test', () => {66  it(`Can deploy smart contract Flipper, instantiate it and call it's get and flip messages.`, async () => {67    await usingApi(async api => {68      const deployer = await prepareDeployer(api);69      70      const wasm = fs.readFileSync('./src/flipper/flipper.wasm');71      72      const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));73      const abi = new Abi(metadata);7475      const code = new CodePromise(api, abi, wasm);7677      const blueprint = await deployBlueprint(deployer, code);78      const contract = (await deployContract(deployer, blueprint))['contract'];7980      const getFlipValue = async () => {81        const result = await contract.query.get(deployer.address, value, gasLimit);8283        if(!result.result.isSuccess) {84          throw `Failed to get flipper value`;85        }86        return (result.result.asSuccess.data[0] == 0x00) ? false : true;87      }8889      const initialGetResponse = await getFlipValue();90      expect(initialGetResponse).to.be.true;9192      const flip = contract.exec('flip', value, gasLimit);93      await submitTransactionAsync(deployer, flip);9495      const afterFlipGetResponse = await getFlipValue();9697      expect(afterFlipGetResponse).to.be.false;98    });99  });100101  it.skip('Can transfer balance using smart contract.', async () => {102    await usingApi(async api => {103      // const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);104      // const wasm = fs.readFileSync('./src/balance-transfer-contract/calls.wasm');105      // const contract = compactAddLength(u8aToU8a(wasm));106107      // const metadata = JSON.parse(fs.readFileSync('./src/balance-transfer-contract/metadata.json').toString('utf-8'));108      // const abi = new Abi(api.registry as any, metadata);109110      // const alicesPrivateKey = privateKey('//Alice');111112      // const contractHash = await deployContract(api, contract, alicesPrivateKey);113114      // // const args = abi.constructors[0]();115      // const instanceAccountId = await instantiateContract(api, contractHash, /*args,*/ alicesPrivateKey);116      // const contractInstance = new ContractPromise(api, abi, instanceAccountId);117      // const bob = new GenericAccountId(api.registry, bobsPublicKey);118119      // const transfer = contractInstance.exec('balance_transfer', 0, 1000000000000n, [bob, new u128(api.registry, 1000000)]);120      // await submitTransactionAsync(alicesPrivateKey, transfer);121122      // const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);123124      // expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;125      // expect(bobsBalanceAfter > bobsBalanceBefore).to.be.true;126    });127  })128});
after · tests/src/contracts.test.ts
1import chai from "chai";2import chaiAsPromised from 'chai-as-promised';3import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";4import fs from "fs";5import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";6import { IKeyringPair } from "@polkadot/types/types";7import { ApiPromise, Keyring } from "@polkadot/api";8import { ApiTypes, SubmittableExtrinsic } from "@polkadot/api/types";9import privateKey from "./substrate/privateKey";1011chai.use(chaiAsPromised);12const expect = chai.expect;13import { BigNumber } from 'bignumber.js';14import { findUnusedAddress } from './util/helpers'1516const value = 0;17const gasLimit = 3000n * 1000000n;18const endowment = `1000000000000000`;1920function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {21  return new Promise<Blueprint>(async (resolve, reject) => {22    const unsub = await code23      .createBlueprint()24      .signAndSend(alice, (result) => {25        if (result.status.isInBlock || result.status.isFinalized) {26          // here we have an additional field in the result, containing the blueprint27          resolve(result.blueprint);28          unsub();29        }30      })31  });32}3334function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {35  return new Promise<any>(async (resolve, reject) => {36    const initValue = true;3738    const unsub = await blueprint.tx39    .new(endowment, gasLimit, initValue)40    .signAndSend(alice, (result) => {41      if (result.status.isInBlock || result.status.isFinalized) {42        unsub();43        resolve(result);44      }45    });    46  });47}4849async function prepareDeployer(api: ApiPromise) {50  // Find unused address51  const deployer = await findUnusedAddress(api);5253  // Transfer balance to it54  const keyring = new Keyring({ type: 'sr25519' });55  const alice = keyring.addFromUri(`//Alice`);56  let amount = new BigNumber(endowment);57  amount = amount.plus(1e15);58  const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());59  await submitTransactionAsync(alice, tx);6061  return deployer;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}9192describe('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  });106107  it(`Whitelisted account can call contract.`, async () => {108    await usingApi(async api => {109      const bob = privateKey("//Bob");110      111      const [contract, deployer] = await deployFlipper(api);112      const consoleError = console.error;113      console.error = (...data: any[]) => {114      };115116      let expectedFlipValue = await getFlipValue(contract, deployer);117118      const flip = contract.exec('flip', value, gasLimit);119      await submitTransactionAsync(bob, flip);120      expectedFlipValue = !expectedFlipValue;121      const afterFlip = await getFlipValue(contract,deployer);122      expect(afterFlip).to.be.eq(expectedFlipValue, `Anyone can call new contract.`);123124      const deployerCanFlip = async () => {125        expectedFlipValue = !expectedFlipValue;126        const deployerFlip = contract.exec('flip', value, gasLimit);127        await submitTransactionAsync(deployer, deployerFlip);128        const aliceFlip1Response = await getFlipValue(contract, deployer);129        expect(aliceFlip1Response).to.be.eq(expectedFlipValue, `Deployer always can flip.`);130      };131      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;137      const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);138      expect(flipValueAfterEnableWhiteList).to.be.eq(expectedFlipValue, `Enabling whitelist doesn't make it possible to call contract for everyone.`);139140      await deployerCanFlip();141142      const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);143      const addBobResult = await submitTransactionAsync(deployer, addBobToWhiteListTx);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);153      const removeBobResult = await submitTransactionAsync(deployer, removeBobFromWhiteListTx);154      const bobRemoved = contract.exec('flip', value, gasLimit);155      await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;156      const afterBobRemoved = await getFlipValue(contract, deployer);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;170    });171  });172173  it.skip('Can transfer balance using smart contract.', async () => {174    await usingApi(async api => {175      // const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);176      // const wasm = fs.readFileSync('./src/balance-transfer-contract/calls.wasm');177      // const contract = compactAddLength(u8aToU8a(wasm));178179      // const metadata = JSON.parse(fs.readFileSync('./src/balance-transfer-contract/metadata.json').toString('utf-8'));180      // const abi = new Abi(api.registry as any, metadata);181182      // const alicesPrivateKey = privateKey('//Alice');183184      // const contractHash = await deployContract(api, contract, alicesPrivateKey);185186      // // const args = abi.constructors[0]();187      // const instanceAccountId = await instantiateContract(api, contractHash, /*args,*/ alicesPrivateKey);188      // const contractInstance = new ContractPromise(api, abi, instanceAccountId);189      // const bob = new GenericAccountId(api.registry, bobsPublicKey);190191      // const transfer = contractInstance.exec('balance_transfer', 0, 1000000000000n, [bob, new u128(api.registry, 1000000)]);192      // await submitTransactionAsync(alicesPrivateKey, transfer);193194      // const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);195196      // expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;197      // expect(bobsBalanceAfter > bobsBalanceBefore).to.be.true;198    });199  })200});
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -56,3 +56,25 @@
     }
   });
 }
+
+export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {
+  return new Promise(async function(resolve, reject) {
+    try {
+      await transaction.signAndSend(sender, ({ events = [], status }) => {
+        if (status.isReady) {
+          // nothing to do
+          // console.log(`Current tx status is Ready`);
+        } else if (status.isBroadcast) {
+          // nothing to do
+          // console.log(`Current tx status is Broadcast`);
+        } else if (status.isInBlock || status.isFinalized) {
+          resolve(events);
+        } else {
+          reject("Transaction failed");
+        }
+      });
+    } catch (e) {
+      reject(e);
+    }
+  });
+}
\ No newline at end of file