refactor: Remove rpc-rx (#1037)
* Remove rpc-rx * Make some stuff work * Fix tests * Update Base * Change some stuff * Remove rpc-rx mentions * Add correct tests * Make cache work * Fix little bugs * Rename to spec * Fix lint * Fix little bugs * Add comment * Add correct test * Update header * Add test * Add comments * Indentation
This commit is contained in:
+34
-29
@@ -17,53 +17,58 @@ import Rpc from '@polkadot/rpc-core';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
|
||||
const provider = new WsProvider('http://127.0.0.1:9944');
|
||||
const api = new Rpc(provider);
|
||||
const rpc = new Rpc(provider);
|
||||
```
|
||||
|
||||
Retrieving the block header object for a given block header hash (a 0x-prefixed hex string with length of 64) -
|
||||
|
||||
```js
|
||||
api.chain
|
||||
rpc.chain
|
||||
.getHeader('0x1234567890')
|
||||
.then((header) => console.log(header))
|
||||
.catch((error) => console.error(error));
|
||||
.subscribe(
|
||||
(header) => console.log(header),
|
||||
(error) => console.error('error:', error)
|
||||
);
|
||||
```
|
||||
|
||||
Retrieving the best block number, parent hash, state root hash, extrinsics root hash, and digest (once-off) -
|
||||
|
||||
```js
|
||||
api.chain
|
||||
rpc.chain
|
||||
.getHead()
|
||||
.then((headerHash) => {
|
||||
return api.chain.getHeader(headerHash);
|
||||
})
|
||||
.then((header) => {
|
||||
console.log(`best #${header.blockNumber.toString()}`);
|
||||
console.log(`parentHash: ${header.parentHash.toString()}`);
|
||||
console.log(`stateRoot: ${header.stateRoot.toString()}`);
|
||||
console.log(`extrinsicsRoot: ${header.extrinsicsRoot.toString()}`);
|
||||
console.log(`digest: ${header.digest.toString()}`);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('error:', error);
|
||||
});
|
||||
.pipe(
|
||||
switchMap((headerHash) => {
|
||||
return rpc.chain.getHeader(headerHash);
|
||||
})
|
||||
)
|
||||
.subscribe(
|
||||
(header) => {
|
||||
console.log(`best #${header.blockNumber.toString()}`);
|
||||
console.log(`parentHash: ${header.parentHash.toString()}`);
|
||||
console.log(`stateRoot: ${header.stateRoot.toString()}`);
|
||||
console.log(`extrinsicsRoot: ${header.extrinsicsRoot.toString()}`);
|
||||
console.log(`digest: ${header.digest.toString()}`);
|
||||
},
|
||||
(error) => {
|
||||
console.error('error:', error);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
Retrieving best header via subscription -
|
||||
|
||||
```js
|
||||
api.chain
|
||||
.subscribeNewHead((header) => {
|
||||
console.log(`best #${header.blockNumber}`);
|
||||
})
|
||||
.then((subscriptionId) => {
|
||||
console.log(`subscriptionId: ${subscriptionId}`);
|
||||
// id for the subscription, can unsubscribe via
|
||||
// api.chain.subscribeNewHead.unsubscribe(subscriptionId);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('error subscribing:', error);
|
||||
});
|
||||
rpc
|
||||
.subscribeNewHead()
|
||||
.subscribe(
|
||||
(header) => {
|
||||
console.log(`best #${header.blockNumber}`);
|
||||
},
|
||||
(error) => {
|
||||
console.error('error subscribing:', error);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
## Classes
|
||||
|
||||
@@ -30,6 +30,8 @@
|
||||
"@polkadot/jsonrpc": "^0.82.0-beta.13",
|
||||
"@polkadot/rpc-provider": "^0.82.0-beta.13",
|
||||
"@polkadot/types": "^0.82.0-beta.13",
|
||||
"@polkadot/util": "^0.94.0-beta.3"
|
||||
"@polkadot/util": "^0.94.0-beta.3",
|
||||
"memoizee": "^0.4.14",
|
||||
"rxjs": "^6.5.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// Copyright 2017-2019 @polkadot/rpc-core 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 testingPairs from '@polkadot/keyring/testingPairs';
|
||||
import MockProvider from '@polkadot/rpc-provider/mock';
|
||||
import { AccountId } from '@polkadot/types';
|
||||
|
||||
import Rpc from '.';
|
||||
|
||||
describe('Cached Observables', () => {
|
||||
let rpc: Rpc;
|
||||
const keyring = testingPairs();
|
||||
|
||||
beforeEach(() => {
|
||||
rpc = new Rpc(new MockProvider());
|
||||
});
|
||||
|
||||
it('creates a single observable for subscriptions (multiple calls)', () => {
|
||||
const observable1 = rpc.chain.subscribeNewHead(123);
|
||||
const observable2 = rpc.chain.subscribeNewHead(123);
|
||||
|
||||
expect(observable2).toBe(observable1);
|
||||
});
|
||||
|
||||
it('creates a single observable for subscriptions (multiple calls, no arguments)', () => {
|
||||
const observable1 = rpc.chain.subscribeNewHead();
|
||||
const observable2 = rpc.chain.subscribeNewHead();
|
||||
|
||||
expect(observable2).toBe(observable1);
|
||||
});
|
||||
|
||||
it('creates a single observable (multiple calls, different arguments that should be cached together)', () => {
|
||||
const observable1 = rpc.chain.subscribeNewHead(keyring.alice.address);
|
||||
const observable2 = rpc.chain.subscribeNewHead(new AccountId(keyring.alice.address));
|
||||
|
||||
expect(observable2).toBe(observable1);
|
||||
});
|
||||
|
||||
it('creates multiple observables for different values', () => {
|
||||
const observable1 = rpc.chain.subscribeNewHead(123);
|
||||
const observable2 = rpc.chain.subscribeNewHead(456);
|
||||
|
||||
expect(observable2).not.toBe(observable1);
|
||||
});
|
||||
|
||||
it('clears cache if there are no more subscribers', () => {
|
||||
const observable1 = rpc.chain.subscribeNewHead();
|
||||
const observable2 = rpc.chain.subscribeNewHead();
|
||||
|
||||
expect(observable1).toBe(observable2);
|
||||
|
||||
const sub1 = observable1.subscribe();
|
||||
const sub2 = observable2.subscribe();
|
||||
|
||||
sub1.unsubscribe();
|
||||
sub2.unsubscribe();
|
||||
|
||||
// No more subscribers, now create a new observable
|
||||
const observable3 = rpc.chain.subscribeNewHead();
|
||||
|
||||
expect(observable3).not.toBe(observable1);
|
||||
});
|
||||
|
||||
it('creates different observables for different methods but same arguments', () => {
|
||||
const observable1 = rpc.chain.subscribeNewHead(123);
|
||||
const observable2 = rpc.state.subscribeStorage(123);
|
||||
|
||||
expect(observable2).not.toBe(observable1);
|
||||
});
|
||||
|
||||
it('creates multiple observables for one-shots', () => {
|
||||
const observable1 = rpc.system.chain(123);
|
||||
const observable2 = rpc.system.chain(123);
|
||||
|
||||
expect(observable2).not.toBe(observable1);
|
||||
});
|
||||
});
|
||||
@@ -16,11 +16,11 @@ import Api from '.';
|
||||
const ADDR_ONE = '5DkQbYAExs3M2sZgT1Ec3mKfZnAQCL4Dt9beTCknkCUn5jzo';
|
||||
const ADDR_TWO = '5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF';
|
||||
const BALANCE_KEYS = [
|
||||
/* v3- */ '0x4af2c53fce3ec33c6ccccf22e926f1a7',
|
||||
/* v4+ */ '0xec8f96437274a883afcac82d01a9defeb68209cd4f2c084632813692aa5e65ad'
|
||||
/* v3-, using xxHash */ '0x4af2c53fce3ec33c6ccccf22e926f1a7',
|
||||
/* v4+, using blake2_256 */ '0xec8f96437274a883afcac82d01a9defeb68209cd4f2c084632813692aa5e65ad'
|
||||
];
|
||||
|
||||
function formattingTests (version: string, storage: Storage, encodedValues: [String, String]) {
|
||||
function formattingTests (version: string, storage: Storage, encodedValues: [string, string]) {
|
||||
const [ENC_ONE, ENC_TWO] = encodedValues;
|
||||
|
||||
describe(`formatting with Metadata ${version}`, () => {
|
||||
@@ -36,8 +36,8 @@ function formattingTests (version: string, storage: Storage, encodedValues: [Str
|
||||
: null
|
||||
)
|
||||
),
|
||||
subscribe: jest.fn((type, method, params, subscription) =>
|
||||
subscription(null, {
|
||||
subscribe: jest.fn((type, method, params, cb) =>
|
||||
cb(null, {
|
||||
block: '0x1234',
|
||||
changes: [
|
||||
[ENC_ONE, '0x01020000000000000000000000000000'],
|
||||
@@ -49,10 +49,10 @@ function formattingTests (version: string, storage: Storage, encodedValues: [Str
|
||||
api = new Api(provider);
|
||||
});
|
||||
|
||||
it('encodes key (with params), decoding response', () => {
|
||||
return api.state
|
||||
it('encodes key (with params), decoding response', (done) => {
|
||||
api.state
|
||||
.getStorage([storage.balances.freeBalance, ADDR_ONE])
|
||||
.then((value) => {
|
||||
.subscribe((value) => {
|
||||
expect(
|
||||
provider.send
|
||||
).toHaveBeenCalledWith(
|
||||
@@ -60,42 +60,44 @@ function formattingTests (version: string, storage: Storage, encodedValues: [Str
|
||||
[ENC_ONE]
|
||||
);
|
||||
expect(value.toNumber()).toEqual(513);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the fallback result on not-found values', () => {
|
||||
return api.state
|
||||
it('returns the fallback result on not-found values', (done) => {
|
||||
api.state
|
||||
.getStorage([storage.system.accountNonce, ADDR_ONE])
|
||||
.then((value) => {
|
||||
.subscribe((value) => {
|
||||
expect(value.toHex()).toEqual('0x0000000000000000');
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('encodes multiple keys, decoding multiple results', (done) => {
|
||||
return api.state.subscribeStorage(
|
||||
api.state.subscribeStorage(
|
||||
[
|
||||
[storage.balances.freeBalance, ADDR_ONE],
|
||||
[storage.balances.freeBalance, ADDR_TWO]
|
||||
],
|
||||
(value: any) => {
|
||||
console.error(value);
|
||||
]
|
||||
).subscribe((value: any) => {
|
||||
console.error(value);
|
||||
|
||||
expect(
|
||||
provider.subscribe
|
||||
).toHaveBeenCalledWith(
|
||||
'state_storage',
|
||||
'state_subscribeStorage',
|
||||
[[ENC_ONE, ENC_TWO]],
|
||||
expect.anything()
|
||||
);
|
||||
expect(
|
||||
value.map((balance: BN) =>
|
||||
balance.toNumber()
|
||||
)
|
||||
).toEqual([513, 258]);
|
||||
expect(
|
||||
provider.subscribe
|
||||
).toHaveBeenCalledWith(
|
||||
'state_storage',
|
||||
'state_subscribeStorage',
|
||||
[[ENC_ONE, ENC_TWO]],
|
||||
expect.anything()
|
||||
);
|
||||
expect(
|
||||
value.map((balance: BN) =>
|
||||
balance.toNumber()
|
||||
)
|
||||
).toEqual([513, 258]);
|
||||
|
||||
done();
|
||||
});
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,38 +2,25 @@
|
||||
// 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 '.';
|
||||
import MockProvider from '@polkadot/rpc-provider/mock';
|
||||
|
||||
import Rpc from '.';
|
||||
|
||||
describe('Api', () => {
|
||||
let api: Api;
|
||||
let provider: any;
|
||||
let sendSpy: any;
|
||||
|
||||
beforeEach(() => {
|
||||
provider = {
|
||||
send: (method: any, params: Array<any>) => {
|
||||
return Promise.resolve(params[0]);
|
||||
}
|
||||
};
|
||||
sendSpy = jest.spyOn(provider, 'send');
|
||||
api = new Api(provider);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sendSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('requires a provider with a send method', () => {
|
||||
expect(
|
||||
() => new Api({} as any)
|
||||
() => new Rpc({} as any)
|
||||
).toThrow(/Expected Provider/);
|
||||
});
|
||||
|
||||
it('sets up the chain interface', () => {
|
||||
expect(api.chain).toBeDefined();
|
||||
});
|
||||
it('creates an instance with all sections', () => {
|
||||
const rpc = new Rpc(new MockProvider());
|
||||
|
||||
it('sets up the state interface', () => {
|
||||
expect(api.state).toBeDefined();
|
||||
expect(
|
||||
Object.keys(rpc)
|
||||
).toEqual([
|
||||
'provider',
|
||||
'author', 'chain', 'state', 'system'
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
+100
-49
@@ -2,12 +2,14 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface, ProviderInterface$Callback } from '@polkadot/rpc-provider/types';
|
||||
import { ProviderInterface } from '@polkadot/rpc-provider/types';
|
||||
import { RpcSection, RpcMethod } from '@polkadot/jsonrpc/types';
|
||||
import { RpcInterface, RpcInterface$Method, RpcInterface$Section } from './types';
|
||||
|
||||
import memoize from 'memoizee';
|
||||
import { combineLatest, from, Observable, Observer, of, throwError } from 'rxjs';
|
||||
import { catchError, map, publishReplay, refCount, switchMap } from 'rxjs/operators';
|
||||
import interfaces from '@polkadot/jsonrpc';
|
||||
import { WsProvider } from '@polkadot/rpc-provider';
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
import { Option, StorageChangeSet, StorageKey, Vector, createClass, createType } from '@polkadot/types';
|
||||
import { ExtError, assert, isFunction, isNull, logger } from '@polkadot/util';
|
||||
@@ -39,15 +41,15 @@ const EMPTY_META = {
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import Api from '@polkadot/rpc-core';
|
||||
* import Rpc from '@polkadot/rpc-core';
|
||||
* import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
*
|
||||
* const provider = new WsProvider('ws://127.0.0.1:9944');
|
||||
* const api = new Api(provider);
|
||||
* const rpc = new Rpc(provider);
|
||||
* ```
|
||||
*/
|
||||
export default class Rpc implements RpcInterface {
|
||||
readonly _provider: ProviderInterface;
|
||||
readonly provider: ProviderInterface;
|
||||
readonly author: RpcInterface$Section;
|
||||
readonly chain: RpcInterface$Section;
|
||||
readonly state: RpcInterface$Section;
|
||||
@@ -58,10 +60,10 @@ export default class Rpc implements RpcInterface {
|
||||
* Default constructor for the Api Object
|
||||
* @param {ProviderInterface} provider An API provider using HTTP or WebSocket
|
||||
*/
|
||||
constructor (provider: ProviderInterface = new WsProvider()) {
|
||||
constructor (provider: ProviderInterface) {
|
||||
assert(provider && isFunction(provider.send), 'Expected Provider to API create');
|
||||
|
||||
this._provider = provider;
|
||||
this.provider = provider;
|
||||
|
||||
this.author = this.createInterface(interfaces.author);
|
||||
this.chain = this.createInterface(interfaces.chain);
|
||||
@@ -96,17 +98,21 @@ export default class Rpc implements RpcInterface {
|
||||
* @description Manually disconnect from the attached provider
|
||||
*/
|
||||
disconnect (): void {
|
||||
this._provider.disconnect();
|
||||
this.provider.disconnect();
|
||||
}
|
||||
|
||||
private createErrorMessage (method: RpcMethod, error: Error) {
|
||||
return `${Rpc.signature(method)}:: ${error.message}`;
|
||||
}
|
||||
|
||||
private createInterface ({ methods }: RpcSection): RpcInterface$Section {
|
||||
return Object
|
||||
.keys(methods)
|
||||
.reduce((exposed, method) => {
|
||||
.reduce((exposed, methodName) => {
|
||||
|
||||
const def = methods[method];
|
||||
const def = methods[methodName];
|
||||
|
||||
exposed[method] = def.isSubscription
|
||||
exposed[methodName] = def.isSubscription
|
||||
? this.createMethodSubscribe(def)
|
||||
: this.createMethodSend(def);
|
||||
|
||||
@@ -117,23 +123,40 @@ export default class Rpc implements RpcInterface {
|
||||
private createMethodSend (method: RpcMethod): RpcInterface$Method {
|
||||
const rpcName = `${method.section}_${method.method}`;
|
||||
|
||||
const call = async (...values: Array<any>): Promise<any> => {
|
||||
const call = (...values: Array<any>): Observable<any> => {
|
||||
// TODO Warn on deprecated methods
|
||||
try {
|
||||
const params = this.formatInputs(method, values);
|
||||
const paramsJson = params.map((param) => param.toJSON());
|
||||
const result = await this._provider.send(rpcName, paramsJson);
|
||||
|
||||
return this.formatOutput(method, params, result);
|
||||
} catch (error) {
|
||||
const message = `${Rpc.signature(method)}:: ${error.message}`;
|
||||
// Here, logically, it should be `of(this.formatInputs(method, values))`.
|
||||
// However, formatInputs can throw, and when it does, the above way
|
||||
// doesn't throw in the "Observable loop" (which is internally wrapped in
|
||||
// a try/catch block). So we:
|
||||
// - first do `of(1)` - won't throw
|
||||
// - then do `map(()=>this.formatInputs)` - might throw, but inside Observable.
|
||||
return of(1)
|
||||
.pipe(
|
||||
map(() => this.formatInputs(method, values)),
|
||||
switchMap((params) =>
|
||||
combineLatest([
|
||||
of(params),
|
||||
from(this.provider.send(rpcName, params.map((param) => param.toJSON())))
|
||||
])
|
||||
),
|
||||
map(([params, result]) => this.formatOutput(method, params, result)),
|
||||
catchError((error) => {
|
||||
const message = this.createErrorMessage(method, error);
|
||||
|
||||
l.error(message);
|
||||
l.error(message);
|
||||
|
||||
throw new ExtError(message, (error as ExtError).code, undefined);
|
||||
}
|
||||
return throwError(new ExtError(message, (error as ExtError).code, undefined));
|
||||
}),
|
||||
publishReplay(1), // create a Replay(1)
|
||||
refCount() // Unsubcribe WS when there are no more subscribers
|
||||
);
|
||||
};
|
||||
|
||||
// We voluntarily don't cache the "one-shot" RPC calls. For example,
|
||||
// `getStorage('123')` returns the current value, but this value can change
|
||||
// over time, so we wouldn't want to cache the Observable.
|
||||
return call as RpcInterface$Method;
|
||||
}
|
||||
|
||||
@@ -143,40 +166,68 @@ export default class Rpc implements RpcInterface {
|
||||
const unsubName = `${method.section}_${unsubMethod}`;
|
||||
const subType = `${method.section}_${updateType}`;
|
||||
|
||||
const unsubscribe = (subscriptionId: any): Promise<any> =>
|
||||
this._provider.unsubscribe(subType, unsubName, subscriptionId);
|
||||
const _call = async (...values: Array<any>): Promise<any> => {
|
||||
try {
|
||||
const cb: ProviderInterface$Callback = values.pop();
|
||||
const call = (...values: Array<any>): Observable<any> => {
|
||||
return new Observable((observer: Observer<any>) => {
|
||||
let subscriptionPromise: Promise<number>;
|
||||
|
||||
assert(isFunction(cb), `Expected callback in last position of params`);
|
||||
try {
|
||||
const params = this.formatInputs(method, values);
|
||||
const paramsJson = params.map((param) => param.toJSON());
|
||||
const update = (error?: Error, result?: any) => {
|
||||
if (error) {
|
||||
l.error(this.createErrorMessage(method, error));
|
||||
return;
|
||||
}
|
||||
|
||||
const params = this.formatInputs(method, values);
|
||||
const paramsJson = params.map((param) => param.toJSON());
|
||||
const update = (error: Error | null, result?: any) => {
|
||||
if (error) {
|
||||
l.error(`${Rpc.signature(method)}:: ${error.message}`);
|
||||
return;
|
||||
}
|
||||
observer.next(this.formatOutput(method, params, result));
|
||||
};
|
||||
|
||||
cb(this.formatOutput(method, params, result));
|
||||
subscriptionPromise = this.provider.subscribe(subType, subName, paramsJson, update);
|
||||
} catch (error) {
|
||||
const message = this.createErrorMessage(method, error);
|
||||
|
||||
l.error(message);
|
||||
|
||||
observer.error(new ExtError(message, (error as ExtError).code, undefined));
|
||||
}
|
||||
|
||||
// Teardown logic
|
||||
return () => {
|
||||
// Delete from cache
|
||||
// Reason:
|
||||
// ```
|
||||
// const s = api.query.system.accountNonce(addr1).subscribe(); // let's say it's 6
|
||||
// s.unsubscribe();
|
||||
// // wait a bit, for the nonce to increase to 7
|
||||
// api.query.system.accountNonce(addr1).subscribe(); // will output 6 instead of 7 if we don't clear cache
|
||||
// // that's because all our observables are replay(1)
|
||||
// ```
|
||||
memoized.delete(...values);
|
||||
// Unsubscribe from provider
|
||||
subscriptionPromise
|
||||
.then((subscriptionId) => this.provider.unsubscribe(subType, unsubName, subscriptionId))
|
||||
.catch((error: Error) => {
|
||||
const message = this.createErrorMessage(method, error);
|
||||
|
||||
l.error(message);
|
||||
});
|
||||
};
|
||||
|
||||
return this._provider.subscribe(subType, subName, paramsJson, update);
|
||||
} catch (error) {
|
||||
const message = `${Rpc.signature(method)}:: ${error.message}`;
|
||||
|
||||
l.error(message);
|
||||
|
||||
throw new ExtError(message, (error as ExtError).code, undefined);
|
||||
}
|
||||
}).pipe(
|
||||
publishReplay(1),
|
||||
refCount()
|
||||
);
|
||||
};
|
||||
|
||||
const call = _call as RpcInterface$Method;
|
||||
const memoized = memoize(call, {
|
||||
// Dynamic length for argument
|
||||
length: false,
|
||||
// Normalize args so that different args that should be cached
|
||||
// together are cached together.
|
||||
// E.g.: `query.my.method('abc') === query.my.method(new AccountId('abc'));`
|
||||
normalizer: JSON.stringify
|
||||
});
|
||||
|
||||
call.unsubscribe = unsubscribe;
|
||||
|
||||
return call;
|
||||
return memoized;
|
||||
}
|
||||
|
||||
private formatInputs (method: RpcMethod, inputs: Array<any>): Array<Codec> {
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
// 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 '.';
|
||||
import Rpc from '.';
|
||||
|
||||
describe('methodSend', () => {
|
||||
let api: Api;
|
||||
let rpc: Rpc;
|
||||
let methods: any;
|
||||
let provider: any;
|
||||
|
||||
@@ -33,34 +33,42 @@ describe('methodSend', () => {
|
||||
})
|
||||
};
|
||||
|
||||
api = new Api(provider);
|
||||
rpc = new Rpc(provider);
|
||||
});
|
||||
|
||||
it('wraps errors with the call signature', () => {
|
||||
it('wraps errors with the call signature', (done) => {
|
||||
// @ts-ignore private method
|
||||
const method = api.createMethodSend(methods.blah);
|
||||
const method = rpc.createMethodSend(methods.blah);
|
||||
|
||||
return method().catch((error) => {
|
||||
expect(error.message).toMatch(/blah \(foo: Bytes\): Bytes/);
|
||||
});
|
||||
method().subscribe(
|
||||
() => { /* noop */ },
|
||||
(error) => {
|
||||
expect(error.message).toMatch(/blah \(foo: Bytes\): Bytes/);
|
||||
done();
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
it('checks for mismatched parameters', () => {
|
||||
it('checks for mismatched parameters', (done) => {
|
||||
// @ts-ignore private method
|
||||
const method = api.createMethodSend(methods.bleh);
|
||||
const method = rpc.createMethodSend(methods.bleh);
|
||||
|
||||
return method(1).catch((error) => {
|
||||
expect(error.message).toMatch(/parameters, 1 found instead/);
|
||||
});
|
||||
method(1).subscribe(
|
||||
() => { /* noop */ },
|
||||
(error) => {
|
||||
expect(error.message).toMatch(/parameters, 1 found instead/);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('calls the provider with the correct parameters', () => {
|
||||
it('calls the provider with the correct parameters', (done) => {
|
||||
// @ts-ignore private method
|
||||
const method = api.createMethodSend(methods.blah);
|
||||
const method = rpc.createMethodSend(methods.blah);
|
||||
|
||||
// Args are length-prefixed, because it's a Bytes
|
||||
return method(new Uint8Array([2 << 2, 0x12, 0x34])).then(() => {
|
||||
method(new Uint8Array([2 << 2, 0x12, 0x34])).subscribe(() => {
|
||||
expect(provider.send).toHaveBeenCalledWith('test_blah', ['0x1234']);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// Copyright 2017-2019 @polkadot/rpc-core 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 { of } from 'rxjs';
|
||||
import MockProvider from '@polkadot/rpc-provider/mock';
|
||||
|
||||
import Rpc from '.';
|
||||
|
||||
describe('replay', () => {
|
||||
let rpc: Rpc;
|
||||
|
||||
beforeEach(() => {
|
||||
rpc = new Rpc(new MockProvider());
|
||||
});
|
||||
|
||||
it('subscribes via the rpc section', (done) => {
|
||||
rpc.chain.getBlockHash = jest.fn(() => of(1));
|
||||
|
||||
rpc.chain.getBlockHash(123, false).subscribe(() => {
|
||||
expect(
|
||||
rpc.chain.getBlockHash
|
||||
).toHaveBeenCalledWith(123, false);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the observable value', (done) => {
|
||||
rpc.system.chain().subscribe((value) => {
|
||||
if (value) {
|
||||
expect(value).toEqual('mockChain'); // Defined in MockProvider
|
||||
done();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('replay(1) works as expected', (done) => {
|
||||
const observable = rpc.system.chain();
|
||||
let a: string | undefined;
|
||||
observable.subscribe((value) => { a = value; });
|
||||
|
||||
setTimeout(() => {
|
||||
// Subscribe again to the same observable, it should fire value immediately
|
||||
observable.subscribe((value) => {
|
||||
expect(value).toEqual(a);
|
||||
done();
|
||||
});
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
it('unsubscribes as required', (done) => {
|
||||
rpc.provider.unsubscribe = jest.fn();
|
||||
|
||||
const subscription = rpc.chain.subscribeNewHead().subscribe(() => {
|
||||
subscription.unsubscribe();
|
||||
// There's a promise inside .unsubscribe(), wait a bit
|
||||
setTimeout(() => {
|
||||
expect(rpc.provider.unsubscribe).toHaveBeenCalled();
|
||||
done();
|
||||
}, 200);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,11 +2,10 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
export interface RpcInterface$Method {
|
||||
(...params: Array<any>): Promise<any>;
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
subscription: string;
|
||||
unsubscribe: (id: number) => Promise<any>;
|
||||
export interface RpcInterface$Method {
|
||||
(...params: Array<any>): Observable<any>;
|
||||
}
|
||||
|
||||
export type RpcInterface$Section = {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// Copyright 2017-2019 @polkadot/rpc-core 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 { BlockNumber, Index, SignedBlock, StorageChangeSet } from '@polkadot/types';
|
||||
import storage from '@polkadot/storage/static';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
|
||||
import Rpc from '../../src';
|
||||
|
||||
const randomAccount = '5HTqyWJHAVUieZnpb1V8gK4T1E4mnhkrUVSSzWBQd6kYgsVJ';
|
||||
|
||||
describe.skip('e2e Alexander - Polkadot', () => {
|
||||
let rpc: Rpc;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
rpc = new Rpc(new WsProvider('wss://poc3-rpc.polkadot.io/'));
|
||||
});
|
||||
|
||||
it('subscribes to storage', (done) => {
|
||||
rpc.state
|
||||
.subscribeStorage([
|
||||
[storage.system.accountNonce, randomAccount],
|
||||
[storage.session.currentIndex]
|
||||
])
|
||||
.subscribe((data: StorageChangeSet) => {
|
||||
expect(data).toHaveLength(2);
|
||||
expect(data).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.any(BlockNumber),
|
||||
expect.any(Index)
|
||||
])
|
||||
);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves a block by hash (krumme lanke #1)', (done) => {
|
||||
rpc.chain
|
||||
.getBlock('0x627847bffdf5f3e01ac440d057dec6a37a12a6f329db7ef8367665574b76b5df')
|
||||
.subscribe((block: SignedBlock) => {
|
||||
expect(block).toBeDefined();
|
||||
expect(block).toBeInstanceOf(SignedBlock);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves a block by hash (krumme lanke #2)', (done) => {
|
||||
rpc.chain
|
||||
.getBlock('0x53416d53a4b1dfcae9165a89d193608e4aa770414f02267f5b2c4015a2e66091')
|
||||
.subscribe((block: SignedBlock) => {
|
||||
expect(block).toBeDefined();
|
||||
expect(block).toBeInstanceOf(SignedBlock);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
// Copyright 2017-2019 @polkadot/rpc-core 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 { BlockNumber, Index, SignedBlock, StorageChangeSet } from '@polkadot/types';
|
||||
import storage from '@polkadot/storage/static';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
|
||||
import Rpc from '../../src';
|
||||
|
||||
const randomAccount = '5HTqyWJHAVUieZnpb1V8gK4T1E4mnhkrUVSSzWBQd6kYgsVJ';
|
||||
|
||||
describe.skip('e2e Alexander - Polkadot', () => {
|
||||
let api: Rpc;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
api = new Rpc(new WsProvider('wss://poc3-rpc.polkadot.io/'));
|
||||
});
|
||||
|
||||
it('subscribes to storage', (done) => {
|
||||
return (
|
||||
api.state
|
||||
.subscribeStorage(
|
||||
[
|
||||
[storage.system.accountNonce, randomAccount],
|
||||
[storage.session.currentIndex]
|
||||
],
|
||||
(data: StorageChangeSet) => {
|
||||
expect(data).toHaveLength(2);
|
||||
expect(data).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.any(BlockNumber),
|
||||
expect.any(Index)
|
||||
])
|
||||
);
|
||||
|
||||
done();
|
||||
}).then((subscriptionId: number) => {
|
||||
console.log('stoarge subscriptionId =', subscriptionId);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('retrieves a block by hash (krumme lanke #1)', () => {
|
||||
return api.chain
|
||||
.getBlock('0x627847bffdf5f3e01ac440d057dec6a37a12a6f329db7ef8367665574b76b5df')
|
||||
.then((block: SignedBlock) => {
|
||||
expect(block).toBeDefined();
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves a block by hash (krumme lanke #2)', () => {
|
||||
return api.chain
|
||||
.getBlock('0x53416d53a4b1dfcae9165a89d193608e4aa770414f02267f5b2c4015a2e66091')
|
||||
.then((block: SignedBlock) => {
|
||||
expect(block).toBeDefined();
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
});
|
||||
+12
-19
@@ -8,36 +8,29 @@ import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import Rpc from '../../src';
|
||||
|
||||
describe.skip('e2e basics', () => {
|
||||
let api: Rpc;
|
||||
let rpc: Rpc;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
api = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
|
||||
rpc = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
|
||||
});
|
||||
|
||||
it('retrieves the pending extrinsics', () => {
|
||||
return api.author
|
||||
it('retrieves the pending extrinsics', (done) => {
|
||||
rpc.author
|
||||
.pendingExtrinsics()
|
||||
.then((extrinsics: PendingExtrinsics) => {
|
||||
console.log('extrinsics', extrinsics);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
.subscribe((extrinsics: PendingExtrinsics) => {
|
||||
expect(extrinsics).toBeInstanceOf(PendingExtrinsics);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves the system properties', () => {
|
||||
return api.system
|
||||
it('retrieves the system properties', (done) => {
|
||||
rpc.system
|
||||
.properties()
|
||||
.then((properties: ChainProperties) => {
|
||||
.subscribe((properties: ChainProperties) => {
|
||||
expect(properties).toBeInstanceOf(ChainProperties);
|
||||
console.log('properties', properties);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
+11
-18
@@ -8,40 +8,33 @@ import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
import Rpc from '../../src';
|
||||
|
||||
describe.skip('e2e chain', () => {
|
||||
let api: Rpc;
|
||||
let rpc: Rpc;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
api = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
|
||||
rpc = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
|
||||
});
|
||||
|
||||
it('subscribes via subscribeNewHead', (done) => {
|
||||
let count: number = 0;
|
||||
|
||||
// tslint:disable-next-line
|
||||
api.chain
|
||||
.subscribeNewHead((header: Header) => {
|
||||
expect(header).toBeDefined();
|
||||
rpc.chain
|
||||
.subscribeNewHead()
|
||||
.subscribe((header: Header) => {
|
||||
expect(header).toBeInstanceOf(Header);
|
||||
|
||||
if (++count === 3) {
|
||||
done();
|
||||
}
|
||||
})
|
||||
.then((subscriptionId: number) => {
|
||||
console.log('newHead: subscriptionId =', subscriptionId);
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves the runtime version', () => {
|
||||
return api.chain
|
||||
it('retrieves the runtime version', (done) => {
|
||||
rpc.chain
|
||||
.getRuntimeVersion()
|
||||
.then((version: RuntimeVersion) => {
|
||||
console.error('version', version);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
.subscribe((version: RuntimeVersion) => {
|
||||
expect(version).toBeInstanceOf(RuntimeVersion);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
+45
-56
@@ -22,81 +22,66 @@ const CODE = '0x3a636f6465'; // :code
|
||||
const CHILD_STORAGE = '0x3a6368696c645f73746f726167653a'; // :child_storage:
|
||||
|
||||
describe.skip('e2e state', () => {
|
||||
let api: Rpc;
|
||||
let rpc: Rpc;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
api = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
|
||||
rpc = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
|
||||
});
|
||||
|
||||
it('getMetadata(): retrieves the wasm metadata', () => {
|
||||
return api.state
|
||||
it('getMetadata(): retrieves the wasm metadata', (done) => {
|
||||
rpc.state
|
||||
.getMetadata()
|
||||
.then((meta: Metadata) => {
|
||||
.subscribe((meta: Metadata) => {
|
||||
console.error(JSON.stringify(meta.toJSON()));
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('getKeys(): retrieves storage keys for ":code"', () => {
|
||||
return api.state
|
||||
it('getKeys(): retrieves storage keys for ":code"', (done) => {
|
||||
rpc.state
|
||||
.getKeys(CODE)
|
||||
.then((keys: Array<StorageKey>) => {
|
||||
.subscribe((keys: Array<StorageKey>) => {
|
||||
expect(keys.length).toEqual(1);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe('test-suite getStorage()', () => {
|
||||
it('retrieves code', () => {
|
||||
return api.state
|
||||
it('retrieves code', (done) => {
|
||||
rpc.state
|
||||
.getStorage([
|
||||
storage.substrate.code
|
||||
])
|
||||
.then((code: Bytes) => {
|
||||
.subscribe((code: Bytes) => {
|
||||
console.error(code.toHex().substr(0, 256), '...');
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves balances', () => {
|
||||
return api.state
|
||||
it('retrieves balances', (done) => {
|
||||
rpc.state
|
||||
.getStorage([
|
||||
storage.balances.freeBalance, ALICE
|
||||
])
|
||||
.then((balance: Balance) => {
|
||||
.subscribe((balance: Balance) => {
|
||||
console.error(balance);
|
||||
|
||||
expect(balance.isZero()).not.toEqual(true);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves timestamp', () => {
|
||||
return api.state
|
||||
it('retrieves timestamp', (done) => {
|
||||
rpc.state
|
||||
.getStorage([
|
||||
storage.timestamp.now
|
||||
])
|
||||
.then((moment: Moment) => {
|
||||
.subscribe((moment: Moment) => {
|
||||
console.error(moment);
|
||||
|
||||
expect(moment.toNumber()).not.toEqual(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -134,46 +119,50 @@ describe.skip('e2e state', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('getChildKeys(): retrieves :child_storage: keys for one deployed flipper contract', async () => {
|
||||
const storageKeys = await api.state.getKeys(CHILD_STORAGE);
|
||||
it('getChildKeys(): retrieves :child_storage: keys for one deployed flipper contract', async (done) => {
|
||||
const storageKeys = await rpc.state.getKeys(CHILD_STORAGE).toPromise();
|
||||
|
||||
return api.state
|
||||
rpc.state
|
||||
.getChildKeys(storageKeys[0], '0x')
|
||||
.then((keys: Array<StorageKey>) => {
|
||||
.subscribe((keys: Array<StorageKey>) => {
|
||||
expect(keys.length).toBeGreaterThanOrEqual(1);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('getChildStorage(): retrieves the default value of the flipper smart contract', async () => {
|
||||
const storageKeys = await api.state.getKeys(CHILD_STORAGE);
|
||||
const childStorageKeys = await api.state.getChildKeys(storageKeys[0], '0x');
|
||||
it('getChildStorage(): retrieves the default value of the flipper smart contract', async (done) => {
|
||||
const storageKeys = await rpc.state.getKeys(CHILD_STORAGE).toPromise();
|
||||
const childStorageKeys = await rpc.state.getChildKeys(storageKeys[0], '0x').toPromise();
|
||||
|
||||
return api.state
|
||||
rpc.state
|
||||
.getChildStorage(storageKeys[0], childStorageKeys[0])
|
||||
.then((storage: StorageData) => {
|
||||
.subscribe((storage: StorageData) => {
|
||||
expect(storage.toString()).toBe('0x00');
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('getChildStorageHash(): retrieves the Hash of the flipper smart contract', async () => {
|
||||
const storageKeys = await api.state.getKeys(CHILD_STORAGE);
|
||||
const childStorageKeys = await api.state.getChildKeys(storageKeys[0], '0x');
|
||||
it('getChildStorageHash(): retrieves the Hash of the flipper smart contract', async (done) => {
|
||||
const storageKeys = await rpc.state.getKeys(CHILD_STORAGE).toPromise();
|
||||
const childStorageKeys = await rpc.state.getChildKeys(storageKeys[0], '0x').toPromise();
|
||||
|
||||
return api.state
|
||||
rpc.state
|
||||
.getChildStorageHash(storageKeys[0], childStorageKeys[0])
|
||||
.then((storage: StorageData) => {
|
||||
.subscribe((storage: StorageData) => {
|
||||
expect(storage.toString()).toBe('0x03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314');
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('getChildStorageSize(): retrieves the size of the flipper smart contract', async () => {
|
||||
const storageKeys = await api.state.getKeys(CHILD_STORAGE);
|
||||
const childStorageKeys = await api.state.getChildKeys(storageKeys[0], '0x');
|
||||
it('getChildStorageSize(): retrieves the size of the flipper smart contract', async (done) => {
|
||||
const storageKeys = await rpc.state.getKeys(CHILD_STORAGE).toPromise();
|
||||
const childStorageKeys = await rpc.state.getChildKeys(storageKeys[0], '0x').toPromise();
|
||||
|
||||
return api.state
|
||||
rpc.state
|
||||
.getChildStorageSize(storageKeys[0], childStorageKeys[0])
|
||||
.then((storage: StorageData) => {
|
||||
.subscribe((storage: StorageData) => {
|
||||
expect(storage.toString()).toBe('1');
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
+5
-7
@@ -9,26 +9,24 @@ import storage from '@polkadot/storage/static';
|
||||
import Rpc from '../../src';
|
||||
|
||||
describe.skip('e2e subscriptions', () => {
|
||||
let api: Rpc;
|
||||
let rpc: Rpc;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
api = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
|
||||
rpc = new Rpc(new WsProvider('ws://127.0.0.1:9944'));
|
||||
});
|
||||
|
||||
it('retrieves current timestamp', (done) => {
|
||||
let count: number = 0;
|
||||
|
||||
return api.state
|
||||
.subscribeStorage([[storage.timestamp.now]], (data: StorageChangeSet) => {
|
||||
rpc.state
|
||||
.subscribeStorage([[storage.timestamp.now]])
|
||||
.subscribe((data: StorageChangeSet) => {
|
||||
expect(data).toBeDefined();
|
||||
|
||||
if (++count === 3) {
|
||||
done();
|
||||
}
|
||||
})
|
||||
.then((subscriptionId: number) => {
|
||||
console.log('newHead: subscriptionId =', subscriptionId);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user