Initial add
This commit is contained in:
+71
@@ -0,0 +1,71 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
import type { InterfaceDefinition } from '@polkadot/jsonrpc/src/types';
|
||||
import type { ApiInterface } from './types';
|
||||
import type { ProviderInterface } from './provider/types';
|
||||
|
||||
const interfaces = require('@polkadot/jsonrpc');
|
||||
const { callSignature } = require('@polkadot/jsonrpc/lib/util');
|
||||
const { formatInputs, formatOutput } = require('./format');
|
||||
const { HttpProvider } = require('./provider');
|
||||
const { isFunction } = require('./util/is');
|
||||
|
||||
module.exports = class Api implements ApiInterface {
|
||||
_provider: ProviderInterface;
|
||||
_chainInterface: any = null;
|
||||
_stateInterface: any = null;
|
||||
|
||||
constructor (provider: ProviderInterface) {
|
||||
if (!provider) {
|
||||
throw new Error('Instantiate the Api with `new Api(new Provider(...))`');
|
||||
}
|
||||
|
||||
if (!isFunction(provider.send)) {
|
||||
throw new Error('Supplied provider does not expose send method');
|
||||
}
|
||||
|
||||
this._provider = provider;
|
||||
|
||||
this._chainInterface = this._createInterface(interfaces, 'chain');
|
||||
this._stateInterface = this._createInterface(interfaces, 'state');
|
||||
}
|
||||
|
||||
get chain (): any {
|
||||
return this._chainInterface;
|
||||
}
|
||||
|
||||
get state (): any {
|
||||
return this._stateInterface;
|
||||
}
|
||||
|
||||
_createInterface (definitions: { [string]: InterfaceDefinition }, section: string): any {
|
||||
const definition = definitions[section];
|
||||
|
||||
return Object
|
||||
.keys(definition.methods)
|
||||
.reduce((container, method: string) => {
|
||||
const { inputs, output } = definition.methods[method];
|
||||
const rpcName = `${section}_${method}`;
|
||||
|
||||
container[method] = async (..._params: Array<any>): any => {
|
||||
try {
|
||||
if (inputs.length !== _params.length) {
|
||||
throw new Error(`${inputs.length} params expected, found ${_params.length} instead`);
|
||||
}
|
||||
|
||||
const params = formatInputs(inputs, _params);
|
||||
const result = await this._provider.send(rpcName, params);
|
||||
|
||||
return formatOutput(output, result);
|
||||
} catch (error) {
|
||||
throw new Error(`${callSignature(rpcName, inputs, output)}:: ${error.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
return container;
|
||||
}, {});
|
||||
}
|
||||
|
||||
static HttpProvider = HttpProvider;
|
||||
};
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
/* eslint-disable no-unused-expressions */
|
||||
|
||||
const sinon = require('sinon');
|
||||
|
||||
const { isFunction } = require('./util/is');
|
||||
|
||||
const Api = require('./api');
|
||||
|
||||
describe('Api', () => {
|
||||
let api;
|
||||
let provider;
|
||||
|
||||
beforeEach(() => {
|
||||
provider = {
|
||||
send: (method, params) => {
|
||||
return Promise.resolve(params[0]);
|
||||
}
|
||||
};
|
||||
sinon.spy(provider, 'send');
|
||||
api = new Api(provider);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
provider.send.restore();
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('requires a provider', () => {
|
||||
expect(
|
||||
() => new Api()
|
||||
).to.throw(/Instantiate the Api/);
|
||||
});
|
||||
|
||||
it('requires a provider with a send method', () => {
|
||||
expect(
|
||||
() => new Api({})
|
||||
).to.throw(/does not expose send/);
|
||||
});
|
||||
|
||||
it('sets up the chain interface', () => {
|
||||
expect(api.chain).to.be.ok;
|
||||
});
|
||||
|
||||
it('sets up the state interface', () => {
|
||||
expect(api.state).to.be.ok;
|
||||
});
|
||||
});
|
||||
|
||||
describe('_createInterface', () => {
|
||||
let container;
|
||||
|
||||
beforeEach(() => {
|
||||
container = api._createInterface({
|
||||
test: {
|
||||
methods: {
|
||||
blah: {
|
||||
inputs: [
|
||||
{ name: 'foo', type: 'Address' }
|
||||
],
|
||||
output: { type: 'Address' }
|
||||
},
|
||||
bleh: {
|
||||
inputs: [],
|
||||
output: { type: 'Address' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 'test');
|
||||
});
|
||||
|
||||
describe('method expansion', () => {
|
||||
it('adds the specified methods to the interface', () => {
|
||||
expect(Object.keys(container)).to.deep.equal(['blah', 'bleh']);
|
||||
});
|
||||
|
||||
it('had function calls for the attached methods', () => {
|
||||
expect(isFunction(container.blah)).to.be.true;
|
||||
expect(isFunction(container.bleh)).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe('calling', () => {
|
||||
it('wraps errors with the call signature', () => {
|
||||
return container
|
||||
.blah()
|
||||
.catch((error) => {
|
||||
expect(error).to.match(/test_blah\(foo: Address\) => Address/);
|
||||
});
|
||||
});
|
||||
|
||||
it('checks for mismatched parameters', () => {
|
||||
return container
|
||||
.bleh(1)
|
||||
.catch((error) => {
|
||||
expect(error).to.match(/0 params expected, found 1 instead/);
|
||||
});
|
||||
});
|
||||
|
||||
it('calls the provider with the correct parameters', () => {
|
||||
return container
|
||||
.blah('0x123')
|
||||
.then(() => {
|
||||
expect(provider.send).to.have.been.calledWith('test_blah', [
|
||||
'0x0000000000000000000000000000000000000123'
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('static', () => {
|
||||
it('exports Api.HttpProvider', () => {
|
||||
expect(Api.HttpProvider).to.be.ok;
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
const formatInputs = require('./input');
|
||||
const formatOutput = require('./output');
|
||||
|
||||
module.exports = {
|
||||
formatInputs,
|
||||
formatOutput
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
const { formatH160 } = require('./hex');
|
||||
|
||||
// TODO: Currently the format assumes 160-bit values (like Ethereum)
|
||||
// this will probably change along the way as things get firmed up
|
||||
module.exports = function format (value: ?string): string {
|
||||
return formatH160(value);
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
const format = require('./address');
|
||||
|
||||
describe('format/input/address', () => {
|
||||
describe('format', () => {
|
||||
it('pads to H160 value', () => {
|
||||
expect(
|
||||
format('0x1234567890')
|
||||
).to.equal('0x0000000000000000000000000000001234567890');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
const { addHexPrefix, hasHexPrefix, stripHexPrefix } = require('../../util/hex');
|
||||
|
||||
const H64_ZERO: string = '00000000000000000000000000000000';
|
||||
const H128_ZERO: string = `${H64_ZERO}${H64_ZERO}`;
|
||||
const H256_ZERO: string = `${H128_ZERO}${H128_ZERO}`;
|
||||
// const H512_ZERO: string = `${H256_ZERO}${H256_ZERO}`;
|
||||
|
||||
function leftHexPad (value: ?string, bitLength: number): string {
|
||||
const length = 2 * bitLength / 8;
|
||||
|
||||
if (hasHexPrefix(value)) {
|
||||
value = stripHexPrefix(value);
|
||||
}
|
||||
|
||||
return addHexPrefix(`${H256_ZERO}${value || ''}`.slice(-length));
|
||||
}
|
||||
|
||||
function formatH160 (value: ?string): string {
|
||||
return leftHexPad(value, 160);
|
||||
}
|
||||
|
||||
function formatH256 (value: ?string): string {
|
||||
return leftHexPad(value, 256);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
leftHexPad,
|
||||
formatH160,
|
||||
formatH256
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
const { leftHexPad, formatH160, formatH256 } = require('./hex');
|
||||
|
||||
describe('format/input/hex', () => {
|
||||
describe('leftHexPad', () => {
|
||||
it('padds to the required length', () => {
|
||||
expect(
|
||||
leftHexPad('0x123', 16)
|
||||
).to.equal('0x0123');
|
||||
});
|
||||
|
||||
it('padds to the required length (no prefix)', () => {
|
||||
expect(
|
||||
leftHexPad('123', 16)
|
||||
).to.equal('0x0123');
|
||||
});
|
||||
|
||||
it('pads null values correctly', () => {
|
||||
expect(
|
||||
leftHexPad(null, 16)
|
||||
).to.equal('0x0000');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatH160', () => {
|
||||
it('pads to 40 bytes', () => {
|
||||
expect(
|
||||
formatH160('0x1234567890')
|
||||
).to.equal('0x0000000000000000000000000000001234567890');
|
||||
});
|
||||
|
||||
it('pads null values correctly', () => {
|
||||
expect(
|
||||
formatH160(null)
|
||||
).to.match(/^0x(00){20,}$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatH256', () => {
|
||||
it('pads to 64 bytes', () => {
|
||||
expect(
|
||||
formatH256('0x1234567890')
|
||||
).to.equal('0x0000000000000000000000000000000000000000000000000000001234567890');
|
||||
});
|
||||
|
||||
it('pads null values correctly', () => {
|
||||
expect(
|
||||
formatH256(null)
|
||||
).to.match(/^0x(00){32,}$/);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
import type { FormatInputType, InterfaceInputType } from '@polkadot/jsonrpc/src/types';
|
||||
import type { FormatterFunction } from '../types';
|
||||
|
||||
const formatAddress = require('./address');
|
||||
const { formatH256 } = require('./hex');
|
||||
const formatNoop = require('../noop');
|
||||
const util = require('../util');
|
||||
|
||||
const formatters: { [FormatInputType]: FormatterFunction } = {
|
||||
'Address': formatAddress,
|
||||
'CallData': formatNoop,
|
||||
'H256': formatH256,
|
||||
'HeaderHash': formatH256,
|
||||
'String': formatNoop
|
||||
};
|
||||
|
||||
module.exports = function format (inputs: Array<InterfaceInputType>, values: Array<any>): Array<any> {
|
||||
const types = inputs.map(({ type }) => type);
|
||||
|
||||
return util.formatArray(formatters, types, values);
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
const format = require('./index');
|
||||
|
||||
describe('format/input', () => {
|
||||
describe('format', () => {
|
||||
it('formats each value in an array', () => {
|
||||
expect(
|
||||
format(
|
||||
[
|
||||
{ name: 'foo', type: 'Address' },
|
||||
{ name: 'bar', type: 'H256' }
|
||||
],
|
||||
['0x1234', '0xabcd']
|
||||
)
|
||||
).to.deep.equal([
|
||||
'0x0000000000000000000000000000000000001234',
|
||||
'0x000000000000000000000000000000000000000000000000000000000000abcd'
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
module.exports = function format (value: any): any {
|
||||
return value;
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
const format = require('./noop');
|
||||
|
||||
describe('format/noop', () => {
|
||||
it('returns input value as output value', () => {
|
||||
const input = { 'some': 'object' };
|
||||
|
||||
expect(
|
||||
format(input)
|
||||
).to.equal(input);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
import type { FormatOutputType, InterfaceOutputType } from '@polkadot/jsonrpc/src/types';
|
||||
import type { FormatterFunction } from '../types';
|
||||
|
||||
const formatNoop = require('../noop');
|
||||
const util = require('../util');
|
||||
|
||||
const formatters: { [FormatOutputType]: FormatterFunction } = {
|
||||
'Header': formatNoop,
|
||||
'OutData': formatNoop,
|
||||
'StorageData': formatNoop
|
||||
};
|
||||
|
||||
module.exports = function format (output: InterfaceOutputType, value: any): any {
|
||||
return util.format(formatters, output.type, value);
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
const format = require('./index');
|
||||
|
||||
describe('format/output', () => {
|
||||
describe('format', () => {
|
||||
it('formats the value', () => {
|
||||
expect(
|
||||
format('Header', 'test')
|
||||
).to.deep.equal('test');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
export type FormatterFunction = (value: any) => any;
|
||||
@@ -0,0 +1,36 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
import type { FormatterFunction } from './types';
|
||||
|
||||
const formatNoop = require('./noop');
|
||||
const { isUndefined } = require('../util/is');
|
||||
|
||||
function format (formatters: { [any]: FormatterFunction }, type: string, value: any): any {
|
||||
const formatter = formatters[type];
|
||||
|
||||
if (isUndefined(formatter)) {
|
||||
console.warn(`Unable to find default formatter for '${type}', falling back to noop`);
|
||||
|
||||
return formatNoop(value);
|
||||
}
|
||||
|
||||
try {
|
||||
return formatter(value);
|
||||
} catch (error) {
|
||||
throw new Error(`Error formatting '${value}' as '${type}'': ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function formatArray (formatters: { [any]: FormatterFunction }, types: Array<string>, values: Array<any>): Array<any> {
|
||||
return types.map((type, index) => {
|
||||
const value = values[index];
|
||||
|
||||
return format(formatters, type, value);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
format,
|
||||
formatArray
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
const sinon = require('sinon');
|
||||
|
||||
const { format, formatArray } = require('./util');
|
||||
|
||||
describe('format/util', () => {
|
||||
let formatters;
|
||||
let addressStub;
|
||||
let warnSpy;
|
||||
|
||||
beforeEach(() => {
|
||||
addressStub = sinon.stub();
|
||||
formatters = {
|
||||
'Address': addressStub,
|
||||
'Exception': () => {
|
||||
throw new Error('something went wrong');
|
||||
}
|
||||
};
|
||||
warnSpy = sinon.spy(console, 'warn');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
console.warn.restore();
|
||||
});
|
||||
|
||||
describe('format', () => {
|
||||
it('formats unknown types with a fallback', () => {
|
||||
expect(
|
||||
format(formatters, 'Unknown', 'test')
|
||||
).to.equal('test');
|
||||
});
|
||||
|
||||
it('logs a warning with unknown types', () => {
|
||||
format(formatters, 'Unknown', 'test');
|
||||
expect(warnSpy).to.have.been.calledWith("Unable to find default formatter for 'Unknown', falling back to noop");
|
||||
});
|
||||
|
||||
it('formats known types using the supplied formatter', () => {
|
||||
format(formatters, 'Address', '0xaddress');
|
||||
|
||||
expect(addressStub).to.have.been.calledWith('0xaddress');
|
||||
});
|
||||
|
||||
it('wraps exceptions with the type', () => {
|
||||
expect(
|
||||
() => format(formatters, 'Exception', 'test')
|
||||
).to.throw(/Error formatting 'test' as 'Exception'/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatArray', () => {
|
||||
it('formats each value in an array', () => {
|
||||
expect(
|
||||
formatArray(formatters, ['Unknown', 'Unknown'], ['test', 'blah'])
|
||||
).to.deep.equal(['test', 'blah']);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
require('./polyfill');
|
||||
|
||||
const Api = require('./api');
|
||||
|
||||
module.exports = Api;
|
||||
@@ -0,0 +1,11 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
/* eslint-disable no-unused-expressions */
|
||||
|
||||
const Api = require('./index');
|
||||
|
||||
describe('index', () => {
|
||||
it('exports default Api', () => {
|
||||
expect(Api).to.be.ok;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
if (typeof fetch === 'undefined') {
|
||||
require('isomorphic-fetch');
|
||||
}
|
||||
|
||||
if (typeof WebSocket === 'undefined') {
|
||||
global.WebSocket = require('ws');
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
import type { ProviderInterface } from './types';
|
||||
|
||||
const JsonRpcCoder = require('./jsonRpcCoder');
|
||||
|
||||
module.exports = class HttpProvider extends JsonRpcCoder implements ProviderInterface {
|
||||
_endpoint: string;
|
||||
|
||||
constructor (endpoint: string) {
|
||||
super();
|
||||
|
||||
this._endpoint = endpoint;
|
||||
}
|
||||
|
||||
async send (method: string, params: Array<any>): Promise<any> {
|
||||
const body = this.encodeJson(method, params);
|
||||
const response = await fetch(this._endpoint, {
|
||||
body,
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Length': `${body.length}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
method: 'POST'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`[${response.status}]: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
return this.decodeResponse(result);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,97 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
/* eslint-disable no-unused-expressions */
|
||||
|
||||
const { mockHttp, TEST_HTTP_URL } = require('../../test/mockHttp');
|
||||
|
||||
const sinon = require('sinon');
|
||||
|
||||
const Http = require('./http');
|
||||
|
||||
describe('provider/Http', () => {
|
||||
let http;
|
||||
let mock;
|
||||
|
||||
beforeEach(() => {
|
||||
http = new Http(TEST_HTTP_URL);
|
||||
|
||||
sinon.spy(http, 'encodeJson');
|
||||
sinon.spy(http, 'decodeResponse');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
http.encodeJson.restore();
|
||||
http.decodeResponse.restore();
|
||||
|
||||
mock.done();
|
||||
});
|
||||
|
||||
describe('send', () => {
|
||||
it('encodes requests', () => {
|
||||
mock = mockHttp([{
|
||||
method: 'test_encoding',
|
||||
reply: {
|
||||
result: 'ok'
|
||||
}
|
||||
}]);
|
||||
|
||||
return http
|
||||
.send('test_encoding', ['param'])
|
||||
.then((result) => {
|
||||
expect(http.encodeJson).to.have.been.calledWith('test_encoding', ['param']);
|
||||
});
|
||||
});
|
||||
|
||||
it('decodes responses', () => {
|
||||
mock = mockHttp([{
|
||||
method: 'test_encoding',
|
||||
reply: {
|
||||
result: 'ok'
|
||||
}
|
||||
}]);
|
||||
|
||||
return http
|
||||
.send('test_encoding', ['param'])
|
||||
.then((result) => {
|
||||
expect(http.decodeResponse).to.have.been.calledWith({
|
||||
id: 1,
|
||||
jsonrpc: '2.0',
|
||||
result: 'ok'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('passes the body through correctly', () => {
|
||||
mock = mockHttp([{
|
||||
method: 'test_body',
|
||||
reply: {
|
||||
result: 'ok'
|
||||
}
|
||||
}]);
|
||||
|
||||
return http
|
||||
.send('test_body', ['param'])
|
||||
.then((result) => {
|
||||
expect(mock.body['test_body']).to.deep.equal({
|
||||
id: 1,
|
||||
jsonrpc: '2.0',
|
||||
method: 'test_body',
|
||||
params: ['param']
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('throws error when !response.ok', () => {
|
||||
mock = mockHttp([{
|
||||
code: 500,
|
||||
method: 'test_error'
|
||||
}]);
|
||||
|
||||
return http
|
||||
.send('test_error', [])
|
||||
.catch((error) => {
|
||||
expect(error).to.match(/\[500\]: Internal Server/);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
const HttpProvider = require('./http');
|
||||
|
||||
module.exports = {
|
||||
HttpProvider
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
import type { JsonRpcRequest, JsonRpcResponse } from './types';
|
||||
|
||||
const { isNumber, isUndefined } = require('../util/is');
|
||||
|
||||
module.exports = class JsonRpcCoder {
|
||||
_id: number = 0;
|
||||
|
||||
decodeResponse (response: JsonRpcResponse): any {
|
||||
if (!response) {
|
||||
throw new Error('Empty response object received');
|
||||
}
|
||||
|
||||
if (response.jsonrpc !== '2.0') {
|
||||
throw new Error('Invalid jsonrpc field in decoded object');
|
||||
}
|
||||
|
||||
if (!isNumber(response.id)) {
|
||||
throw new Error('Invalid id field in decoded object');
|
||||
}
|
||||
|
||||
if (response.error) {
|
||||
const { code, message } = response.error;
|
||||
|
||||
throw new Error(`[${code}]: ${message}`);
|
||||
}
|
||||
|
||||
if (isUndefined(response.result)) {
|
||||
throw new Error('No result found in JsonRpc response');
|
||||
}
|
||||
|
||||
return response.result;
|
||||
}
|
||||
|
||||
encodeObject (method: string, params: Array<any>): JsonRpcRequest {
|
||||
return {
|
||||
id: ++this._id,
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params
|
||||
};
|
||||
}
|
||||
|
||||
encodeJson (method: string, params: Array<any>): string {
|
||||
return JSON.stringify(
|
||||
this.encodeObject(method, params)
|
||||
);
|
||||
}
|
||||
|
||||
get id (): number {
|
||||
return this._id;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
const JsonRpcCoder = require('./jsonRpcCoder');
|
||||
|
||||
describe('provider/JsonRpcCoder', () => {
|
||||
let coder;
|
||||
|
||||
beforeEach(() => {
|
||||
coder = new JsonRpcCoder();
|
||||
});
|
||||
|
||||
describe('id', () => {
|
||||
it('starts with id === 0 (nothing sent)', () => {
|
||||
expect(coder.id).to.equal(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('decodeResponse', () => {
|
||||
it('expects a non-empty input object', () => {
|
||||
expect(
|
||||
() => coder.decodeResponse()
|
||||
).to.throw(/Empty response/);
|
||||
});
|
||||
|
||||
it('expects a valid jsonrpc field', () => {
|
||||
expect(
|
||||
() => coder.decodeResponse({})
|
||||
).to.throw(/Invalid jsonrpc/);
|
||||
});
|
||||
|
||||
it('expects a valid id field', () => {
|
||||
expect(
|
||||
() => coder.decodeResponse({ jsonrpc: '2.0' })
|
||||
).to.throw(/Invalid id/);
|
||||
});
|
||||
|
||||
it('expects a valid result field', () => {
|
||||
expect(
|
||||
() => coder.decodeResponse({ id: 1, jsonrpc: '2.0' })
|
||||
).to.throw(/No result/);
|
||||
});
|
||||
|
||||
it('throws any error found', () => {
|
||||
expect(
|
||||
() => coder.decodeResponse({ id: 1, jsonrpc: '2.0', error: { code: 123, message: 'test error' } })
|
||||
).to.throw(/\[123\]: test error/);
|
||||
});
|
||||
|
||||
it('returns the result', () => {
|
||||
expect(
|
||||
coder.decodeResponse({ id: 1, jsonrpc: '2.0', result: 'some result' })
|
||||
).to.equal('some result');
|
||||
});
|
||||
});
|
||||
|
||||
describe('encodeObject', () => {
|
||||
it('encodes a valid JsonRPC object', () => {
|
||||
expect(
|
||||
coder.encodeObject('method', 'params')
|
||||
).to.deep.equal({
|
||||
id: 1,
|
||||
jsonrpc: '2.0',
|
||||
method: 'method',
|
||||
params: 'params'
|
||||
});
|
||||
expect(coder.id).to.equal(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('encodeJson', () => {
|
||||
it('encodes a valid JsonRPC JSON string', () => {
|
||||
expect(
|
||||
coder.encodeJson('method', 'params')
|
||||
).to.equal('{"id":1,"jsonrpc":"2.0","method":"method","params":"params"}');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
export type JsonRpcObject = {
|
||||
id: number;
|
||||
jsonrpc: '2.0';
|
||||
};
|
||||
|
||||
export type JsonRpcRequest = JsonRpcObject & {
|
||||
method: string;
|
||||
params: Array<any>;
|
||||
};
|
||||
|
||||
export type JsonRpcResponseBase = {
|
||||
error?: {
|
||||
code: number,
|
||||
message: string
|
||||
};
|
||||
result?: any;
|
||||
}
|
||||
|
||||
export type JsonRpcResponse = JsonRpcObject & JsonRpcResponseBase;
|
||||
|
||||
export interface ProviderInterface {
|
||||
send (method: string, params: Array<any>): Promise<any>;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
import type { JsonRpcResponse, ProviderInterface } from './types';
|
||||
|
||||
type AwaitingType = {
|
||||
callback: (error: ?Error, result: any) => void
|
||||
};
|
||||
|
||||
type WsMessageType = {
|
||||
data: any
|
||||
};
|
||||
|
||||
const JsonRpcCoder = require('./jsonRpcCoder');
|
||||
|
||||
module.exports = class WsProvider extends JsonRpcCoder implements ProviderInterface {
|
||||
_autoConnect: boolean = true;
|
||||
_endpoint: string;
|
||||
_handlers: { [number]: AwaitingType } = {};
|
||||
_websocket: WebSocket;
|
||||
|
||||
constructor (endpoint: string, autoConnect: boolean = true) {
|
||||
super();
|
||||
|
||||
this._endpoint = endpoint;
|
||||
this._autoConnect = autoConnect;
|
||||
|
||||
if (autoConnect) {
|
||||
this.connect();
|
||||
}
|
||||
}
|
||||
|
||||
connect = () => {
|
||||
this._handlers = {};
|
||||
|
||||
this._websocket = new WebSocket(this._endpoint);
|
||||
|
||||
this._websocket.onclose = this._onClose;
|
||||
this._websocket.onerror = this._onError;
|
||||
this._websocket.onmessage = this._onMessage;
|
||||
this._websocket.onopen = this._onOpen;
|
||||
}
|
||||
|
||||
_onClose = () => {
|
||||
console.log('disconnected from', this._endpoint);
|
||||
|
||||
if (this._autoConnect) {
|
||||
setTimeout(this.connect, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
_onError = (error: Event) => {
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
_onOpen = () => {
|
||||
console.log('connected to', this._endpoint);
|
||||
}
|
||||
|
||||
_onMessage = (message: WsMessageType) => {
|
||||
// {"jsonrpc":"2.0","id":2,"result":"0x9ce59a13059e417087c02d3236a0b1cc"}
|
||||
// "jsonrpc": "2.0", "method": "eth_subscription", "params": { "result": {...} }, "subscription": "0x9ce59a13059e417087c02d3236a0b1cc"
|
||||
const response: JsonRpcResponse = JSON.parse(message.data);
|
||||
const handler = this._handlers[response.id];
|
||||
|
||||
if (!handler) {
|
||||
console.error(`Unable to find handler for ${response.id}`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = this.decodeResponse(response);
|
||||
|
||||
handler.callback(null, result);
|
||||
} catch (error) {
|
||||
handler.callback(error);
|
||||
}
|
||||
|
||||
delete this._handlers[response.id];
|
||||
}
|
||||
|
||||
send (method: string, params: Array<any>): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
this._websocket.send(
|
||||
this.encodeObject(method, params)
|
||||
);
|
||||
|
||||
this._handlers[this.id] = {
|
||||
callback: (error: ?Error, result: any) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,121 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
/* eslint-disable no-unused-expressions */
|
||||
|
||||
const { mockWs, TEST_WS_URL } = require('../../test/mockWs');
|
||||
|
||||
const sinon = require('sinon');
|
||||
|
||||
const Ws = require('./ws');
|
||||
|
||||
let ws;
|
||||
let mock;
|
||||
|
||||
function createWs (requests, autoConnect = true) {
|
||||
mock = autoConnect
|
||||
? mockWs(requests)
|
||||
: null;
|
||||
|
||||
ws = new Ws(TEST_WS_URL, autoConnect);
|
||||
|
||||
sinon.spy(ws, 'encodeObject');
|
||||
sinon.spy(ws, 'decodeResponse');
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
describe('provider/Ws', () => {
|
||||
afterEach(() => {
|
||||
ws.encodeObject.restore();
|
||||
ws.decodeResponse.restore();
|
||||
|
||||
if (mock) {
|
||||
mock.done();
|
||||
}
|
||||
});
|
||||
|
||||
describe('send', () => {
|
||||
it('handles internal errors', () => {
|
||||
ws = createWs([], false);
|
||||
|
||||
return ws
|
||||
.send('test_encoding', ['param'])
|
||||
.catch((error) => {
|
||||
expect(error).to.be.ok;
|
||||
});
|
||||
});
|
||||
|
||||
it('encodes requests', () => {
|
||||
ws = createWs([{
|
||||
id: 1,
|
||||
method: 'test_encoding',
|
||||
reply: {
|
||||
result: 'ok'
|
||||
}
|
||||
}]);
|
||||
|
||||
return ws
|
||||
.send('test_encoding', ['param'])
|
||||
.then((result) => {
|
||||
expect(ws.encodeObject).to.have.been.calledWith('test_encoding', ['param']);
|
||||
});
|
||||
});
|
||||
|
||||
it('decodes responses', () => {
|
||||
ws = createWs([{
|
||||
id: 1,
|
||||
method: 'test_encoding',
|
||||
reply: {
|
||||
result: 'ok'
|
||||
}
|
||||
}]);
|
||||
|
||||
return ws
|
||||
.send('test_encoding', ['param'])
|
||||
.then((result) => {
|
||||
expect(ws.decodeResponse).to.have.been.calledWith({
|
||||
id: 1,
|
||||
jsonrpc: '2.0',
|
||||
result: 'ok'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('passes the body through correctly', () => {
|
||||
ws = createWs([{
|
||||
id: 1,
|
||||
method: 'test_body',
|
||||
reply: {
|
||||
result: 'ok'
|
||||
}
|
||||
}]);
|
||||
|
||||
return ws
|
||||
.send('test_body', ['param'])
|
||||
.then((result) => {
|
||||
expect(mock.body['test_body']).to.deep.equal({
|
||||
id: 1,
|
||||
jsonrpc: '2.0',
|
||||
method: 'test_body',
|
||||
params: ['param']
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('throws error when !response.ok', () => {
|
||||
ws = createWs([{
|
||||
id: 1,
|
||||
error: {
|
||||
code: 666,
|
||||
message: 'error'
|
||||
}
|
||||
}]);
|
||||
|
||||
return ws
|
||||
.send('test_error', [])
|
||||
.catch((error) => {
|
||||
expect(error).to.match(/\[666\]: error/);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
export interface ApiInterface {
|
||||
+chain: any;
|
||||
+state: any;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
function addHexPrefix (value: ?string): string {
|
||||
if (value && hasHexPrefix(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return `0x${value || ''}`;
|
||||
}
|
||||
|
||||
function hasHexPrefix (value: ?string): boolean {
|
||||
return !!(value && value.substr(0, 2) === '0x');
|
||||
}
|
||||
|
||||
function stripHexPrefix (value: ?string): string {
|
||||
if (value && hasHexPrefix(value)) {
|
||||
return value.substr(2);
|
||||
}
|
||||
|
||||
return value || '';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
addHexPrefix,
|
||||
hasHexPrefix,
|
||||
stripHexPrefix
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
/* eslint-disable no-unused-expressions */
|
||||
|
||||
const { addHexPrefix, hasHexPrefix, stripHexPrefix } = require('./hex');
|
||||
|
||||
describe('util/hex', () => {
|
||||
describe('addHexPrefix', () => {
|
||||
it('does not add when prefix is available', () => {
|
||||
expect(
|
||||
addHexPrefix('0x123')
|
||||
).to.equal('0x123');
|
||||
});
|
||||
|
||||
it('adds the prefix when it is not available', () => {
|
||||
expect(
|
||||
addHexPrefix('123')
|
||||
).to.equal('0x123');
|
||||
});
|
||||
|
||||
it('returns null as 0x', () => {
|
||||
expect(
|
||||
addHexPrefix(null)
|
||||
).to.equal('0x');
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasHexPrefix', () => {
|
||||
it('returns true when hex prefix is found', () => {
|
||||
expect(
|
||||
hasHexPrefix('0x123')
|
||||
).to.be.true;
|
||||
});
|
||||
|
||||
it('returns false when no prefix attached', () => {
|
||||
expect(
|
||||
hasHexPrefix('123')
|
||||
).to.be.false;
|
||||
});
|
||||
|
||||
it('returns false when null value supplied', () => {
|
||||
expect(
|
||||
hasHexPrefix(null)
|
||||
).to.be.false;
|
||||
});
|
||||
});
|
||||
|
||||
describe('stripHexPrefix', () => {
|
||||
it('returns the value as-is when no prefix', () => {
|
||||
expect(
|
||||
stripHexPrefix('01ab')
|
||||
).to.equal('01ab');
|
||||
});
|
||||
|
||||
it('returns an empty string when null value supplied', () => {
|
||||
expect(
|
||||
stripHexPrefix(null)
|
||||
).to.equal('');
|
||||
});
|
||||
|
||||
it('strips the prefix from other strings', () => {
|
||||
expect(
|
||||
stripHexPrefix('0x1223')
|
||||
).to.equal('1223');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
function isFunction (value: any): boolean {
|
||||
return typeof value === 'function';
|
||||
}
|
||||
|
||||
function isNumber (value: any): boolean {
|
||||
return typeof value === 'number';
|
||||
}
|
||||
|
||||
function isUndefined (value: any): boolean {
|
||||
return typeof value === 'undefined';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isFunction,
|
||||
isNumber,
|
||||
isUndefined
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
/* eslint-disable no-unused-expressions */
|
||||
|
||||
const { isFunction, isNumber, isUndefined } = require('./is');
|
||||
|
||||
describe('util/is', () => {
|
||||
describe('isFunction', () => {
|
||||
it('returns true on valid functions', () => {
|
||||
expect(
|
||||
isFunction(isFunction)
|
||||
).to.be.true;
|
||||
});
|
||||
|
||||
it('returns false of invalid functions', () => {
|
||||
expect(
|
||||
isFunction('notAFunction')
|
||||
).to.be.false;
|
||||
});
|
||||
});
|
||||
|
||||
describe('isNumber', () => {
|
||||
it('returns true on valid numbers', () => {
|
||||
expect(
|
||||
isNumber(2)
|
||||
).to.be.true;
|
||||
});
|
||||
|
||||
it('returns fals on invalid numbers', () => {
|
||||
expect(
|
||||
isNumber('2')
|
||||
).to.be.false;
|
||||
});
|
||||
});
|
||||
|
||||
describe('isUndefined', () => {
|
||||
it('returns true on undefined values', () => {
|
||||
expect(
|
||||
isUndefined()
|
||||
).to.be.true;
|
||||
});
|
||||
|
||||
it('returns false on defined values', () => {
|
||||
expect(
|
||||
isUndefined(null)
|
||||
).to.be.false;
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user