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 27 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 51 const deployer = await findUnusedAddress(api);5253 54 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 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);9798 const flip = contract.exec('flip', value, gasLimit);99 await submitTransactionAsync(deployer, flip);100101 const afterFlipGetResponse = await getFlipValue(contract, deployer);102 expect(afterFlipGetResponse).not.to.be.eq(initialGetResponse, 'Flipping should change value.');103 });104 });105106 it(`Whitelisted account can call contract.`, async () => {107 await usingApi(async api => {108 const bob = privateKey("//Bob");109 110 const [contract, deployer] = await deployFlipper(api);111 const consoleError = console.error;112 console.error = (...data: any[]) => {113 };114115 let expectedFlipValue = await getFlipValue(contract, deployer);116117 const flip = contract.exec('flip', value, gasLimit);118 await expect(submitTransactionExpectFailAsync(bob, flip)).to.be.rejected;119 const firstFailResponse = await getFlipValue(contract, deployer);120 expect(firstFailResponse).to.be.eq(expectedFlipValue, `Only account who deployed contract can flip value.`);121122 const deployerCanFlip = async () => {123 expectedFlipValue = !expectedFlipValue;124 const deployerFlip = contract.exec('flip', value, gasLimit);125 await submitTransactionAsync(deployer, deployerFlip);126 const aliceFlip1Response = await getFlipValue(contract, deployer);127 expect(aliceFlip1Response).to.be.eq(expectedFlipValue, `Deployer always can flip.`);128 };129 await deployerCanFlip();130131 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;135 const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);136 expect(flipValueAfterEnableWhiteList).to.be.eq(expectedFlipValue, `Enabling whitelist doesn't make it possible to call contract for everyone.`);137138 await deployerCanFlip();139140 const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);141 const addBobResult = await submitTransactionAsync(deployer, addBobToWhiteListTx);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.`);147148 await deployerCanFlip();149150 const disableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, false);151 const disableeResult = await submitTransactionAsync(deployer, disableWhiteListTx);152 const flipWithDisabledWhitelist = contract.exec('flip', value, gasLimit);153 await expect(submitTransactionExpectFailAsync(bob, flipWithDisabledWhitelist)).to.be.rejected;154 const flipWithDisabledWhiteList = await getFlipValue(contract, deployer);155 expect(flipWithDisabledWhiteList).to.be.eq(expectedFlipValue, `Bob can't flip when whitelist is disabled, even tho he is in whitelist.`);156157 await deployerCanFlip();158159 const enableWhiteListOneMoreTimeTx = api.tx.nft.toggleContractWhiteList(contract.address, true);160 const enableOneMoreTimeResult = await submitTransactionAsync(deployer, enableWhiteListOneMoreTimeTx);161162 await deployerCanFlip();163164 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.`);170171 await deployerCanFlip();172173 const cleanupTx = api.tx.nft.toggleContractWhiteList(contract.address, false);174 const cleanupResult = await submitTransactionAsync(deployer, cleanupTx);175176 console.error = consoleError;177 });178 });179180 it.skip('Can transfer balance using smart contract.', async () => {181 await usingApi(async api => {182 183 184 185186 187 188189 190191 192193 194 195 196 197198 199 200201 202203 204 205 });206 })207});