Convert tests to ts and fix existing (#936)

* Add jest watch option to package.json

* convert promise-alex-spec to ts & add types

* convert ./api tests from JS to TS

* convert ./api tests from JS to TS pt. 2

* More convert tests from JS to TS

* rpc-provider convert tests from js to ts

* rpc-provider tests js => ts

* rpc-provider tests js => ts

* linting issues

* tslint fixes

* 101 => 68 typescript errors

* WIP

* connect() e2e tests

* more fixes

* Fix linting errors of new ERA tests after merge

* test for listeners in connect

* formatting

* getting there...

* re-add skips

* test refactoring & codeclimate fixes

* more fixed tests

* mock.body workaround

* Fixed wrong test description

* ApiPromiseInterface => Api

* ws polyfill / send

* bring back isZero() test

* .then().catch() => .catch()

* Removed leftover body

* Type ProviderInterface => Http

* Fixed polyfill tests

* trailing whitespce

* (mock.body as any)['test_body'] and Balance

* Fix autoconnect in WsProvider

* Fixed part of linting errors in ERA tests

* call unused const unsubscribe

* added ts-ignores for testing private properties/ methods of Provider

* Archive node test

* Fixed linting for ERA tests

* Further changes

* Update packages/rpc-provider/src/ws/polyfill.spec.ts

Co-Authored-By: Amaury Martiny <amaury.martiny@protonmail.com>

* relative paths for imports inside module & reordering of imports pt. 1

* relative paths for imports inside module & reordering of imports pt. 2

* added skip back to e2e transactions

* Fix some more tests in TS (#952)

* Fix some more tests in ts

* Add more constructor

* More typing in ./api

* .skip

* <SubmittableResult>'s

* .catch() -> return()

* Extrinsics tests

* Left TODO's for extrinsic e2e tests

* Workaround for failing Type Extrinsic tests
This commit is contained in:
Stefanie Doll
2019-05-27 17:08:06 +02:00
committed by GitHub
co-authored by Amaury Martiny
parent f50229db0d
commit c01ade86a6
53 changed files with 770 additions and 658 deletions
+3 -1
View File
@@ -10,6 +10,8 @@ import testKeyring from '@polkadot/keyring/testingPairs';
import { IExtrinsic, IMethod } from '@polkadot/types/types';
import { Header } from '@polkadot/types';
import { SubmittableResult } from './';
export default async function test () {
const api = await ApiPromise.create();
const keyring = testKeyring();
@@ -39,7 +41,7 @@ export default async function test () {
const unsub = await api.tx.balances
.transfer(keyring.bob.address(), 12345)
.signAndSend(keyring.alice, ({ status }) => {
.signAndSend(keyring.alice, ({ status }: SubmittableResult) => {
console.log('transfer status:', status.type);
unsub();
+3 -3
View File
@@ -2,12 +2,12 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiPromise } from '@polkadot/api';
import { ApiOptions } from '@polkadot/api/types';
import { Hash, Metadata } from '@polkadot/types';
import Mock from '@polkadot/rpc-provider/mock/index';
import { ApiPromise } from './..';
import { ApiOptions } from './../types';
describe.skip('Metadata queries', () => {
let mock: Mock;
@@ -3,7 +3,6 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { SubscriptionResult } from './types';
import Combinator from './Combinator';
describe('Combinator', () => {
@@ -2,10 +2,13 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import Api from '../../src/promise';
import { Extrinsic, SignedBlock } from '@polkadot/types';
import Api from './../../src/promise';
// To run these tests locally you need to run a Alexander full archive node locally
describe.skip('alex archive queries (local)', () => {
let api;
let api: Api;
beforeEach(() => {
jest.setTimeout(30000);
@@ -23,7 +26,7 @@ describe.skip('alex archive queries (local)', () => {
console.error(JSON.stringify(metadata, null, 2));
const block = await api.rpc.chain.getBlock('0x6f6f9bba0eed8e3ae9446c37eee763f93118b52a315a7b46090453ba6288da1f')
const block = await api.rpc.chain.getBlock('0x6f6f9bba0eed8e3ae9446c37eee763f93118b52a315a7b46090453ba6288da1f');
console.error(block);
@@ -34,25 +37,25 @@ describe.skip('alex archive queries (local)', () => {
// https://github.com/polkadot-js/api/issues/846
it('handles toJSON with no issues', async (done) => {
const signedBlock = await api.rpc.chain.getBlock('0x85c62b581f38cb81c3e443d34392672beb1fb877017fd7237cc87704113259dc');
const failed = signedBlock.block.extrinsics.filter((extrinsic) => {
try {
const json = extrinsic.method.toJSON();
return (
api.rpc.chain.getBlock('0x85c62b581f38cb81c3e443d34392672beb1fb877017fd7237cc87704113259dc', (result: SignedBlock) => {
const failed: Array<Extrinsic> = result.block.extrinsics.filter((extrinsic: Extrinsic) => {
try {
const json = extrinsic.method.toJSON();
console.error(json);
console.error(json);
return false;
} catch (error) {
console.log(extrinsic.method);
console.log(extrinsic.method.keys());
console.error(error);
return true;
}
});
expect(failed).toHaveLength(0);
done();
return false;
} catch (error) {
console.log(extrinsic.method);
console.log(extrinsic.method.keys());
console.error(error);
return true;
}
});
expect(failed).toBeTruthy();
done();
})
);
});
});
@@ -1,94 +0,0 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Hash, Header } from '@polkadot/types';
import Api from '../../src/promise';
import WsProvider from '../../../rpc-provider/src/ws';
const WS_URL = 'wss://poc3-rpc.polkadot.io/';
// const WS_URL = 'wss://substrate-rpc.parity.io/';
describe.skip('alex queries', () => {
let api;
beforeEach(() => {
jest.setTimeout(30000);
});
beforeEach(async () => {
api = await Api.create({
provider: new WsProvider(WS_URL)
});
return api;
});
it('retrieves the list of validators', (done) => {
api.query.staking.validators((res) => {
console.error(res);
console.log('api.query.staking.validators():', res.toJSON());
done();
});
});
it('retrieves a single value', (done) => {
api.query.staking.validators('5DuiZFa184E9iCwbh4WjXYvJ88NHvWJbS8SARY8Ev1YEqrri', (res) => {
console.error(res);
console.log('api.query.staking.validators(id):', res.toJSON());
done();
});
it('Gets the hash of the last finalized header', async (done) => {
api.rpc.chain.getFinalizedHead((head) => {
expect(head instanceof Hash).toBe(true);
done();
});
});
it('Subscribes to the best finalized header on ALEX', async (done) => {
api.rpc.chain.subscribeFinalizedHeads((heads) => {
expect(heads instanceof Header).toBe(true);
done();
});
});
});
it('derives a list of the controllers', (done) => {
api.derive.staking.controllers((res) => {
console.log('api.derive.staking.controllers:', JSON.stringify(res));
done();
});
});
it('makes a query at a latest block (specified)', async () => {
const header = await api.rpc.chain.getHeader();
const events = await api.query.system.events.at(header.hash);
events.forEach(({ event: { data, method, section }, phase, topics }, index) => {
console.error(index, phase.toString(), `: ${section}.${method}`, data.toString(), topics.toString());
});
expect(events.length).not.toEqual(0);
});
it('subscribes to events', (done) => {
api.query.system.events((events) => {
console.error(JSON.stringify(events));
events.forEach(({ event: { data, method, section }, phase, topics }, index) => {
console.error(index, phase.toString(), `: ${section}.${method}`, data.toString(), topics.toString());
});
expect(events).not.toHaveLength(0);
done();
});
});
});
@@ -0,0 +1,92 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import WsProvider from '@polkadot/rpc-provider/ws';
import { EventRecord, Hash, Header, Vector } from '@polkadot/types';
import Api from './../../src/promise';
const WS_URL = 'wss://poc3-rpc.polkadot.io/';
// const WS_URL = 'wss://substrate-rpc.parity.io/';
describe.skip('alex queries', () => {
let api: Api;
beforeEach(() => {
jest.setTimeout(30000);
});
beforeEach(async () => {
api = await Api.create({
provider: new WsProvider(WS_URL)
});
return api;
});
it('retrieves the list of validators', (done) => {
return (
api.query.staking.validators((res) => {
console.error(res);
console.log('api.query.staking.validators():', res.toJSON());
done();
})
);
});
describe('retrieves a single value', () => {
it('retrieves the list of stash validators', (done) => {
return (
api.query.staking.validators('5DuiZFa184E9iCwbh4WjXYvJ88NHvWJbS8SARY8Ev1YEqrri', (res) => {
console.error(res);
console.log('api.query.staking.validators(id):', res.toJSON());
done();
})
);
});
it('Gets the hash of the last finalized header', async (done) => {
return (
api.rpc.chain.getFinalizedHead((head) => {
expect(head instanceof Hash).toBe(true);
done();
})
);
});
it('Subscribes to the best finalized header on ALEX', async (done) => {
return(
api.rpc.chain.subscribeFinalizedHeads((head) => {
expect(head instanceof Header).toBe(true);
done();
})
);
});
});
it('derives a list of the controllers', (done) => {
return (
api.derive.staking.controllers((res) => {
console.log('api.derive.staking.controllers:', JSON.stringify(res));
done();
})
);
});
it('makes a query at a latest block (specified)', async () => {
const header = await api.rpc.chain.getHeader() as Header;
const events = await api.query.system.events.at(header.hash) as Vector<EventRecord>;
expect(events.length).not.toEqual(0);
});
it('subscribes to events', (done) => {
api.query.system.events((events: Array<EventRecord>) => {
expect(events).not.toHaveLength(0);
done();
});
});
});
@@ -5,18 +5,22 @@
import fs from 'fs';
import path from 'path';
import { ContractAbi } from '@polkadot/types';
import { ContractAbi, Address, Hash } from '@polkadot/types';
import { KeyringPair } from '@polkadot/keyring/types';
import testingPairs from '@polkadot/keyring/testingPairs';
import Api from './../../src/promise';
import incrementer from '../data/incrementer.json';
import erc20 from '../data/erc20.json';
import Api from '../../src/promise';
import { SubmittableResult } from './../../src';
describe.skip('e2e contracts', () => {
let address;
let codeHash;
let keyring;
let api;
describe.skip('Promise e2e contracts', () => {
let address: Address;
let codeHash: Hash;
let keyring: {
[index: string]: KeyringPair
};
let api: Api;
beforeEach(async (done) => {
if (!api) {
@@ -30,7 +34,7 @@ describe.skip('e2e contracts', () => {
});
describe('incrementer', () => {
let abi;
let abi: ContractAbi;
beforeEach(() => {
abi = new ContractAbi(incrementer);
@@ -39,60 +43,63 @@ describe.skip('e2e contracts', () => {
it('allows putCode', (done) => {
const code = fs.readFileSync(path.join(__dirname, '../data/incrementer-opt.wasm')).toString('hex');
api.tx.contract
return(
api.tx.contract
.putCode(200000, `0x${code}`)
.signAndSend(keyring.eve, (result) => {
.signAndSend(keyring.eve, (result: SubmittableResult) => {
console.error('putCode', JSON.stringify(result));
if (result.status.isFinalized) {
const record = result.findRecord('contract', 'CodeStored');
if (record) {
codeHash = record.event.data[0];
done();
codeHash = record.event.data[0] as Hash;
}
done();
}
});
})
);
});
it('allows contract create', (done) => {
expect(codeHash).toBeDefined();
api.tx.contract
.create(12345, 500000, codeHash, abi.deploy(12345))
.signAndSend(keyring.bob, (result) => {
console.error('create', JSON.stringify(result));
return (
api.tx.contract
.create(12345, 500000, codeHash, abi.deploy(12345))
.signAndSend(keyring.bob, (result: SubmittableResult) => {
console.error('create', JSON.stringify(result));
if (result.status.isFinalized) {
const record = result.findRecord('contract', 'Instantiated');
if (result.status.isFinalized) {
const record = result.findRecord('contract', 'Instantiated');
if (record) {
address = record.event.data[1] as Address;
if (record) {
address = record.event.data[1];
done();
done();
}
}
}
});
})
);
});
it('allows contract call', (done) => {
expect(address).toBeDefined();
api.tx.contract
.call(address, 12345, 500000, abi.messages.inc(123))
.signAndSend(keyring.bob, (result) => {
console.error('call', JSON.stringify(result));
return (
api.tx.contract
.call(address, 12345, 500000, abi.messages.inc(123))
.signAndSend(keyring.bob, (result: SubmittableResult) => {
console.error('call', JSON.stringify(result));
if (result.status.isFinalized && result.findRecord('system', 'ExtrinsicSuccess')) {
done();
}
});
if (result.status.isFinalized && result.findRecord('system', 'ExtrinsicSuccess')) {
done();
}
})
);
});
});
describe('erc20', () => {
let abi;
let abi: ContractAbi;
beforeEach(() => {
abi = abi = new ContractAbi(erc20);
@@ -1,186 +0,0 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import testingPairs from '@polkadot/keyring/testingPairs';
import { LinkageResult } from '@polkadot/types/codec/Linkage';
import Api from '../../src/promise';
import WsProvider from '../../../rpc-provider/src/ws';
const ZERO = new BN(0);
const WS_URL = 'ws://127.0.0.1:9944';
// const WS_URL = 'wss://poc3-rpc.polkadot.io/';
describe.skip('e2e queries', () => {
const keyring = testingPairs({ type: 'ed25519' });
let api;
beforeEach(async (done) => {
if (!api) {
api = await Api.create({
provider: new WsProvider(WS_URL)
});
}
jest.setTimeout(30000);
done();
});
it('makes the runtime, rpc, state & extrinsics available', () => {
expect(api.genesisHash).toBeDefined();
expect(api.runtimeMetadata).toBeDefined();
expect(api.runtimeVersion).toBeDefined();
expect(api.rpc).toBeDefined();
expect(api.query).toBeDefined();
expect(api.tx).toBeDefined();
expect(api.derive).toBeDefined();
});
it('queries state for a balance', async () => {
const balance = await api.query.balances.freeBalance(keyring.alice.address());
expect(
balance.isZero()
).toBe(false);
});
it('subscribes to rpc', (done) => {
api.rpc.chain.subscribeNewHead((header) => {
expect(header.blockNumber.isZero()).toBe(false);
done();
});
});
it('subscribes to finalized', (done) => {
api.rpc.chain.subscribeFinalizedHeads((header) => {
expect(header.blockNumber.isZero()).toBe(false);
done();
});
});
it('subscribes to derive', (done) => {
api.derive.chain.subscribeNewHead((header) => {
expect(header.blockNumber.isZero()).toBe(false);
done();
});
});
it('subscribes to queries', (done) => {
api.query.system.accountNonce(keyring.ferdie.address(), (nonce) => {
expect(nonce instanceof BN).toBe(true);
done();
});
});
it.skip('subscribes to queries (default)', (done) => {
api.query.staking.validators(keyring.ferdie.address(), (prefs) => {
expect(prefs.unstakeThreshold.toNumber()).toBe(3);
done();
});
});
it('subscribes to a linked map (staking.validators)', (done) => {
api.query.staking.validators((prefs) => {
expect(prefs instanceof LinkageResult).toBe(true);
done();
});
});
it('subscribes to multiple results (freeBalance.multi)', (done) => {
api.query.balances.freeBalance.multi([
keyring.alice.address(),
keyring.bob.address(),
'5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y',
keyring.ferdie.address()
], (balances) => {
console.error(balances);
expect(balances).toHaveLength(4);
done();
});
});
it('subscribes to multiple results (api.queryMulti)', (done) => {
return api.queryMulti([
[api.query.balances.freeBalance, keyring.alice.address()],
[api.query.balances.freeBalance, keyring.bob.address()],
[api.query.balances.freeBalance, '5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y'],
[api.query.balances.freeBalance, keyring.ferdie.address()]
], (balances) => {
console.error(balances);
expect(balances).toHaveLength(4);
done();
});
});
it('subscribes to derived balances (balances.all)', (done) => {
api.derive.balances.all(
keyring.alice.address(),
(all) => {
expect(all.accountId.toString()).toEqual(keyring.alice.address());
expect(all.freeBalance).toBeDefined();
expect(all.freeBalance.gt(ZERO)).toBe(true);
expect(all.availableBalance).toBeDefined();
expect(all.availableBalance.gt(ZERO)).toBe(true);
expect(all.reservedBalance).toBeDefined();
expect(all.lockedBalance).toBeDefined();
expect(all.vestedBalance).toBeDefined();
console.error(all);
done();
}
);
});
it('makes a query at a latest block (specified)', async () => {
const header = await api.rpc.chain.getHeader();
const events = await api.query.system.events.at(header.hash);
events.forEach(({ event: { data, method, section }, phase, topics }, index) => {
console.error(index, phase.toString(), `: ${section}.${method}`, data.toString(), topics.toString());
});
expect(events.length).not.toEqual(0);
});
it('subscribes to events', (done) => {
api.query.system.events((events) => {
events.forEach(({ event: { data, method, section }, phase, topics }, index) => {
console.error(index, phase.toString(), `: ${section}.${method}`, data.toString(), topics.toString());
});
expect(events).not.toHaveLength(0);
done();
});
});
it('queries state using double map key', async () => {
// TODO Update ['any', '0x1234'] to the key of a known event topic and update '[]' to the expected value
const eventTopics = await api.query.system.eventTopics(['any', '0x1234']);
expect(eventTopics.toString()).toEqual('[]');
});
it('subscribes to queries using double map key', async (done) => {
// TODO Update ['any', '0x1234'] to the key of a known event topic and update '[]' to the expected value
api.query.system.eventTopics(['any', '0x1234'], (eventTopics) => {
expect(eventTopics.toString()).toEqual('[]');
done();
});
});
});
@@ -0,0 +1,196 @@
// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import WsProvider from '@polkadot/rpc-provider/ws';
import testingPairs from '@polkadot/keyring/testingPairs';
import { LinkageResult } from '@polkadot/types/codec/Linkage';
import { EventRecord, Header, Vector } from '@polkadot/types';
import Api from './../../src/promise';
const ZERO = new BN(0);
const WS_URL = 'ws://127.0.0.1:9944';
// const WS_URL = 'wss://poc3-rpc.polkadot.io/';
describe.skip('Promise e2e queries', () => {
const keyring = testingPairs({ type: 'ed25519' });
let api: Api;
beforeEach(async (done) => {
if (!api) {
api = await Api.create({
provider: new WsProvider(WS_URL)
});
}
jest.setTimeout(30000);
done();
});
it('makes the runtime, rpc, state & extrinsics available', () => {
expect(api.genesisHash).toBeDefined();
expect(api.runtimeMetadata).toBeDefined();
expect(api.runtimeVersion).toBeDefined();
expect(api.rpc).toBeDefined();
expect(api.query).toBeDefined();
expect(api.tx).toBeDefined();
expect(api.derive).toBeDefined();
});
it('queries state for a balance', async () => {
return(
api.query.balances.freeBalance(keyring.alice.address(), balance => {
expect(balance).toBeInstanceOf(BN);
expect(balance.isZero()).toBe(false);
})
);
});
it('subscribes to rpc', (done) => {
return(
api.rpc.chain.subscribeNewHead((header) => {
expect(header.blockNumber.isZero()).toBe(false);
done();
})
);
});
it('subscribes to finalized', (done) => {
return(
api.rpc.chain.subscribeFinalizedHeads((header) => {
expect(header.blockNumber.isZero()).toBe(false);
done();
})
);
});
it('subscribes to derive', (done) => {
return(
api.derive.chain.subscribeNewHead((header) => {
expect(header.blockNumber.isZero()).toBe(false);
done();
})
);
});
it('subscribes to queries', (done) => {
return(
api.query.system.accountNonce(keyring.ferdie.address(), (nonce) => {
expect(nonce instanceof BN).toBe(true);
done();
})
);
});
it.skip('subscribes to queries (default)', (done) => {
return(
api.query.staking.validators(keyring.ferdie.address(), (prefs) => {
expect(prefs.unstakeThreshold.toNumber()).toBe(3);
done();
})
);
});
it('subscribes to a linked map (staking.validators)', (done) => {
return(
api.query.staking.validators((prefs) => {
expect(prefs instanceof LinkageResult).toBe(true);
done();
})
);
});
it('subscribes to multiple results (freeBalance.multi)', (done) => {
return(
api.query.balances.freeBalance.multi([
keyring.alice.address(),
keyring.bob.address(),
'5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y',
keyring.ferdie.address()
], (balances) => {
expect(balances).toHaveLength(4);
done();
})
);
});
it('subscribes to multiple results (api.queryMulti)', (done) => {
return api.queryMulti([
[api.query.balances.freeBalance, keyring.alice.address()],
[api.query.balances.freeBalance, keyring.bob.address()],
[api.query.balances.freeBalance, '5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y'],
[api.query.balances.freeBalance, keyring.ferdie.address()]
], (balances: Array<BN>) => {
expect(balances).toHaveLength(4);
done();
});
});
it('subscribes to derived balances (balances.all)', (done) => {
return(
api.derive.balances.all(
keyring.alice.address(),
(all) => {
expect(all.accountId.toString()).toEqual(keyring.alice.address());
expect(all.freeBalance).toBeDefined();
expect(all.freeBalance.gt(ZERO)).toBe(true);
expect(all.availableBalance).toBeDefined();
expect(all.availableBalance.gt(ZERO)).toBe(true);
expect(all.reservedBalance).toBeDefined();
expect(all.lockedBalance).toBeDefined();
expect(all.vestedBalance).toBeDefined();
done();
}
)
);
});
it('makes a query at a latest block (specified)', async () => {
const header = await api.rpc.chain.getHeader() as Header;
const events = await api.query.system.events.at(header.hash) as Vector<EventRecord>;
expect(events.length).not.toEqual(0);
events.forEach(({ event: { data, method, section }, phase, topics }: EventRecord) => {
console.error(phase.toString(), `: ${section}.${method}`, data.toString(), topics.toString());
});
});
it('subscribes to events', (done) => {
return(
api.query.system.events((events) => {
expect(events).not.toHaveLength(0);
done();
})
);
});
it('queries state using double map key', async () => {
// TODO Update ['any', '0x1234'] to the key of a known event topic and update '[]' to the expected value
const eventTopics = await api.query.system.eventTopics(['any', '0x1234']);
expect(eventTopics.toString()).toEqual('[]');
});
it('subscribes to queries using double map key', async (done) => {
return(
// TODO Update ['any', '0x1234'] to the key of a known event topic and update '[]' to the expected value
api.query.system.eventTopics(['any', '0x1234'], (eventTopics) => {
expect(eventTopics.toString()).toEqual('[]');
done();
})
);
});
});
@@ -4,35 +4,37 @@
import Keyring from '@polkadot/keyring';
import testingPairs from '@polkadot/keyring/testingPairs';
import { ExtrinsicEra } from '@polkadot/types/type';
import { randomAsHex } from '@polkadot/util-crypto';
import WsProvider from '@polkadot/rpc-provider/ws';
import { ExtrinsicEra, Hash, Index, SignedBlock } from '@polkadot/types';
import Api from '../../src/promise';
import WsProvider from '../../../rpc-provider/src/ws';
import SingleAccountSigner from '../util/SingleAccountSigner';
import { SubmittableResult } from './../../src';
import { Signer } from './../../src/types';
import Api from './../../src/promise';
describe.skip('e2e transactions', () => {
// log all events for the transfare, calling done() when finalized
const logEvents = (done) =>
({ events, status }) => {
console.log('Transaction status:', status.type);
// log all events for the transfare, calling done() when finalized
const logEvents = (done: () => {}) =>
({ events, status }: SubmittableResult) => {
console.log('Transaction status:', status.type);
if (status.isFinalized) {
console.log('Completed at block hash', status.value.toHex());
console.log('Events:');
if (status.isFinalized) {
console.log('Completed at block hash', status.value.toHex());
console.log('Events:');
events.forEach(({ phase, event: { data, method, section } }) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
events.forEach(({ phase, event: { data, method, section } }: any) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
});
if (events.length) {
done();
}
if (events.length) {
done();
}
};
}
};
describe.skip('Promise e2e transactions', () => {
const keyring = testingPairs({ type: 'ed25519' });
let api;
let api: Api;
beforeEach(async (done) => {
if (!api) {
@@ -50,7 +52,7 @@ describe.skip('e2e transactions', () => {
});
it('can submit an extrinsic from hex', async (done) => {
const nonce = await api.query.system.accountNonce(keyring.dave.address());
const nonce = await api.query.system.accountNonce(keyring.dave.address()) as Index;
const hex = api.tx.balances
.transfer(keyring.eve.address(), 12345)
.sign(keyring.dave, { nonce })
@@ -60,7 +62,7 @@ describe.skip('e2e transactions', () => {
});
it('makes a transfer (sign, then send)', async (done) => {
const nonce = await api.query.system.accountNonce(keyring.dave.address());
const nonce = await api.query.system.accountNonce(keyring.dave.address()) as Index;
return api.tx.balances
.transfer(keyring.eve.address(), 12345)
@@ -69,11 +71,11 @@ describe.skip('e2e transactions', () => {
});
it('makes a transfer (sign, then send - compat version)', async (done) => {
const nonce = await api.query.system.accountNonce(keyring.dave.address());
const nonce = await api.query.system.accountNonce(keyring.dave.address()) as Index;
return api.tx.balances
.transfer(keyring.eve.address(), 12345)
.sign(keyring.dave, nonce)
.sign(keyring.dave, { nonce })
.send(logEvents(done));
});
@@ -84,7 +86,7 @@ describe.skip('e2e transactions', () => {
});
it('makes a transfer (signAndSend via Signer)', async (done) => {
const signer = new SingleAccountSigner(keyring.dave);
const signer = new SingleAccountSigner(keyring.dave) as Signer;
api.setSigner(signer);
@@ -93,28 +95,32 @@ describe.skip('e2e transactions', () => {
.signAndSend(keyring.dave.address(), logEvents(done));
});
it('makes a transfer (signAndSend via Signer) - sad path', async () => {
//no signer
api.setSigner();
it('makes a transfer (signAndSend via Signer) with undefined Signer', async () => {
const signer: any = undefined;
// no signer
api.setSigner(signer);
await expect(api.tx.balances
.transfer(keyring.eve.address(), 12345)
.signAndSend(keyring.alice.address())).rejects.toThrow('no signer exists');
});
const signer = new SingleAccountSigner(keyring.dave);
it('makes a transfer (signAndSend via Signer) with the wrong keyring pair', async () => {
const signer: Signer = new SingleAccountSigner(keyring.dave);
api.setSigner(signer);
//no callback
// no callback
await expect(api.tx.balances
.transfer(keyring.eve.address(), 12345)
.signAndSend(keyring.alice.address())).rejects.toThrow('does not have the keyringPair');
});
//with callback
it('makes a transfer (signAndSend via Signer) with the wrong keyring pair with a callback', async () => {
// with callback
await expect(api.tx.balances
.transfer(keyring.eve.address(), 12345)
.signAndSend(keyring.alice.address(), ({ events, status }) => {
})).rejects.toThrow('does not have the keyringPair');
.signAndSend(keyring.alice.address(), (cb: any) => { /*do nothing */ })).rejects.toThrow('does not have the keyringPair');
});
it('makes a transfer (no callback)', async () => {
@@ -128,7 +134,7 @@ describe.skip('e2e transactions', () => {
it('makes a proposal', async () => {
// don't wait for status, just get hash. Here we generate a large-ish payload
// to ensure that we can sign with the hashed version as well (and have it accepted)
const hash = await api.tx.democracy
const hash: Hash = await api.tx.democracy
.propose(api.tx.consensus.setCode(randomAsHex(4096)), 10000)
.signAndSend(keyring.bob);
@@ -138,13 +144,13 @@ describe.skip('e2e transactions', () => {
it('makes a transfer, and uses new balance to transfers to new', async (done) => {
const pair = new Keyring().addFromUri('testing123', {}, 'ed25519');
function doOne (cb) {
function doOne (cb: any) {
return api.tx.balances
.transfer(pair.address(), 123456)
.signAndSend(keyring.dave, logEvents(cb));
};
}
function doTwo (cb) {
function doTwo (cb: any) {
return api.tx.balances
.transfer(keyring.alice.address(), 12345)
.signAndSend(pair, logEvents(cb));
@@ -152,47 +158,46 @@ describe.skip('e2e transactions', () => {
// return doTwo(done);
return doOne(() => {
doTwo(done)
return doTwo(done);
});
});
it('makes a transfer with ERA (signAndSend)', async (done) => {
const nonce = await api.query.system.accountNonce(keyring.dave.address());
const nonce = await api.query.system.accountNonce(keyring.dave.address()) as Index;
const signedBlock = await api.rpc.chain.getBlock();
const currentHeight = signedBlock.block.header.number;
const currentHeight = (signedBlock as SignedBlock).block.header.number;
const exERA = new ExtrinsicEra({ current: currentHeight, period: 10 });
// eraBirth - start of ERA which is always less than current block height
// eraDeath - end of ERA validity (EXPIRY)
const eraBirth = exERA.asMortalEra.birth(currentHeight.toNumber());
const eraDeath = exERA.asMortalEra.death(currentHeight.toNumber());
console.log('STARTED AT :'+eraBirth+' EXPIRED AT :'+eraDeath);
console.log('STARTED AT :' + eraBirth + ' EXPIRED AT :' + eraDeath);
const eraHash = await api.rpc.chain.getBlockHash(eraBirth);
const ex = api.tx.balances
.transfer(keyring.eve.address(), 12345);
const hash = await ex.signAndSend(keyring.dave, {blockHash: eraHash, era:exERA, nonce});
const ex = api.tx.balances.transfer(keyring.eve.address(), 12345);
const hash = await ex.signAndSend(keyring.dave, { blockHash: eraHash, era: exERA, nonce } as any);
expect(hash.toHex()).toHaveLength(66);
done();
});
it('makes a transfer with ERA (signAndSend) with invalid time', async (done) => {
const nonce = await api.query.system.accountNonce(keyring.alice.address());
const nonce = await api.query.system.accountNonce(keyring.alice.address()) as Index;
const signedBlock = await api.rpc.chain.getBlock();
const currentHeight = signedBlock.block.header.number;
const currentHeight = (signedBlock as SignedBlock).block.header.number;
const exERA = new ExtrinsicEra({ current: currentHeight, period: 4 });
const eraBirth = exERA.asMortalEra.birth(currentHeight.toNumber());
const eraDeath = exERA.asMortalEra.death(currentHeight.toNumber());
console.log('STARTED AT :'+eraBirth+' EXPIRED AT :'+eraDeath);
console.log('STARTED AT :' + eraBirth + ' EXPIRED AT :' + eraDeath);
const eraHash = await api.rpc.chain.getBlockHash(eraBirth);
const ex = api.tx.balances.transfer(keyring.eve.address(), 12345);
const unsubscribe = await api.rpc.chain.subscribeNewHead(async(header) => {
console.log(`Chain is at block: #${header.blockNumber}`);
if (header.blockNumber.toNumber() === eraDeath-1) {
const hash = await ex.signAndSend(keyring.alice, {blockHash: eraHash, era:exERA, nonce});
expect(hash).toBeUndefined();
done();
}
});
return(
api.rpc.chain.subscribeNewHead(async (header) => {
if (header.blockNumber.toNumber() === eraDeath - 1) {
const hash = await ex.signAndSend(keyring.alice, { blockHash: eraHash, era: exERA, nonce } as any);
expect(hash).toBeUndefined();
done();
}
})
);
});
});
@@ -2,14 +2,17 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import BN from 'bn.js';
import { switchMap } from 'rxjs/operators';
import { Balance } from '@polkadot/types';
import testingPairs from '@polkadot/keyring/testingPairs';
import Api from '../../src/rx';
describe.skip('e2e queries', () => {
describe.skip('Rx e2e queries', () => {
const keyring = testingPairs({ type: 'ed25519' });
let api;
let api: Api;
beforeEach(async (done) => {
api = await Api.create().toPromise();
@@ -29,10 +32,8 @@ describe.skip('e2e queries', () => {
it('queries state for a balance', (done) => {
api.query.balances.freeBalance(keyring.alice.address()).subscribe((balance) => {
expect(
balance.isZero()
).toBe(false);
expect(balance).toBeInstanceOf(BN);
expect((balance as Balance).isZero()).toBe(false);
done();
});
});
@@ -41,11 +42,11 @@ describe.skip('e2e queries', () => {
api.rpc.chain
.getHeader()
.pipe(
switchMap((header) =>
api.query.system.events.at(header.hash)
switchMap(({ hash }: any) =>
api.query.system.events.at(hash)
)
)
.subscribe((events) => {
.subscribe((events: any) => {
expect(events.length).not.toEqual(0);
done();
});
@@ -3,18 +3,20 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { first, switchMap } from 'rxjs/operators';
import testingPairs from '@polkadot/keyring/testingPairs';
import Api from '../../src/rx';
import Api from './../../src/rx';
import { SubmittableResult } from './../../src';
describe.skip('e2e transactions', () => {
describe.skip('Rx e2e transactions', () => {
const keyring = testingPairs({ type: 'ed25519' });
let api;
let api: Api;
beforeEach(async (done) => {
api = await Api.create().toPromise();
jest.setTimeout(30000);
done()
done();
});
afterEach(() => {
@@ -26,14 +28,14 @@ describe.skip('e2e transactions', () => {
.accountNonce(keyring.alice.address())
.pipe(
first(),
switchMap((nonce) =>
switchMap((nonce: any) =>
api.tx.balances
.transfer(keyring.bob.address(), 12345)
.sign(keyring.alice, { nonce })
.send()
)
)
.subscribe(({ status }) => {
.subscribe(({ status }: SubmittableResult) => {
if (status.isFinalized) {
done();
}
@@ -45,14 +47,14 @@ describe.skip('e2e transactions', () => {
.accountNonce(keyring.alice.address())
.pipe(
first(),
switchMap((nonce) =>
switchMap((nonce: any) =>
api.tx.democracy
.propose(api.tx.consensus.setCode('0xdeadbeef'), 10000)
.sign(keyring.alice, { nonce })
.send()
)
)
.subscribe(({ status }) => {
.subscribe(({ status }: SubmittableResult) => {
if (status.isFinalized) {
done();
}