1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | import { StorageFunction } from '@polkadot/types/StorageKey';
|
8 | import { KeyringPair } from '@polkadot/util-keyring/types';
|
9 | import { ProviderInterface$Emitted } from '../types';
|
10 | import { MockState, MockState$Db, MockState$Subscriptions } from './types';
|
11 |
|
12 | import BN from 'bn.js';
|
13 | import Header from '@polkadot/types/Header';
|
14 | import storage from '@polkadot/storage/testing';
|
15 | import bnToU8a from '@polkadot/util/bn/toU8a';
|
16 | import u8aToHex from '@polkadot/util/u8a/toHex';
|
17 | import randomAsU8a from '@polkadot/util-crypto/random/asU8a';
|
18 | import testKeyring from '@polkadot/util-keyring/testing';
|
19 |
|
20 | const keyring = testKeyring();
|
21 |
|
22 | const emitEvents: Array<ProviderInterface$Emitted> = ['connected', 'disconnected'];
|
23 | let emitIndex = 0;
|
24 |
|
25 | function makeBlockHeader (prevNumber: BN) {
|
26 | const blockNumber = prevNumber.addn(1);
|
27 |
|
28 | return {
|
29 | digest: {
|
30 | logs: []
|
31 | },
|
32 | extrinsicsRoot: randomAsU8a(),
|
33 | number: blockNumber,
|
34 | parentHash: prevNumber.eqn(-1)
|
35 | ? new Uint8Array(32)
|
36 | : bnToU8a(prevNumber, 256, false),
|
37 | stateRoot: bnToU8a(blockNumber, 256, false)
|
38 | };
|
39 | }
|
40 |
|
41 | function updateSubs (subscriptions: MockState$Subscriptions, method: string, value: any) {
|
42 | subscriptions[method].lastValue = value;
|
43 |
|
44 | Object
|
45 | .values(subscriptions[method].callbacks)
|
46 | .forEach((cb) => {
|
47 | try {
|
48 | cb(null, value);
|
49 | } catch (error) {
|
50 | console.error(`Error on '${method}' subscription`, error);
|
51 | }
|
52 | });
|
53 | }
|
54 |
|
55 | function setStorageBn (db: MockState$Db, createKey: StorageFunction, value: BN | number, ...keyParams: Array<Uint8Array>): void {
|
56 | const keyValue = u8aToHex(
|
57 | createKey(...keyParams)
|
58 | );
|
59 |
|
60 | db[keyValue] = bnToU8a(value, 64, true);
|
61 | }
|
62 |
|
63 | export default function mocks ({ emitter, db, subscriptions }: MockState): void {
|
64 | let newHead = makeBlockHeader(new BN(-1));
|
65 |
|
66 | setInterval(() => {
|
67 | if (++emitIndex === emitEvents.length) {
|
68 | emitIndex = 0;
|
69 | }
|
70 |
|
71 | emitter.emit(emitEvents[emitIndex]);
|
72 |
|
73 | newHead = makeBlockHeader(newHead.number);
|
74 |
|
75 | keyring.getPairs().forEach(({ publicKey }: KeyringPair, index: number) => {
|
76 | setStorageBn(db, storage.balances.freeBalance, newHead.number.muln(3).iaddn(index), publicKey());
|
77 | setStorageBn(db, storage.system.accountNonce, newHead.number.addn(index), publicKey());
|
78 | });
|
79 |
|
80 | setStorageBn(db, storage.timestamp.now, Math.floor(Date.now() / 1000));
|
81 |
|
82 | updateSubs(subscriptions, 'chain_newHead', new Header(newHead).toJSON());
|
83 | }, 5000);
|
84 | }
|