diff options
Diffstat (limited to 'packages/subproviders')
12 files changed, 116 insertions, 36 deletions
diff --git a/packages/subproviders/package.json b/packages/subproviders/package.json index d0d9023d4..3e52e4823 100644 --- a/packages/subproviders/package.json +++ b/packages/subproviders/package.json @@ -55,6 +55,7 @@ "ethereumjs-util": "^5.1.1", "ganache-core": "0xProject/ganache-core", "hdkey": "^0.7.1", + "json-rpc-error": "2.0.0", "lodash": "^4.17.4", "semaphore-async-await": "^1.5.1", "web3-provider-engine": "14.0.6" diff --git a/packages/subproviders/src/index.ts b/packages/subproviders/src/index.ts index 71d643f14..9d4480e59 100644 --- a/packages/subproviders/src/index.ts +++ b/packages/subproviders/src/index.ts @@ -1,5 +1,6 @@ import Eth from '@ledgerhq/hw-app-eth'; import TransportU2F from '@ledgerhq/hw-transport-u2f'; +export import Web3ProviderEngine = require('web3-provider-engine'); export { ECSignature } from '@0xproject/types'; import { LedgerEthereumClient } from './types'; @@ -10,6 +11,7 @@ export { FakeGasEstimateSubprovider } from './subproviders/fake_gas_estimate_sub export { SignerSubprovider } from './subproviders/signer'; export { RedundantSubprovider } from './subproviders/redundant_subprovider'; export { LedgerSubprovider } from './subproviders/ledger'; +export { RPCSubprovider } from './subproviders/rpc_subprovider'; export { GanacheSubprovider } from './subproviders/ganache'; export { Subprovider } from './subproviders/subprovider'; export { NonceTrackerSubprovider } from './subproviders/nonce_tracker'; diff --git a/packages/subproviders/src/subproviders/rpc_subprovider.ts b/packages/subproviders/src/subproviders/rpc_subprovider.ts new file mode 100644 index 000000000..3ad0e5325 --- /dev/null +++ b/packages/subproviders/src/subproviders/rpc_subprovider.ts @@ -0,0 +1,90 @@ +import { assert } from '@0xproject/assert'; +import { StatusCodes } from '@0xproject/types'; +import { fetchAsync } from '@0xproject/utils'; +import { JSONRPCRequestPayload } from 'ethereum-types'; +import JsonRpcError = require('json-rpc-error'); + +import { Callback, ErrorCallback } from '../types'; + +import { Subprovider } from './subprovider'; + +/** + * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface. + * It forwards on JSON RPC requests to the supplied `rpcUrl` endpoint + */ +export class RPCSubprovider extends Subprovider { + private _rpcUrl: string; + private _requestTimeoutMs: number; + constructor(rpcUrl: string, requestTimeoutMs: number = 20000) { + super(); + assert.isString('rpcUrl', rpcUrl); + assert.isNumber('requestTimeoutMs', requestTimeoutMs); + this._rpcUrl = rpcUrl; + this._requestTimeoutMs = requestTimeoutMs; + } + /** + * This method conforms to the web3-provider-engine interface. + * It is called internally by the ProviderEngine when it is this subproviders + * turn to handle a JSON RPC request. + * @param payload JSON RPC payload + * @param next Callback to call if this subprovider decides not to handle the request + * @param end Callback to call if subprovider handled the request and wants to pass back the request. + */ + // tslint:disable-next-line:prefer-function-over-method async-suffix + public async handleRequest(payload: JSONRPCRequestPayload, _next: Callback, end: ErrorCallback): Promise<void> { + const finalPayload = Subprovider._createFinalPayload(payload); + const headers = new Headers({ + Accept: 'application/json', + 'Content-Type': 'application/json', + }); + + let response; + try { + response = await fetchAsync( + this._rpcUrl, + { + method: 'POST', + headers, + body: JSON.stringify(finalPayload), + }, + this._requestTimeoutMs, + ); + } catch (err) { + end(new JsonRpcError.InternalError(err)); + return; + } + + const text = await response.text(); + if (!response.ok) { + const statusCode = response.status; + switch (statusCode) { + case StatusCodes.MethodNotAllowed: + end(new JsonRpcError.MethodNotFound()); + return; + case StatusCodes.GatewayTimeout: + const errMsg = + 'Gateway timeout. The request took too long to process. This can happen when querying logs over too wide a block range.'; + const err = new Error(errMsg); + end(new JsonRpcError.InternalError(err)); + return; + default: + end(new JsonRpcError.InternalError(text)); + return; + } + } + + let data; + try { + data = JSON.parse(text); + } catch (err) { + end(new JsonRpcError.InternalError(err)); + return; + } + + if (data.error) { + end(data.error); + return; + } + end(null, data.result); + } +} diff --git a/packages/subproviders/src/subproviders/subprovider.ts b/packages/subproviders/src/subproviders/subprovider.ts index ff8378c4e..5dc273569 100644 --- a/packages/subproviders/src/subproviders/subprovider.ts +++ b/packages/subproviders/src/subproviders/subprovider.ts @@ -9,18 +9,7 @@ import { Callback, ErrorCallback, JSONRPCRequestPayloadWithMethod } from '../typ export abstract class Subprovider { // tslint:disable-next-line:underscore-private-and-protected private engine!: Provider; - // Ported from: https://github.com/MetaMask/provider-engine/blob/master/util/random-id.js - private static _getRandomId(): number { - const extraDigits = 3; - const baseTen = 10; - // 13 time digits - const datePart = new Date().getTime() * Math.pow(baseTen, extraDigits); - // 3 random digits - const extraPart = Math.floor(Math.random() * Math.pow(baseTen, extraDigits)); - // 16 digits - return datePart + extraPart; - } - private static _createFinalPayload( + protected static _createFinalPayload( payload: Partial<JSONRPCRequestPayloadWithMethod>, ): Partial<JSONRPCRequestPayloadWithMethod> { const finalPayload = { @@ -32,6 +21,17 @@ export abstract class Subprovider { }; return finalPayload; } + // Ported from: https://github.com/MetaMask/provider-engine/blob/master/util/random-id.js + private static _getRandomId(): number { + const extraDigits = 3; + const baseTen = 10; + // 13 time digits + const datePart = new Date().getTime() * Math.pow(baseTen, extraDigits); + // 3 random digits + const extraPart = Math.floor(Math.random() * Math.pow(baseTen, extraDigits)); + // 16 digits + return datePart + extraPart; + } // tslint:disable-next-line:async-suffix public abstract async handleRequest( payload: JSONRPCRequestPayload, diff --git a/packages/subproviders/src/utils/subprovider_utils.ts b/packages/subproviders/src/utils/subprovider_utils.ts index 24ebedd06..beda408ab 100644 --- a/packages/subproviders/src/utils/subprovider_utils.ts +++ b/packages/subproviders/src/utils/subprovider_utils.ts @@ -1,4 +1,4 @@ -import ProviderEngine = require('web3-provider-engine'); +import Web3ProviderEngine = require('web3-provider-engine'); import { Subprovider } from '../subproviders/subprovider'; @@ -7,7 +7,7 @@ import { Subprovider } from '../subproviders/subprovider'; * @param provider Given provider * @param subprovider Subprovider to prepend */ -export function prependSubprovider(provider: ProviderEngine, subprovider: Subprovider): void { +export function prependSubprovider(provider: Web3ProviderEngine, subprovider: Subprovider): void { subprovider.setEngine(provider); // HACK: We use implementation details of provider engine here // https://github.com/MetaMask/provider-engine/blob/master/index.js#L68 diff --git a/packages/subproviders/test/integration/ledger_subprovider_test.ts b/packages/subproviders/test/integration/ledger_subprovider_test.ts index 196cecf32..103e8f952 100644 --- a/packages/subproviders/test/integration/ledger_subprovider_test.ts +++ b/packages/subproviders/test/integration/ledger_subprovider_test.ts @@ -7,10 +7,8 @@ import TransportNodeHid from '@ledgerhq/hw-transport-node-hid'; import * as chai from 'chai'; import { JSONRPCResponsePayload } from 'ethereum-types'; import * as ethUtils from 'ethereumjs-util'; -import Web3ProviderEngine = require('web3-provider-engine'); -import RpcSubprovider = require('web3-provider-engine/subproviders/rpc'); -import { LedgerSubprovider } from '../../src'; +import { LedgerSubprovider, RPCSubprovider, Web3ProviderEngine } from '../../src'; import { LedgerEthereumClient } from '../../src/types'; import { chaiSetup } from '../chai_setup'; import { fixtureData } from '../utils/fixture_data'; @@ -86,9 +84,7 @@ describe('LedgerSubprovider', () => { before(() => { ledgerProvider = new Web3ProviderEngine(); ledgerProvider.addProvider(ledgerSubprovider); - const httpProvider = new RpcSubprovider({ - rpcUrl: 'http://localhost:8545', - }); + const httpProvider = new RPCSubprovider('http://localhost:8545'); ledgerProvider.addProvider(httpProvider); ledgerProvider.start(); diff --git a/packages/subproviders/test/unit/eth_lightwallet_subprovider_test.ts b/packages/subproviders/test/unit/eth_lightwallet_subprovider_test.ts index f17c21f02..063817a95 100644 --- a/packages/subproviders/test/unit/eth_lightwallet_subprovider_test.ts +++ b/packages/subproviders/test/unit/eth_lightwallet_subprovider_test.ts @@ -2,9 +2,8 @@ import * as chai from 'chai'; import * as lightwallet from 'eth-lightwallet'; import { JSONRPCResponsePayload } from 'ethereum-types'; import * as ethUtils from 'ethereumjs-util'; -import Web3ProviderEngine = require('web3-provider-engine'); -import { EthLightwalletSubprovider } from '../../src'; +import { EthLightwalletSubprovider, Web3ProviderEngine } from '../../src'; import { DoneCallback } from '../../src/types'; import { chaiSetup } from '../chai_setup'; import { fixtureData } from '../utils/fixture_data'; diff --git a/packages/subproviders/test/unit/ledger_subprovider_test.ts b/packages/subproviders/test/unit/ledger_subprovider_test.ts index 3b57e125b..edff5144e 100644 --- a/packages/subproviders/test/unit/ledger_subprovider_test.ts +++ b/packages/subproviders/test/unit/ledger_subprovider_test.ts @@ -2,9 +2,8 @@ import * as chai from 'chai'; import { JSONRPCResponsePayload } from 'ethereum-types'; import * as ethUtils from 'ethereumjs-util'; import * as _ from 'lodash'; -import Web3ProviderEngine = require('web3-provider-engine'); -import { LedgerSubprovider } from '../../src'; +import { LedgerSubprovider, Web3ProviderEngine } from '../../src'; import { DoneCallback, LedgerCommunicationClient, diff --git a/packages/subproviders/test/unit/mnemonic_wallet_subprovider_test.ts b/packages/subproviders/test/unit/mnemonic_wallet_subprovider_test.ts index 51ba7094c..f2bdda3cd 100644 --- a/packages/subproviders/test/unit/mnemonic_wallet_subprovider_test.ts +++ b/packages/subproviders/test/unit/mnemonic_wallet_subprovider_test.ts @@ -1,9 +1,8 @@ import * as chai from 'chai'; import { JSONRPCResponsePayload } from 'ethereum-types'; import * as ethUtils from 'ethereumjs-util'; -import Web3ProviderEngine = require('web3-provider-engine'); -import { GanacheSubprovider, MnemonicWalletSubprovider } from '../../src/'; +import { GanacheSubprovider, MnemonicWalletSubprovider, Web3ProviderEngine } from '../../src/'; import { DoneCallback, WalletSubproviderErrors } from '../../src/types'; import { chaiSetup } from '../chai_setup'; import { fixtureData } from '../utils/fixture_data'; diff --git a/packages/subproviders/test/unit/nonce_tracker_subprovider_test.ts b/packages/subproviders/test/unit/nonce_tracker_subprovider_test.ts index fa33cd50a..c437d0815 100644 --- a/packages/subproviders/test/unit/nonce_tracker_subprovider_test.ts +++ b/packages/subproviders/test/unit/nonce_tracker_subprovider_test.ts @@ -1,11 +1,10 @@ import * as chai from 'chai'; -import Web3ProviderEngine = require('web3-provider-engine'); import FixtureSubprovider = require('web3-provider-engine/subproviders/fixture'); import { promisify } from '@0xproject/utils'; import EthereumTx = require('ethereumjs-tx'); -import { NonceTrackerSubprovider } from '../../src'; +import { NonceTrackerSubprovider, Web3ProviderEngine } from '../../src'; import { chaiSetup } from '../chai_setup'; const expect = chai.expect; diff --git a/packages/subproviders/test/unit/private_key_wallet_subprovider_test.ts b/packages/subproviders/test/unit/private_key_wallet_subprovider_test.ts index ab321bcff..95773145f 100644 --- a/packages/subproviders/test/unit/private_key_wallet_subprovider_test.ts +++ b/packages/subproviders/test/unit/private_key_wallet_subprovider_test.ts @@ -1,9 +1,8 @@ import * as chai from 'chai'; import { JSONRPCResponsePayload } from 'ethereum-types'; import * as ethUtils from 'ethereumjs-util'; -import Web3ProviderEngine = require('web3-provider-engine'); -import { GanacheSubprovider, PrivateKeyWalletSubprovider } from '../../src/'; +import { GanacheSubprovider, PrivateKeyWalletSubprovider, Web3ProviderEngine } from '../../src/'; import { DoneCallback, WalletSubproviderErrors } from '../../src/types'; import { chaiSetup } from '../chai_setup'; import { fixtureData } from '../utils/fixture_data'; diff --git a/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts b/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts index 810fb8f45..e30d2f74e 100644 --- a/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts +++ b/packages/subproviders/test/unit/redundant_rpc_subprovider_test.ts @@ -2,10 +2,8 @@ import { DoneCallback } from '@0xproject/types'; import * as chai from 'chai'; import { JSONRPCResponsePayload } from 'ethereum-types'; import * as Sinon from 'sinon'; -import Web3ProviderEngine = require('web3-provider-engine'); -import RpcSubprovider = require('web3-provider-engine/subproviders/rpc'); -import { RedundantSubprovider } from '../../src'; +import { RedundantSubprovider, RPCSubprovider, Web3ProviderEngine } from '../../src'; import { Subprovider } from '../../src/subproviders/subprovider'; import { chaiSetup } from '../chai_setup'; import { ganacheSubprovider } from '../utils/ganache_subprovider'; @@ -39,9 +37,7 @@ describe('RedundantSubprovider', () => { }); it('succeeds when supplied at least one healthy endpoint', (done: DoneCallback) => { provider = new Web3ProviderEngine(); - const nonExistentSubprovider = new RpcSubprovider({ - rpcUrl: 'http://does-not-exist:3000', - }); + const nonExistentSubprovider = new RPCSubprovider('http://does-not-exist:3000'); const handleRequestStub = Sinon.stub(nonExistentSubprovider, 'handleRequest').throws( new Error('REQUEST_FAILED'), ); |