First stage renames, rpc-{core,provider,rx} (#220)
* Docs renames (& removal for re-gen) * Rename api, api-provider & api-rx * Apoi -> Rpc, RxApi -> RpcRx (classes) * Add .nodoc * Bump version * Link updates (summary) * Cleanup deleted (master version) * Deleted re-instated * More... ;) * Types... * Revert .nodoc
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
ISC License (ISC)
|
||||
|
||||
Copyright 2017-2018 @polkadot/rpc-core authors & contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
@@ -0,0 +1,76 @@
|
||||
[](https://polkadot.js.org)
|
||||

|
||||
[](https://github.com/Flet/semistandard)
|
||||
[](https://www.npmjs.com/package/@polkadot/api)
|
||||
[](https://travis-ci.org/polkadot-js/api)
|
||||
[](https://codeclimate.com/github/polkadot-js/api/maintainability)
|
||||
[](https://coveralls.io/github/polkadot-js/api?branch=master)
|
||||
[](https://david-dm.org/polkadot-js/api?path=package/rpc-core)
|
||||
[](https://david-dm.org/polkadot-js/api?path=package/rpc-core#info=devDependencies)
|
||||
|
||||
# @polkadot/api
|
||||
|
||||
This library provides a clean wrapper around all the methods exposed by a Polkadot network client.
|
||||
|
||||
## Usage
|
||||
|
||||
Installation -
|
||||
|
||||
```
|
||||
npm install --save @polkadot/rpc-core
|
||||
```
|
||||
|
||||
Initialisation -
|
||||
|
||||
```js
|
||||
import Api from '@polkadot/rpc-core';
|
||||
import WsProvider from '@polkadot/rpc-provider/ws';
|
||||
|
||||
const provider = new WsProvider('http://127.0.0.1:9944');
|
||||
const api = new Api(provider);
|
||||
```
|
||||
|
||||
Making calls -
|
||||
|
||||
```js
|
||||
api.chain
|
||||
.getHeader('0x1234567890')
|
||||
.then((header) => console.log(header))
|
||||
.catch((error) => console.error(error));
|
||||
```
|
||||
|
||||
Retrieving the best block (once-off) -
|
||||
|
||||
```js
|
||||
api.chain
|
||||
.getHead()
|
||||
.then((headerHash) => {
|
||||
return api.chain.getHeader(headerHash);
|
||||
})
|
||||
.then((header) => {
|
||||
console.log(`best #${header.number.toString()}`);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('error:', error);
|
||||
});
|
||||
```
|
||||
|
||||
Retrieving best header via subscription -
|
||||
|
||||
```js
|
||||
api.chain
|
||||
.newHead((error, header) => {
|
||||
if (error) {
|
||||
console.error('error:', error);
|
||||
}
|
||||
|
||||
console.log(`best #${header.number.toString()}`);
|
||||
})
|
||||
.then((subscriptionId) => {
|
||||
// id for the subscription, can unsubscribe via
|
||||
// api.chain.newHead.unsubscribe(subscriptionId)
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('error subscribing:', error);
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@polkadot/rpc-core",
|
||||
"version": "0.31.0",
|
||||
"description": "A JavaScript wrapper for the Polkadot JsonRPC interface",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
"Polkadot",
|
||||
"JsonRPC"
|
||||
],
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"maintainers": [
|
||||
"Jaco Greeff <jacogr@gmail.com>"
|
||||
],
|
||||
"contributors": [],
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=6.4"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"registry": "https://registry.npmjs.org"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/polkadot-js/api.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/polkadot-js/api/issues"
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/api/tree/master/packages/rpc-core#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.0.0",
|
||||
"@polkadot/jsonrpc": "^0.31.0",
|
||||
"@polkadot/rpc-provider": "^0.31.0",
|
||||
"@polkadot/util": "^0.30.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-core authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import storage from '@polkadot/storage/static';
|
||||
|
||||
import Api from './index';
|
||||
|
||||
const ADDR_ONE = '5EhmTa7fL6SdjgKXo9g6hetR6nHnRAmrtisoGFWEESjzECtY';
|
||||
const ADDR_TWO = '5FjbQAHSptRU4Q7Py6zDsRnE7UkpZikJVg5nm1tmu3WuZXKd';
|
||||
|
||||
const ENC_ONE = '0x24988a82b3bbaae58680bc9de5dea5aa';
|
||||
const ENC_TWO = '0xdb190750267d8849c35316ec9d342111';
|
||||
|
||||
describe('formatting', () => {
|
||||
let api;
|
||||
let provider;
|
||||
|
||||
beforeEach(() => {
|
||||
provider = {
|
||||
send: jest.fn((method, params) =>
|
||||
Promise.resolve('0x0102')
|
||||
),
|
||||
subscribe: jest.fn((type, method, params, subscription) =>
|
||||
subscription(null, {
|
||||
block: '0x1234',
|
||||
changes: [
|
||||
[ENC_ONE, '0x0102'],
|
||||
[ENC_TWO, '0x0201']
|
||||
]
|
||||
})
|
||||
)
|
||||
};
|
||||
api = new Api(provider);
|
||||
});
|
||||
|
||||
it('encodes key (with params), decoding response', () => {
|
||||
return api.state
|
||||
.getStorage(
|
||||
[storage.balances.freeBalance, ADDR_ONE]
|
||||
)
|
||||
.then((value) => {
|
||||
expect(
|
||||
provider.send
|
||||
).toHaveBeenCalledWith(
|
||||
'state_getStorage',
|
||||
[ENC_ONE]
|
||||
);
|
||||
expect(value.toNumber()).toEqual(513);
|
||||
});
|
||||
});
|
||||
|
||||
it('encodes multiple keys, decoding multiple results', (done) => {
|
||||
api.state
|
||||
.storage(
|
||||
[
|
||||
[storage.balances.freeBalance, ADDR_ONE],
|
||||
[storage.balances.freeBalance, ADDR_TWO]
|
||||
],
|
||||
(error, value) => {
|
||||
console.error(value);
|
||||
|
||||
expect(
|
||||
provider.subscribe
|
||||
).toHaveBeenCalledWith(
|
||||
'state_storage',
|
||||
'state_subscribeStorage',
|
||||
[[ENC_ONE, ENC_TWO]],
|
||||
expect.anything()
|
||||
);
|
||||
expect(
|
||||
value.map((balance) =>
|
||||
balance.toNumber()
|
||||
)
|
||||
).toEqual([513, 258]);
|
||||
|
||||
done(error);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-core authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Api from './index';
|
||||
|
||||
describe('Api', () => {
|
||||
let api;
|
||||
let provider;
|
||||
let sendSpy;
|
||||
|
||||
beforeEach(() => {
|
||||
provider = {
|
||||
send: (method, params) => {
|
||||
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({})
|
||||
).toThrow(/Expected Provider/);
|
||||
});
|
||||
|
||||
it('sets up the chain interface', () => {
|
||||
expect(api.chain).toBeDefined();
|
||||
});
|
||||
|
||||
it('sets up the state interface', () => {
|
||||
expect(api.state).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-core authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface, ProviderInterface$Callback } from '@polkadot/rpc-provider/types';
|
||||
import { RpcSection, RpcMethod } from '@polkadot/jsonrpc/types';
|
||||
import { RpcInterface, RpcInterface$Section, RpcInterface$Section$Method } from './types';
|
||||
|
||||
import interfaces from '@polkadot/jsonrpc/index';
|
||||
import extrinsicsFromMeta from '@polkadot/extrinsics/fromMetadata';
|
||||
import { Base, Vector, createType } from '@polkadot/types/codec';
|
||||
import { Method, StorageChangeSet, StorageKey } from '@polkadot/types/index';
|
||||
import assert from '@polkadot/util/assert';
|
||||
import ExtError from '@polkadot/util/ext/error';
|
||||
import isFunction from '@polkadot/util/is/function';
|
||||
|
||||
/**
|
||||
* @name Rpc
|
||||
* @summary The API may use a HTTP or WebSockets provider.
|
||||
* @description It allows for querying a Polkadot Client Node.
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import Api 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);
|
||||
* ```
|
||||
*/
|
||||
export default class Rpc implements RpcInterface {
|
||||
private _provider: ProviderInterface;
|
||||
readonly author: RpcInterface$Section;
|
||||
readonly chain: RpcInterface$Section;
|
||||
readonly state: RpcInterface$Section;
|
||||
readonly system: RpcInterface$Section;
|
||||
|
||||
/**
|
||||
* @constructor
|
||||
* Default constructor for the Api Object
|
||||
* @param {ProviderInterface} provider An API provider using HTTP or WebSocket
|
||||
*/
|
||||
constructor (provider: ProviderInterface) {
|
||||
assert(provider && isFunction(provider.send), 'Expected Provider to API create');
|
||||
|
||||
this._provider = provider;
|
||||
|
||||
this.author = this.createInterface(interfaces.author);
|
||||
this.chain = this.createInterface(interfaces.chain);
|
||||
this.state = this.createInterface(interfaces.state);
|
||||
this.system = this.createInterface(interfaces.system);
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* @name signature
|
||||
* @summary Returns a string representation of the method with inputs and outputs.
|
||||
* @description
|
||||
* Formats the name, inputs and outputs into a human-readable string. This contains the input parameter names input types and output type.
|
||||
*
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import Api from '@polkadot/rpc-core';
|
||||
*
|
||||
* Api.signature({ name: 'test_method', params: [ { name: 'dest', type: 'Address' } ], type: 'Address' }); // => test_method (dest: Address): Address
|
||||
* ```
|
||||
*/
|
||||
static signature ({ method, params, type }: RpcMethod): string {
|
||||
const inputs = params.map(({ name, type }) =>
|
||||
`${name}: ${type}`
|
||||
).join(', ');
|
||||
|
||||
return `${method} (${inputs}): ${type}`;
|
||||
}
|
||||
|
||||
private init (): void {
|
||||
// load metadata and and setup the Method static so we are able to use
|
||||
// decoding at any point going forward. This is not great, but the best
|
||||
// we can come up with for now
|
||||
this.state
|
||||
.getMetadata()
|
||||
.then((metadata) => {
|
||||
Method.injectExtrinsics(
|
||||
extrinsicsFromMeta(metadata)
|
||||
);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Unable to retrieve metadata', error);
|
||||
});
|
||||
}
|
||||
|
||||
private createInterface ({ methods, section }: RpcSection): RpcInterface$Section {
|
||||
return Object
|
||||
.keys(methods)
|
||||
.reduce((exposed, method) => {
|
||||
const rpcName = `${section}_${method}`;
|
||||
const def = methods[method];
|
||||
|
||||
exposed[method] = def.isSubscription
|
||||
? this.createMethodSubscribe(rpcName, def)
|
||||
: this.createMethodSend(rpcName, def);
|
||||
|
||||
return exposed;
|
||||
}, {} as RpcInterface$Section);
|
||||
}
|
||||
|
||||
private createMethodSend (rpcName: string, method: RpcMethod): RpcInterface$Section$Method {
|
||||
const call = async (...values: Array<any>): Promise<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}`;
|
||||
|
||||
console.error(message, error);
|
||||
|
||||
throw new ExtError(message, (error as ExtError).code, undefined);
|
||||
}
|
||||
};
|
||||
|
||||
return call as RpcInterface$Section$Method;
|
||||
}
|
||||
|
||||
private createMethodSubscribe (rpcName: string, method: RpcMethod): RpcInterface$Section$Method {
|
||||
const unsubscribe = (subscriptionId: any): Promise<any> =>
|
||||
this._provider.unsubscribe(rpcName, method.subscribe[1], subscriptionId);
|
||||
const _call = async (...values: Array<any>): Promise<any> => {
|
||||
try {
|
||||
const cb: ProviderInterface$Callback = values.pop();
|
||||
|
||||
assert(isFunction(cb), `Expected callback in last position of params`);
|
||||
|
||||
const params = this.formatInputs(method, values);
|
||||
const paramsJson = params.map((param) => param.toJSON());
|
||||
const update = (error: Error | null, result?: any) => {
|
||||
cb(error, this.formatOutput(method, params, result));
|
||||
};
|
||||
|
||||
return this._provider.subscribe(rpcName, method.subscribe[0], paramsJson, update);
|
||||
} catch (error) {
|
||||
const message = `${Rpc.signature(method)}:: ${error.message}`;
|
||||
|
||||
console.error(message, error);
|
||||
|
||||
throw new ExtError(message, (error as ExtError).code, undefined);
|
||||
}
|
||||
};
|
||||
|
||||
const call = _call as RpcInterface$Section$Method;
|
||||
|
||||
call.unsubscribe = unsubscribe;
|
||||
|
||||
return call;
|
||||
}
|
||||
|
||||
private formatInputs (method: RpcMethod, inputs: Array<any>): Array<Base> {
|
||||
assert(method.params.length === inputs.length, `Expected ${method.params.length} parameters, ${inputs.length} found instead`);
|
||||
|
||||
return method.params.map(({ type }, index) =>
|
||||
createType(type as string, inputs[index])
|
||||
);
|
||||
}
|
||||
|
||||
private formatOutput (method: RpcMethod, params: Array<Base>, result?: any): Base | Array<Base | null | undefined> {
|
||||
const base = createType(method.type as string).fromJSON(result);
|
||||
|
||||
if (method.type === 'StorageData') {
|
||||
// single return value (via state.getStorage), decode the value based on the
|
||||
// outputType that we have specified
|
||||
const type = (params[0] as StorageKey).outputType;
|
||||
|
||||
if (type) {
|
||||
return createType(type, base.raw);
|
||||
}
|
||||
} else if (method.type === 'StorageChangeSet') {
|
||||
// multiple return values (via state.storage subscription), decode the values
|
||||
// one at a time, all based on the query types. Three values can be returned -
|
||||
// - Base - There is a valid value, non-empty
|
||||
// - null - The storage key is empty (but in the resultset)
|
||||
// - undefined - The storage value is not in the resultset
|
||||
return (params[0] as Vector<StorageKey>).reduce((result, _key: StorageKey) => {
|
||||
const type = _key.outputType;
|
||||
|
||||
if (!type) {
|
||||
throw new Error('Cannot format StorageChangeSet, output type missing for key');
|
||||
}
|
||||
|
||||
// see if we have a result value for this specific key
|
||||
const key = _key.toHex();
|
||||
const item = (base as StorageChangeSet).changes.find((item) =>
|
||||
item.key.toHex() === key
|
||||
);
|
||||
|
||||
// if we don't have a value, do not fill in the entry, it will be up to the
|
||||
// caller to sort this out, either ignoring or having a cache for older values
|
||||
result.push(
|
||||
!item
|
||||
? undefined
|
||||
: (
|
||||
item.value.isEmpty
|
||||
? null
|
||||
: createType(type, item.value.value)
|
||||
)
|
||||
);
|
||||
|
||||
return result;
|
||||
}, [] as Array<Base | null | undefined>);
|
||||
}
|
||||
|
||||
return base;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-core authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Api from './index';
|
||||
|
||||
describe('methodSend', () => {
|
||||
let api;
|
||||
let methods;
|
||||
let provider;
|
||||
|
||||
beforeEach(() => {
|
||||
methods = {
|
||||
blah: {
|
||||
method: 'blah',
|
||||
params: [
|
||||
{ name: 'foo', type: 'Bytes' }
|
||||
],
|
||||
type: 'Bytes'
|
||||
},
|
||||
bleh: {
|
||||
method: 'bleh',
|
||||
params: [],
|
||||
type: 'Bytes'
|
||||
}
|
||||
};
|
||||
|
||||
provider = {
|
||||
send: jest.fn((method, params) => {
|
||||
return Promise.resolve(params[0]);
|
||||
})
|
||||
};
|
||||
|
||||
api = new Api(provider);
|
||||
});
|
||||
|
||||
it('wraps errors with the call signature', () => {
|
||||
const method = api.createMethodSend('test_blah', methods.blah);
|
||||
|
||||
return method().catch((error) => {
|
||||
expect(error.message).toMatch(/blah \(foo: Bytes\): Bytes/);
|
||||
});
|
||||
});
|
||||
|
||||
it('checks for mismatched parameters', () => {
|
||||
const method = api.createMethodSend('test_bleh', methods.bleh);
|
||||
|
||||
return method(1).catch((error) => {
|
||||
expect(error.message).toMatch(/parameters, 1 found instead/);
|
||||
});
|
||||
});
|
||||
|
||||
it('calls the provider with the correct parameters', () => {
|
||||
const method = api.createMethodSend('test_blah', methods.blah);
|
||||
|
||||
return method(new Uint8Array([0x12, 0x34])).then(() => {
|
||||
expect(provider.send).toHaveBeenCalledWith('test_blah', ['0x1234']);
|
||||
});
|
||||
});
|
||||
});
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-core authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import interfaces from '@polkadot/jsonrpc/index';
|
||||
|
||||
export interface RpcInterface$Section$Method {
|
||||
(...params: Array<any>): Promise<any>;
|
||||
|
||||
subscription: string;
|
||||
unsubscribe: (id: number) => Promise<any>;
|
||||
}
|
||||
|
||||
export type RpcInterface$Section = {
|
||||
[index: string]: RpcInterface$Section$Method
|
||||
};
|
||||
|
||||
export type RpcInterface = {
|
||||
readonly [key in keyof typeof interfaces]: RpcInterface$Section
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Copyright 2017-2018 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Ws from '@polkadot/rpc-provider/ws';
|
||||
|
||||
import Api from '../../src';
|
||||
|
||||
describe.skip('e2e basics', () => {
|
||||
let api;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
api = new Api(new Ws('ws://127.0.0.1:9944'));
|
||||
});
|
||||
|
||||
it('retrieves the pending extrinsics', () => {
|
||||
return api.author
|
||||
.pendingExtrinsics()
|
||||
.then((extrinsics) => {
|
||||
console.error('extrinsics', extrinsics);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
// Copyright 2017-2018 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Ws from '@polkadot/rpc-provider/ws';
|
||||
|
||||
import Api from '../../src';
|
||||
|
||||
describe.skip('e2e chain', () => {
|
||||
let api;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
api = new Api(new Ws('ws://127.0.0.1:9944'));
|
||||
});
|
||||
|
||||
it('subscribes to chain_newHead', (done) => {
|
||||
let count = 0;
|
||||
|
||||
// tslint:disable-next-line
|
||||
api.chain
|
||||
.newHead((error, data) => {
|
||||
if (error) {
|
||||
return done(error);
|
||||
}
|
||||
|
||||
expect(data).toBeDefined();
|
||||
|
||||
if (++count === 3) {
|
||||
done();
|
||||
}
|
||||
})
|
||||
.then((subscriptionId) => {
|
||||
console.log('newHead: subscriptionId =', subscriptionId);
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves the runtime version', () => {
|
||||
return api.chain
|
||||
.getRuntimeVersion()
|
||||
.then((version) => {
|
||||
console.error('version', version);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// Copyright 2017-2018 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import storage from '@polkadot/storage';
|
||||
import Ws from '@polkadot/rpc-provider/ws';
|
||||
|
||||
import Api from '../../src';
|
||||
|
||||
describe.skip('e2e krumme lanke', () => {
|
||||
let api;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
api = new Api(new Ws('ws://127.0.0.1:9944'));
|
||||
});
|
||||
|
||||
it('subscribes to storage', (done) => {
|
||||
api.state
|
||||
.subscribeStorage(
|
||||
[
|
||||
[storage.system.accountNonce, '5Ejbye9R8ygByQPrDSasaUid1munedPZUmg4f118HGmtodGp'],
|
||||
[storage.balances.freeBalance, '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7']
|
||||
],
|
||||
(error, data) => {
|
||||
if (error) {
|
||||
return done(error);
|
||||
}
|
||||
|
||||
expect(data).toHaveLength(2);
|
||||
expect(data[0].toNumber()).toEqual(0);
|
||||
expect(data[1].toNumber()).not.toEqual(0);
|
||||
|
||||
done();
|
||||
}
|
||||
)
|
||||
.then((subscriptionId) => {
|
||||
console.log('newHead: subscriptionId =', subscriptionId);
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves a block by hash (krumme lanke #1)', () => {
|
||||
return api.chain
|
||||
.getBlock('0x627847bffdf5f3e01ac440d057dec6a37a12a6f329db7ef8367665574b76b5df')
|
||||
.then((block) => {
|
||||
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) => {
|
||||
expect(block).toBeDefined();
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
// Copyright 2017-2018 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Ws from '@polkadot/rpc-provider/ws';
|
||||
import storage from '@polkadot/storage/static';
|
||||
|
||||
import Api from '../../src';
|
||||
|
||||
const ALICE = '5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDtZ';
|
||||
|
||||
describe.skip('e2e state', () => {
|
||||
let api;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
api = new Api(new Ws('ws://127.0.0.1:9944'));
|
||||
});
|
||||
|
||||
it('retrieves code', () => {
|
||||
return api.state
|
||||
.getStorage([
|
||||
storage.substrate.code
|
||||
])
|
||||
.then((code) => {
|
||||
console.error(code.toHex().substr(0, 256), '...');
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves the wasm metadata', () => {
|
||||
return api.state
|
||||
.getMetadata()
|
||||
.then((meta) => {
|
||||
console.error(JSON.stringify(meta.toJSON()));
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves balances', () => {
|
||||
return api.state
|
||||
.getStorage([
|
||||
storage.balances.freeBalance, ALICE
|
||||
])
|
||||
.then((balance) => {
|
||||
console.error(balance);
|
||||
|
||||
expect(balance.toBn().isZero()).not.toEqual(true);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
|
||||
it('retrieves timestamp', () => {
|
||||
return api.state
|
||||
.getStorage([
|
||||
storage.timestamp.now
|
||||
])
|
||||
.then((moment) => {
|
||||
console.error(moment);
|
||||
|
||||
expect(moment.toNumber()).not.toEqual(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
// Copyright 2017-2018 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Ws from '@polkadot/rpc-provider/ws';
|
||||
import storage from '@polkadot/storage/static';
|
||||
|
||||
import Api from '../../src';
|
||||
|
||||
describe.skip('e2e subscriptions', () => {
|
||||
let api;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
api = new Api(new Ws('ws://127.0.0.1:9944'));
|
||||
});
|
||||
|
||||
it('retrieves current timestamp', (done) => {
|
||||
let count = 0;
|
||||
|
||||
return api.state
|
||||
.storage([[storage.timestamp.now]], (error, data) => {
|
||||
if (error) {
|
||||
return done(error);
|
||||
}
|
||||
|
||||
expect(data).toBeDefined();
|
||||
|
||||
if (++count === 3) {
|
||||
done();
|
||||
}
|
||||
})
|
||||
.then((subscriptionId) => {
|
||||
console.log('newHead: subscriptionId =', subscriptionId);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import nock from 'nock';
|
||||
|
||||
const TEST_HTTP_URL = 'http://localhost:9944';
|
||||
|
||||
function mockHttp (requests: any[]) {
|
||||
nock.cleanAll();
|
||||
|
||||
return requests.reduce((scope, request: any, index: number) => {
|
||||
return scope
|
||||
.post('/')
|
||||
.reply(request.code || 200, (uri: string, body: { id: string }) => {
|
||||
scope.body = scope.body || {};
|
||||
scope.body[request.method] = body;
|
||||
|
||||
return Object.assign({ id: body.id, jsonrpc: '2.0' }, request.reply || {});
|
||||
});
|
||||
}, nock(TEST_HTTP_URL));
|
||||
}
|
||||
|
||||
export {
|
||||
TEST_HTTP_URL,
|
||||
mockHttp
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { Server } from 'mock-socket';
|
||||
|
||||
const TEST_WS_URL = 'ws://localhost:9955';
|
||||
|
||||
let server: Server;
|
||||
|
||||
type ErrorDef = {
|
||||
id: number,
|
||||
error: {
|
||||
code: number,
|
||||
message: string
|
||||
}
|
||||
};
|
||||
|
||||
type ReplyDef = {
|
||||
id: number,
|
||||
reply: {
|
||||
result: any
|
||||
}
|
||||
};
|
||||
|
||||
function createError ({ id, error: { code, message } }: ErrorDef) {
|
||||
return {
|
||||
id,
|
||||
jsonrpc: '2.0',
|
||||
error: {
|
||||
code,
|
||||
message
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function createReply ({ id, reply: { result } }: ReplyDef) {
|
||||
return {
|
||||
id,
|
||||
jsonrpc: '2.0',
|
||||
result
|
||||
};
|
||||
}
|
||||
|
||||
function mockWs (requests: Array<{ method: string }>) {
|
||||
server = new Server(TEST_WS_URL);
|
||||
|
||||
let requestCount = 0;
|
||||
const scope: { body: { [index: string]: {} }, requests: number, server: Server, done: any } = {
|
||||
body: {},
|
||||
requests: 0,
|
||||
server,
|
||||
done: () =>
|
||||
server.stop(() => {
|
||||
// ignore
|
||||
})
|
||||
};
|
||||
|
||||
server.on('connection', (socket) => {
|
||||
// @ts-ignore definitions are wrong, this is 'on', not 'onmessage'
|
||||
socket.on('message', (body: {}) => {
|
||||
const request = requests[requestCount];
|
||||
// @ts-ignore Yes, SHOULD be fixed, this is a mess
|
||||
const response = request.error
|
||||
// @ts-ignore Yes, SHOULD be fixed, this is a mess
|
||||
? createError(request)
|
||||
// @ts-ignore Yes, SHOULD be fixed, this is a mess
|
||||
: createReply(request);
|
||||
|
||||
scope.body[request.method] = body;
|
||||
requestCount++;
|
||||
|
||||
socket.send(JSON.stringify(response));
|
||||
});
|
||||
});
|
||||
|
||||
return scope;
|
||||
}
|
||||
|
||||
export {
|
||||
TEST_WS_URL,
|
||||
mockWs
|
||||
};
|
||||
Reference in New Issue
Block a user