/
index.ts
227 lines (181 loc) · 7 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/rpc-provider 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 { Header } from '@polkadot/types/interfaces';
import { Codec, Registry } from '@polkadot/types/types';
import { ProviderInterface, ProviderInterfaceEmitted, ProviderInterfaceEmitCb } from '../types';
import { MockStateSubscriptions, MockStateSubscriptionCallback, MockStateDb } from './types';
import BN from 'bn.js';
import EventEmitter from 'eventemitter3';
import Metadata from '@polkadot/metadata';
import rpcMetadata from '@polkadot/metadata/Metadata/static';
import interfaces from '@polkadot/jsonrpc';
import testKeyring from '@polkadot/keyring/testing';
import rpcSignedBlock from '@polkadot/types/json/SignedBlock.004.immortal.json';
import { createType } from '@polkadot/types';
import { bnToU8a, logger, u8aToHex } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
const INTERVAL = 1000;
const SUBSCRIPTIONS: string[] = Array.prototype.concat.apply(
[], Object.values(interfaces).map((area): string[] =>
Object
.values(area.methods)
.filter((method): boolean =>
method.isSubscription
)
.map(({ method, section }): string =>
`${section}_${method}`
)
.concat('chain_subscribeNewHead')
)
);
const keyring = testKeyring({ type: 'ed25519' });
const l = logger('api-mock');
/**
* A mock provider mainly used for testing.
* @return {ProviderInterface} The mock provider
*/
export default class Mock implements ProviderInterface {
private db: MockStateDb = {};
private emitter = new EventEmitter();
public isUpdating = true;
private registry: Registry;
private requests: Record<string, (...params: any[]) => any> = {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
chain_getBlock: (hash: string): any => createType(this.registry, 'SignedBlock', rpcSignedBlock.result).toJSON(),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
chain_getBlockHash: (blockNumber: number): string => '0x1234',
state_getRuntimeVersion: (): string => createType(this.registry, 'RuntimeVersion').toHex(),
state_getStorage: (storage: MockStateDb, params: any[]): string => {
return u8aToHex(
storage[(params[0] as string)]
);
},
system_chain: (): string => 'mockChain',
state_getMetadata: (): string => rpcMetadata,
system_name: (): string => 'mockClient',
system_properties: (): Record<string, number | string> => ({ ss58Format: 42 }),
system_version: (): string => '9.8.7'
};
public subscriptions: MockStateSubscriptions = SUBSCRIPTIONS.reduce((subs, name): MockStateSubscriptions => {
subs[name] = {
callbacks: {},
lastValue: null
};
return subs;
}, ({} as unknown as MockStateSubscriptions));
private subscriptionId = 0;
private subscriptionMap: Record<number, string> = {};
constructor (registry: Registry) {
this.registry = registry;
this.init();
}
public get hasSubscriptions (): boolean {
return true;
}
public clone (): Mock {
throw new Error('Unimplemented');
}
public disconnect (): void {
// noop
}
public isConnected (): boolean {
return true;
}
public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): void {
this.emitter.on(type, sub);
}
// eslint-disable-next-line @typescript-eslint/require-await
public async send (method: string, params: any[]): Promise<any> {
if (!this.requests[method]) {
throw new Error(`provider.send: Invalid method '${method}'`);
}
return this.requests[method](this.db, params);
}
// eslint-disable-next-line @typescript-eslint/require-await
public async subscribe (type: string, method: string, ...params: any[]): Promise<number> {
l.debug((): any => ['subscribe', method, params]);
if (this.subscriptions[method]) {
const callback: MockStateSubscriptionCallback = params.pop();
const id = ++this.subscriptionId;
this.subscriptions[method].callbacks[id] = callback;
this.subscriptionMap[id] = method;
if (this.subscriptions[method].lastValue !== null) {
callback(null, this.subscriptions[method].lastValue);
}
return id;
}
throw new Error(`provider.subscribe: Invalid method '${method}'`);
}
// eslint-disable-next-line @typescript-eslint/require-await
public async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
const sub = this.subscriptionMap[id];
l.debug((): any => ['unsubscribe', id, sub]);
if (!sub) {
throw new Error(`Unable to find subscription for ${id}`);
}
delete this.subscriptionMap[id];
delete this.subscriptions[sub].callbacks[id];
return true;
}
private init (): void {
const emitEvents: ProviderInterfaceEmitted[] = ['connected', 'disconnected'];
let emitIndex = 0;
let newHead = this.makeBlockHeader(new BN(-1));
let counter = -1;
const metadata = new Metadata(this.registry, rpcMetadata);
// Do something every 1 seconds
setInterval((): void => {
if (!this.isUpdating) {
return;
}
// create a new header (next block)
newHead = this.makeBlockHeader(newHead.number.toBn());
// increment the balances and nonce for each account
keyring.getPairs().forEach(({ publicKey }, index): void => {
this.setStateBn(metadata.query.balances.freeBalance(publicKey), newHead.number.toBn().muln(3).iaddn(index));
this.setStateBn(metadata.query.system.accountNonce(publicKey), newHead.number.toBn().addn(index));
});
// set the timestamp for the current block
this.setStateBn(metadata.query.timestamp.now(), Math.floor(Date.now() / 1000));
this.updateSubs('chain_subscribeNewHead', newHead);
// We emit connected/disconnected at intervals
if (++counter % 2 === 1) {
if (++emitIndex === emitEvents.length) {
emitIndex = 0;
}
this.emitter.emit(emitEvents[emitIndex]);
}
}, INTERVAL);
}
private makeBlockHeader (prevNumber: BN): Header {
const blockNumber = prevNumber.addn(1);
return createType(this.registry, 'Header', {
digest: {
logs: []
},
extrinsicsRoot: randomAsU8a(),
number: blockNumber,
parentHash: blockNumber.isZero()
? new Uint8Array(32)
: bnToU8a(prevNumber, 256, false),
stateRoot: bnToU8a(blockNumber, 256, false)
});
}
private setStateBn (key: Uint8Array, value: BN | number): void {
this.db[u8aToHex(key)] = bnToU8a(value, 64, true);
}
private updateSubs (method: string, value: Codec): void {
this.subscriptions[method].lastValue = value;
Object
.values(this.subscriptions[method].callbacks)
.forEach((cb): void => {
try {
cb(null, value.toJSON());
} catch (error) {
console.error(`Error on '${method}' subscription`, error);
}
});
}
}