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`;19const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';2021function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {22 return new Promise<Blueprint>(async (resolve, reject) => {23 const unsub = await code24 .createBlueprint()25 .signAndSend(alice, (result) => {26 if (result.status.isInBlock || result.status.isFinalized) {27 28 resolve(result.blueprint);29 unsub();30 }31 })32 });33}3435function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {36 return new Promise<any>(async (resolve, reject) => {37 const endowment = 1000000000000000n;38 const initValue = true;3940 const unsub = await blueprint.tx41 .new(endowment, gasLimit, initValue)42 .signAndSend(alice, (result) => {43 if (result.status.isInBlock || result.status.isFinalized) {44 unsub();45 resolve(result);46 }47 }); 48 });49}5051async function prepareDeployer(api: ApiPromise) {52 53 const deployer = await findUnusedAddress(api);5455 56 const keyring = new Keyring({ type: 'sr25519' });57 const alice = keyring.addFromUri(`//Alice`);58 let amount = new BigNumber(endowment);59 amount = amount.plus(1e15);60 const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());61 await submitTransactionAsync(alice, tx);6263 return deployer;64}6566export async function deployFlipper(api: ApiPromise): Promise<[Contract, IKeyringPair]> {67 const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));68 const abi = new Abi(metadata);6970 const deployer = await prepareDeployer(api);7172 const wasm = fs.readFileSync('./src/flipper/flipper.wasm');7374 const code = new CodePromise(api, abi, wasm);7576 const blueprint = await deployBlueprint(deployer, code);77 const contract = (await deployContract(deployer, blueprint))['contract'] as Contract;7879 const initialGetResponse = await getFlipValue(contract, deployer);80 expect(initialGetResponse).to.be.true;8182 return [contract, deployer];83}8485async function getFlipValue(contract: Contract, deployer: IKeyringPair) {86 const result = await contract.query.get(deployer.address, value, gasLimit);8788 if(!result.result.isSuccess) {89 throw `Failed to get flipper value`;90 }91 return (result.result.asSuccess.data[0] == 0x00) ? false : true;92}9394describe('Contracts', () => {95 it(`Can deploy smart contract Flipper, instantiate it and call it's get and flip messages.`, async () => {96 await usingApi(async api => {97 const [contract, deployer] = await deployFlipper(api);98 const initialGetResponse = await getFlipValue(contract, deployer);99100 const bob = privateKey("//Bob");101 const flip = contract.exec('flip', value, gasLimit);102 await submitTransactionAsync(bob, flip);103104 const afterFlipGetResponse = await getFlipValue(contract, deployer);105 expect(afterFlipGetResponse).not.to.be.eq(initialGetResponse, 'Flipping should change value.');106 });107 });108109 it(`Whitelisted account can call contract.`, async () => {110 await usingApi(async api => {111 const bob = privateKey("//Bob");112113 const [contract, deployer] = await deployFlipper(api);114 const consoleError = console.error;115 console.error = (...data: any[]) => {116 };117118 let expectedFlipValue = await getFlipValue(contract, deployer);119120 const flip = contract.exec('flip', value, gasLimit);121 await submitTransactionAsync(bob, flip);122 expectedFlipValue = !expectedFlipValue;123 const afterFlip = await getFlipValue(contract,deployer);124 expect(afterFlip).to.be.eq(expectedFlipValue, `Anyone can call new contract.`);125126 const deployerCanFlip = async () => {127 expectedFlipValue = !expectedFlipValue;128 const deployerFlip = contract.exec('flip', value, gasLimit);129 await submitTransactionAsync(deployer, deployerFlip);130 const aliceFlip1Response = await getFlipValue(contract, deployer);131 expect(aliceFlip1Response).to.be.eq(expectedFlipValue, `Deployer always can flip.`);132 };133 await deployerCanFlip();134135 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);136 const enableResult = await submitTransactionAsync(deployer, enableWhiteListTx);137 const flipWithEnabledWhiteList = contract.exec('flip', value, gasLimit);138 await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledWhiteList)).to.be.rejected;139 const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);140 expect(flipValueAfterEnableWhiteList).to.be.eq(expectedFlipValue, `Enabling whitelist doesn't make it possible to call contract for everyone.`);141142 await deployerCanFlip();143144 const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);145 const addBobResult = await submitTransactionAsync(deployer, addBobToWhiteListTx);146 const flipWithWhitelistedBob = contract.exec('flip', value, gasLimit);147 await submitTransactionAsync(bob, flipWithWhitelistedBob);148 expectedFlipValue = !expectedFlipValue;149 const flipAfterWhiteListed = await getFlipValue(contract,deployer);150 expect(flipAfterWhiteListed).to.be.eq(expectedFlipValue, `Bob was whitelisted, now he can flip.`);151152 await deployerCanFlip();153154 const removeBobFromWhiteListTx = api.tx.nft.removeFromContractWhiteList(contract.address, bob.address);155 const removeBobResult = await submitTransactionAsync(deployer, removeBobFromWhiteListTx);156 const bobRemoved = contract.exec('flip', value, gasLimit);157 await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;158 const afterBobRemoved = await getFlipValue(contract, deployer);159 expect(afterBobRemoved).to.be.eq(expectedFlipValue, `Bob can't call contract, now when he is removeed from white list.`);160161 await deployerCanFlip();162163 const disableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, false);164 const disableWhiteListResult = await submitTransactionAsync(deployer, disableWhiteListTx);165 const whiteListDisabledFlip = contract.exec('flip', value, gasLimit);166 await submitTransactionAsync(bob, whiteListDisabledFlip);167 expectedFlipValue = !expectedFlipValue;168 const afterWhiteListDisabled = await getFlipValue(contract,deployer);169 expect(afterWhiteListDisabled).to.be.eq(expectedFlipValue, `Anyone can call contract with disabled whitelist.`);170171 console.error = consoleError;172 });173 });174175 it('Can initialize contract instance', async () => {176 await usingApi(async (api) => {177 const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));178 const abi = new Abi(metadata);179 const newContractInstance = new Contract(api, abi, marketContractAddress);180 expect(newContractInstance).to.have.property('address');181 expect(newContractInstance.address.toString()).to.equal(marketContractAddress);182 });183 });184185 it.skip('Can transfer balance using smart contract.', async () => {186 await usingApi(async api => {187 188 189 190191 192 193194 195196 197198 199 200 201 202203 204 205206 207208 209 210 });211 });212});