git.delta.rocks / unique-network / refs/commits / 9eaef92b0444

difftreelog

test make eth tests pass

Yaroslav Bolyukin2021-07-27parent: #1cfdc4e.patch.diff
in: master

5 files changed

modifiedtests/src/eth/allowlist.test.tsdiffbeforeafterboth
--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -1,6 +1,5 @@
 import { expect } from 'chai';
 import waitNewBlocks from '../substrate/wait-new-blocks';
-import { setContractSponsoringRateLimitExpectFailure } from '../util/helpers';
 import { contractHelpers, createEthAccount, createEthAccountWithBalance, deployFlipper, itWeb3, usingWeb3Http } from './util/helpers';
 
 describe('EVM allowlist', () => {
modifiedtests/src/eth/fungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -9,7 +9,7 @@
 import fungibleAbi from './fungibleAbi.json';
 import { expect } from 'chai';
 
-describe('Information getting', () => {
+describe('Fungible: Information getting', () => {
   itWeb3('totalSupply', async ({ api, web3 }) => {
     const collection = await createCollectionExpectSuccess({
       name: 'token name',
@@ -22,8 +22,8 @@
     await createFungibleItemExpectSuccess(alice, collection, { Value: 200n }, { substrate: alice.address });
 
     const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address);
-    const totalSupply = await contract.methods.totalSupply().call({ from: caller, ...GAS_ARGS });
+    const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    const totalSupply = await contract.methods.totalSupply().call();
 
     // FIXME: always equals to 0, because this method is not implemented
     expect(totalSupply).to.equal('0');
@@ -41,14 +41,14 @@
     await createFungibleItemExpectSuccess(alice, collection, { Value: 200n }, { ethereum: caller });
 
     const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address);
-    const balance = await contract.methods.balanceOf(caller).call({ from: caller, ...GAS_ARGS });
+    const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    const balance = await contract.methods.balanceOf(caller).call();
 
     expect(balance).to.equal('200');
   });
 });
 
-describe('Plain calls', () => {
+describe('Fungible: Plain calls', () => {
   itWeb3('Can perform approve()', async ({ web3, api }) => {
     const collection = await createCollectionExpectSuccess({
       name: 'token name',
@@ -192,7 +192,7 @@
   });
 });
 
-describe('Substrate calls', () => {
+describe('Fungible: Substrate calls', () => {
   itWeb3('Events emitted for approve()', async ({ web3 }) => {
     const collection = await createCollectionExpectSuccess({
       mode: { type: 'Fungible', decimalPoints: 0 },
modifiedtests/src/eth/metadata.test.tsdiffbeforeafterboth
--- a/tests/src/eth/metadata.test.ts
+++ b/tests/src/eth/metadata.test.ts
@@ -4,9 +4,8 @@
 //
 
 import { expect } from 'chai';
-import privateKey from '../substrate/privateKey';
 import { createCollectionExpectSuccess } from '../util/helpers';
-import { collectionIdToAddress, createEthAccount, itWeb3, transferBalanceToEth } from './util/helpers';
+import { collectionIdToAddress, createEthAccountWithBalance, GAS_ARGS, itWeb3 } from './util/helpers';
 import fungibleMetadataAbi from './fungibleMetadataAbi.json';
 
 describe('Common metadata', () => {
@@ -15,12 +14,11 @@
       name: 'token name',
       mode: { type: 'NFT' },
     });
-    const caller = createEthAccount(web3);
-    await transferBalanceToEth(api, privateKey('//Alice'), caller, 999999);
+    const caller = await createEthAccountWithBalance(api, web3);
 
     const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleMetadataAbi as any, address);
-    const name = await contract.methods.name().call({ from: caller });
+    const contract = new web3.eth.Contract(fungibleMetadataAbi as any, address, { from: caller, ...GAS_ARGS });
+    const name = await contract.methods.name().call();
 
     expect(name).to.equal('token name');
   });
@@ -30,12 +28,11 @@
       tokenPrefix: 'TOK',
       mode: { type: 'NFT' },
     });
-    const caller = createEthAccount(web3);
-    await transferBalanceToEth(api, privateKey('//Alice'), caller, 999999);
+    const caller = await createEthAccountWithBalance(api, web3);
 
     const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleMetadataAbi as any, address);
-    const symbol = await contract.methods.symbol().call({ from: caller });
+    const contract = new web3.eth.Contract(fungibleMetadataAbi as any, address, { from: caller, ...GAS_ARGS });
+    const symbol = await contract.methods.symbol().call();
 
     expect(symbol).to.equal('TOK');
   });
@@ -46,12 +43,11 @@
     const collection = await createCollectionExpectSuccess({
       mode: { type: 'Fungible', decimalPoints: 6 },
     });
-    const caller = createEthAccount(web3);
-    await transferBalanceToEth(api, privateKey('//Alice'), caller, 999999);
+    const caller = await createEthAccountWithBalance(api, web3);
 
     const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleMetadataAbi as any, address);
-    const decimals = await contract.methods.decimals().call({ from: caller });
+    const contract = new web3.eth.Contract(fungibleMetadataAbi as any, address, { from: caller, ...GAS_ARGS });
+    const decimals = await contract.methods.decimals().call();
 
     expect(+decimals).to.equal(6);
   });
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -5,63 +5,65 @@
 
 import privateKey from '../substrate/privateKey';
 import { approveExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess } from '../util/helpers';
-import { collectionIdToAddress, createEthAccount, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from './util/helpers';
+import { collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from './util/helpers';
 import nonFungibleAbi from './nonFungibleAbi.json';
 import { expect } from 'chai';
+import waitNewBlocks from '../substrate/wait-new-blocks';
 
-describe('Information getting', () => {
-  itWeb3('totalSupply', async ({ web3 }) => {
+describe('NFT: Information getting', () => {
+  itWeb3('totalSupply', async ({ api, web3 }) => {
     const collection = await createCollectionExpectSuccess({
       mode: { type: 'NFT' },
     });
     const alice = privateKey('//Alice');
+    const caller = await createEthAccountWithBalance(api, web3);
 
     await createItemExpectSuccess(alice, collection, 'NFT', { substrate: alice.address });
 
     const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
     const totalSupply = await contract.methods.totalSupply().call();
 
     // FIXME: always equals to 0, because this method is not implemented
     expect(totalSupply).to.equal('0');
   });
 
-  itWeb3('balanceOf', async ({ web3 }) => {
+  itWeb3('balanceOf', async ({ api, web3 }) => {
     const collection = await createCollectionExpectSuccess({
       mode: { type: 'NFT' },
     });
     const alice = privateKey('//Alice');
 
-    const caller = createEthAccount(web3);
+    const caller = await createEthAccountWithBalance(api, web3);
     await createItemExpectSuccess(alice, collection, 'NFT', { ethereum: caller });
     await createItemExpectSuccess(alice, collection, 'NFT', { ethereum: caller });
     await createItemExpectSuccess(alice, collection, 'NFT', { ethereum: caller });
 
     const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
     const balance = await contract.methods.balanceOf(caller).call();
 
     expect(balance).to.equal('3');
   });
 
-  itWeb3('ownerOf', async ({ web3 }) => {
+  itWeb3('ownerOf', async ({ api, web3 }) => {
     const collection = await createCollectionExpectSuccess({
       mode: { type: 'NFT' },
     });
     const alice = privateKey('//Alice');
 
-    const caller = createEthAccount(web3);
+    const caller = await createEthAccountWithBalance(api, web3);
     const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', { ethereum: caller });
 
     const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
     const owner = await contract.methods.ownerOf(tokenId).call();
 
     expect(owner).to.equal(caller);
   });
 });
 
-describe('Plain calls', () => {
+describe('NFT: Plain calls', () => {
   itWeb3('Can perform approve()', async ({ web3, api }) => {
     const collection = await createCollectionExpectSuccess({
       mode: { type: 'NFT' },
@@ -113,12 +115,12 @@
     const receiver = createEthAccount(web3);
 
     const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});
 
-    await contract.methods.approve(spender, tokenId).send({ from: owner, gas: '0x1000000', gasPrice: '0x01' });
+    await contract.methods.approve(spender, tokenId).send({ from: owner });
 
     {
-      const result = await contract.methods.transferFrom(owner, receiver, tokenId).send({ from: spender, gas: '0x1000000', gasPrice: '0x01' });
+      const result = await contract.methods.transferFrom(owner, receiver, tokenId).send({ from: spender });
       const events = normalizeEvents(result.events);
       expect(events).to.be.deep.equal([
         {
@@ -159,11 +161,11 @@
     await transferBalanceToEth(api, alice, receiver, 999999999999999);
 
     const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});
 
     {
-      const result = await contract.methods.transfer(receiver, tokenId).send({ from: owner, gas: '0x1000000', gasPrice: '0x01' });
-      console.log(result);
+      const result = await contract.methods.transfer(receiver, tokenId).send({ from: owner });
+      await waitNewBlocks(api, 1);
       const events = normalizeEvents(result.events);
       expect(events).to.be.deep.equal([
         {
@@ -190,7 +192,7 @@
   });
 });
 
-describe('Substrate calls', () => {
+describe('NFT: Substrate calls', () => {
   itWeb3('Events emitted for approve()', async ({ web3 }) => {
     const collection = await createCollectionExpectSuccess({
       mode: { type: 'NFT' },
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
before · tests/src/substrate/substrate-api.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 { WsProvider, ApiPromise } from '@polkadot/api';7import { EventRecord } from '@polkadot/types/interfaces/system/types';8import { ExtrinsicStatus } from '@polkadot/types/interfaces/author/types';9import { IKeyringPair } from '@polkadot/types/types';1011import config from '../config';12import promisifySubstrate from './promisify-substrate';13import { ApiOptions, SubmittableExtrinsic, ApiTypes } from '@polkadot/api/types';14import rtt from '../../../runtime_types.json';1516function defaultApiOptions(): ApiOptions {17  const wsProvider = new WsProvider(config.substrateUrl);18  return {19    provider: wsProvider, types: rtt, signedExtensions: {20      ContractHelpers: {21        extrinsic: {},22        payload: {},23      },24    },25  };26}2728export default async function usingApi<T = void>(action: (api: ApiPromise) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {29  settings = settings || defaultApiOptions();30  const api: ApiPromise = new ApiPromise(settings);31  let result: T = null as unknown as T;3233  // TODO: Remove, this is temporary: Filter unneeded API output 34  // (Jaco promised it will be removed in the next version)35  const consoleErr = console.error;36  const consoleLog = console.log;37  const consoleWarn = console.warn;3839  const outFn = (message: string) => {40    if (!message.includes('StorageChangeSet:: WebSocket is not connected') && 41        !message.includes('2021-') &&42        !message.includes('StorageChangeSet:: Normal connection closure'))43      consoleErr(message);44  };4546  console.error = outFn;47  console.log = outFn;48  console.warn = outFn;4950  try {51    await promisifySubstrate(api, async () => {52      if (api) {53        await api.isReadyOrError;54        result = await action(api);55      }56    })();57  } finally {58    await api.disconnect();59    console.error = consoleErr;60    console.log = consoleLog;61    console.warn = consoleWarn;62  }63  return result as T;64}6566enum TransactionStatus {67  Success,68  Fail,69  NotReady70}7172function getTransactionStatus(events: EventRecord[], status: ExtrinsicStatus): TransactionStatus {73  if (status.isReady) {74    return TransactionStatus.NotReady;75  }76  if (status.isBroadcast) {77    return TransactionStatus.NotReady;78  } 79  if (status.isInBlock || status.isFinalized) {80    if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {81      return TransactionStatus.Fail;82    }83    if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {84      return TransactionStatus.Success;85    }86  }8788  return TransactionStatus.Fail;89}9091export function92submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {93  /* eslint no-async-promise-executor: "off" */94  return new Promise(async (resolve, reject) => {95    try {96      await transaction.signAndSend(sender, ({ events = [], status }) => {97        const transactionStatus = getTransactionStatus(events, status);9899        if (transactionStatus === TransactionStatus.Success) {100          resolve(events);101        } else if (transactionStatus === TransactionStatus.Fail) {102          console.log(`Something went wrong with transaction. Status: ${status}`);103          reject(events);104        }105      });106    } catch (e) {107      console.log('Error: ', e);108      reject(e);109    }110  });111}112113export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {114  const consoleError = console.error;115  const consoleLog = console.log;116  console.error = () => {};117  console.log = () => {};118119  /* eslint no-async-promise-executor: "off" */120  return new Promise<EventRecord[]>(async function(res, rej) {121    const resolve = (rec: EventRecord[]) => {122      setTimeout(() => {123        res(rec);124        console.error = consoleError;125        console.log = consoleLog;126      });127    };128    const reject = (errror: any) => {129      setTimeout(() => {130        rej(errror);131        console.error = consoleError;132        console.log = consoleLog;133      });134    };135    try {136      await transaction.signAndSend(sender, ({ events = [], status }) => {137        const transactionStatus = getTransactionStatus(events, status);138139        // console.log('transactionStatus', transactionStatus, 'events', events);140141        if (transactionStatus === TransactionStatus.Success) {142          resolve(events);143        } else if (transactionStatus === TransactionStatus.Fail) {144          reject(events);145        }146      });147    } catch (e) {148      reject(e);149    }150  });151}
after · tests/src/substrate/substrate-api.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 { WsProvider, ApiPromise } from '@polkadot/api';7import { EventRecord } from '@polkadot/types/interfaces/system/types';8import { ExtrinsicStatus } from '@polkadot/types/interfaces/author/types';9import { IKeyringPair } from '@polkadot/types/types';1011import config from '../config';12import promisifySubstrate from './promisify-substrate';13import { ApiOptions, SubmittableExtrinsic, ApiTypes } from '@polkadot/api/types';14import rtt from '../../../runtime_types.json';1516function defaultApiOptions(): ApiOptions {17  const wsProvider = new WsProvider(config.substrateUrl);18  return {19    provider: wsProvider, types: rtt, signedExtensions: {20      ContractHelpers: {21        extrinsic: {},22        payload: {},23      },24    },25  };26}2728export default async function usingApi<T = void>(action: (api: ApiPromise) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {29  settings = settings || defaultApiOptions();30  const api: ApiPromise = new ApiPromise(settings);31  let result: T = null as unknown as T;3233  // TODO: Remove, this is temporary: Filter unneeded API output 34  // (Jaco promised it will be removed in the next version)35  const consoleErr = console.error;36  const consoleLog = console.log;37  const consoleWarn = console.warn;3839  const outFn = (message: string) => {40    if (typeof message !== 'string') {41      consoleErr(message);42      return;43    }44    if (!message.includes('StorageChangeSet:: WebSocket is not connected') && 45        !message.includes('2021-') &&46        !message.includes('StorageChangeSet:: Normal connection closure'))47      consoleErr(message);48  };4950  console.error = outFn;51  console.log = outFn;52  console.warn = outFn;5354  try {55    await promisifySubstrate(api, async () => {56      if (api) {57        await api.isReadyOrError;58        result = await action(api);59      }60    })();61  } finally {62    await api.disconnect();63    console.error = consoleErr;64    console.log = consoleLog;65    console.warn = consoleWarn;66  }67  return result as T;68}6970enum TransactionStatus {71  Success,72  Fail,73  NotReady74}7576function getTransactionStatus(events: EventRecord[], status: ExtrinsicStatus): TransactionStatus {77  if (status.isReady) {78    return TransactionStatus.NotReady;79  }80  if (status.isBroadcast) {81    return TransactionStatus.NotReady;82  } 83  if (status.isInBlock || status.isFinalized) {84    if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {85      return TransactionStatus.Fail;86    }87    if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {88      return TransactionStatus.Success;89    }90  }9192  return TransactionStatus.Fail;93}9495export function96submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {97  /* eslint no-async-promise-executor: "off" */98  return new Promise(async (resolve, reject) => {99    try {100      await transaction.signAndSend(sender, ({ events = [], status }) => {101        const transactionStatus = getTransactionStatus(events, status);102103        if (transactionStatus === TransactionStatus.Success) {104          resolve(events);105        } else if (transactionStatus === TransactionStatus.Fail) {106          console.log(`Something went wrong with transaction. Status: ${status}`);107          reject(events);108        }109      });110    } catch (e) {111      console.log('Error: ', e);112      reject(e);113    }114  });115}116117export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {118  const consoleError = console.error;119  const consoleLog = console.log;120  console.error = () => {};121  console.log = () => {};122123  /* eslint no-async-promise-executor: "off" */124  return new Promise<EventRecord[]>(async function(res, rej) {125    const resolve = (rec: EventRecord[]) => {126      setTimeout(() => {127        res(rec);128        console.error = consoleError;129        console.log = consoleLog;130      });131    };132    const reject = (errror: any) => {133      setTimeout(() => {134        rej(errror);135        console.error = consoleError;136        console.log = consoleLog;137      });138    };139    try {140      await transaction.signAndSend(sender, ({ events = [], status }) => {141        const transactionStatus = getTransactionStatus(events, status);142143        // console.log('transactionStatus', transactionStatus, 'events', events);144145        if (transactionStatus === TransactionStatus.Success) {146          resolve(events);147        } else if (transactionStatus === TransactionStatus.Fail) {148          reject(events);149        }150      });151    } catch (e) {152      reject(e);153    }154  });155}