Skip to content

Commit

Permalink
Use named exports, add index.ts (#81)
Browse files Browse the repository at this point in the history
* Move cache-utils to separate folder
  • Loading branch information
rekmarks authored Mar 25, 2021
1 parent 423da2b commit fc1fd5d
Show file tree
Hide file tree
Showing 18 changed files with 49 additions and 126 deletions.
6 changes: 2 additions & 4 deletions src/block-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
BlockCache,
Cache,
JsonRpcRequestToCache,
} from './cache-utils';
} from './utils/cache';

// `<nil>` comes from https://github.com/ethereum/go-ethereum/issues/16925
const emptyValues = [undefined, null, '\u003cnil\u003e'];
Expand All @@ -19,8 +19,6 @@ interface BlockCacheMiddlewareOptions {
blockTracker?: PollingBlockTracker;
}

export = createBlockCacheMiddleware;

//
// Cache Strategies
//
Expand Down Expand Up @@ -135,7 +133,7 @@ class BlockCacheStrategy {
}
}

function createBlockCacheMiddleware({
export function createBlockCacheMiddleware({
blockTracker,
}: BlockCacheMiddlewareOptions = {}): JsonRpcMiddleware<string[], Block> {
// validate options
Expand Down
6 changes: 2 additions & 4 deletions src/block-ref-rewrite.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { PollingBlockTracker } from 'eth-block-tracker';
import { createAsyncMiddleware, JsonRpcMiddleware } from 'json-rpc-engine';
import { blockTagParamIndex, Block } from './cache-utils';
import { blockTagParamIndex, Block } from './utils/cache';

interface BlockRefRewriteMiddlewareOptions {
blockTracker?: PollingBlockTracker;
}

export = createBlockRefRewriteMiddleware;

function createBlockRefRewriteMiddleware({
export function createBlockRefRewriteMiddleware({
blockTracker,
}: BlockRefRewriteMiddlewareOptions = {}): JsonRpcMiddleware<string[], Block> {
if (!blockTracker) {
Expand Down
6 changes: 2 additions & 4 deletions src/block-ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,14 @@ import {
Block,
SafeEventEmitterProvider,
blockTagParamIndex,
} from './cache-utils';
} from './utils/cache';

interface BlockRefMiddlewareOptions {
blockTracker?: PollingBlockTracker;
provider?: SafeEventEmitterProvider;
}

export = createBlockRefMiddleware;

function createBlockRefMiddleware({
export function createBlockRefMiddleware({
provider,
blockTracker,
}: BlockRefMiddlewareOptions = {}): JsonRpcMiddleware<string[], Block> {
Expand Down
5 changes: 2 additions & 3 deletions src/block-tracker-inspector.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { PollingBlockTracker } from 'eth-block-tracker';
import { createAsyncMiddleware, JsonRpcMiddleware } from 'json-rpc-engine';

import { Block } from './cache-utils';
import { Block } from './utils/cache';

const futureBlockRefRequests: string[] = [
'eth_getTransactionByHash',
Expand All @@ -11,10 +11,9 @@ const futureBlockRefRequests: string[] = [
interface BlockTrackerInspectorMiddlewareOptions {
blockTracker: PollingBlockTracker;
}
export = createBlockTrackerInspectorMiddleware;

// inspect if response contains a block ref higher than our latest block
function createBlockTrackerInspectorMiddleware({
export function createBlockTrackerInspectorMiddleware({
blockTracker,
}: BlockTrackerInspectorMiddlewareOptions): JsonRpcMiddleware<string[], Block> {
return createAsyncMiddleware(async (req, res, next) => {
Expand Down
2 changes: 1 addition & 1 deletion src/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createAsyncMiddleware, JsonRpcMiddleware } from 'json-rpc-engine';
import { EthereumRpcError, ethErrors } from 'eth-rpc-errors';
import { Payload, Block } from './cache-utils';
import { Payload, Block } from './utils/cache';

/* eslint-disable node/global-require,@typescript-eslint/no-require-imports */
const fetch = global.fetch || require('node-fetch');
Expand Down
11 changes: 11 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export * from './block-cache';
export * from './block-ref-rewrite';
export * from './block-ref';
export * from './block-tracker-inspector';
export * from './fetch';
export * from './inflight-cache';
export * from './providerAsMiddleware';
export * from './providerFromEngine';
export * from './providerFromMiddleware';
export * from './retryOnEmpty';
export * from './wallet';
5 changes: 2 additions & 3 deletions src/inflight-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ import {
cacheIdentifierForPayload,
Block,
JsonRpcRequestToCache,
} from './cache-utils';
} from './utils/cache';

type RequestHandlers = (handledRes: PendingJsonRpcResponse<Block>) => void;
interface InflightRequest {
[cacheId: string]: RequestHandlers[];
}
export = createInflightCache;

function createInflightCache(): JsonRpcMiddleware<string[], Block> {
export function createInflightCacheMiddleware(): JsonRpcMiddleware<string[], Block> {
const inflightRequests: InflightRequest = {};

return createAsyncMiddleware(async (req, res, next) => {
Expand Down
6 changes: 2 additions & 4 deletions src/providerAsMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { JsonRpcMiddleware, PendingJsonRpcResponse } from 'json-rpc-engine';
import { Block, SafeEventEmitterProvider } from './cache-utils';
import { Block, SafeEventEmitterProvider } from './utils/cache';

export = providerAsMiddleware;

function providerAsMiddleware(
export function providerAsMiddleware(
provider: SafeEventEmitterProvider,
): JsonRpcMiddleware<string[], Block> {
return (req, res, _next, end) => {
Expand Down
10 changes: 5 additions & 5 deletions src/providerFromEngine.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { JsonRpcEngine, JsonRpcRequest } from 'json-rpc-engine';
import SafeEventEmitter from '@metamask/safe-event-emitter';
import { SafeEventEmitterProvider } from './cache-utils';
import { SafeEventEmitterProvider } from './utils/cache';

export = providerFromEngine;

function providerFromEngine(engine: JsonRpcEngine): SafeEventEmitterProvider {
export function providerFromEngine(
engine: JsonRpcEngine,
): SafeEventEmitterProvider {
const provider: SafeEventEmitterProvider = new SafeEventEmitter() as SafeEventEmitterProvider;
// handle both rpc send methods
provider.sendAsync = engine.handle.bind(engine);
provider.send = (req: JsonRpcRequest<string[]>, callback: VoidFunction) => {
provider.send = (req: JsonRpcRequest<string[]>, callback: () => void) => {
if (typeof callback !== 'function') {
throw new Error('Must provide callback to "send" method.');
}
Expand Down
8 changes: 3 additions & 5 deletions src/providerFromMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { JsonRpcEngine, JsonRpcMiddleware } from 'json-rpc-engine';
import { SafeEventEmitterProvider, Block } from './cache-utils';
import providerFromEngine from './providerFromEngine';
import { SafeEventEmitterProvider, Block } from './utils/cache';
import { providerFromEngine } from './providerFromEngine';

export = providerFromMiddleware;

function providerFromMiddleware(
export function providerFromMiddleware(
middleware: JsonRpcMiddleware<string[], Block>,
): SafeEventEmitterProvider {
const engine: JsonRpcEngine = new JsonRpcEngine();
Expand Down
6 changes: 2 additions & 4 deletions src/retryOnEmpty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
Block,
blockTagParamIndex,
SafeEventEmitterProvider,
} from './cache-utils';
} from './utils/cache';

//
// RetryOnEmptyMiddleware will retry any request with an empty response that has
Expand All @@ -20,8 +20,6 @@ import {
// nodes that are not always in sync with each other.
//

export = createRetryOnEmptyMiddleware;

// empty values used to determine if a request should be retried
// `<nil>` comes from https://github.com/ethereum/go-ethereum/issues/16925
const emptyValues: (string | null | undefined)[] = [
Expand All @@ -35,7 +33,7 @@ interface RetryOnEmptyMiddlewareOptions {
blockTracker?: PollingBlockTracker;
}

function createRetryOnEmptyMiddleware({
export function createRetryOnEmptyMiddleware({
provider,
blockTracker,
}: RetryOnEmptyMiddlewareOptions = {}): JsonRpcMiddleware<string[], Block> {
Expand Down
2 changes: 1 addition & 1 deletion src/cache-utils.ts → src/utils/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export interface SafeEventEmitterProvider extends SafeEventEmitter {
req: JsonRpcRequest<string[]>,
callback: SendAsyncCallBack
) => void;
send: (req: JsonRpcRequest<string[]>, callback: VoidFunction) => void;
send: (req: JsonRpcRequest<string[]>, callback: () => void) => void;
}

export function cacheIdentifierForPayload(
Expand Down
6 changes: 2 additions & 4 deletions src/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from 'json-rpc-engine';
import * as sigUtil from 'eth-sig-util';
import { ethErrors } from 'eth-rpc-errors';
import { Block } from './cache-utils';
import { Block } from './utils/cache';

interface TransactionParams {
from: string;
Expand Down Expand Up @@ -60,9 +60,7 @@ interface WalletMiddlewareOptions {
) => Promise<Record<string, unknown>>;
}

export = createWalletMiddleware;

function createWalletMiddleware({
export function createWalletMiddleware({
getAccounts,
processDecryptMessage,
processEncryptionPublicKey,
Expand Down
59 changes: 1 addition & 58 deletions test/block-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const { JsonRpcEngine } = require('json-rpc-engine');
const { PollingBlockTracker } = require('eth-block-tracker');
const GanacheCore = require('ganache-core');
const pify = require('pify');
const createBlockCacheMiddleware = require('../dist/block-cache');
const { createBlockCacheMiddleware } = require('../dist');
const createHitTrackerMiddleware = require('./util/createHitTrackerMiddleware');

//
Expand Down Expand Up @@ -149,63 +149,6 @@ cacheTest(
false,
);

//
// result conditional cache
//

// these tests were imported from provider-engine but rely on state setup we dont have here yet

// // tx by hash

// cacheTest('getTransactionByHash for transaction that doesn\'t exist', {
// method: 'eth_getTransactionByHash',
// params: ['0x00000000000000000000000000000000000000000000000000deadbeefcafe00'],
// }, false)

// cacheTest('getTransactionByHash for transaction that\'s pending', {
// method: 'eth_getTransactionByHash',
// params: ['0x00000000000000000000000000000000000000000000000000deadbeefcafe01'],
// }, false)

// cacheTest('getTransactionByHash for mined transaction', {
// method: 'eth_getTransactionByHash',
// params: ['0x00000000000000000000000000000000000000000000000000deadbeefcafe02'],
// }, true)

// // code

// cacheTest('getCode for latest block, then for earliest block, should not return cached response on second request', [{
// method: 'eth_getCode',
// params: ['0x1234', 'latest'],
// }, {
// method: 'eth_getCode',
// params: ['0x1234', 'earliest'],
// }], false)

// cacheTest('getCode for a specific block, then for the one before it, should not return cached response on second request', [{
// method: 'eth_getCode',
// params: ['0x1234', '0x3'],
// }, {
// method: 'eth_getCode',
// params: ['0x1234', '0x2'],
// }], false)

// cacheTest('getCode for a specific block, then the one after it, should return cached response on second request', [{
// method: 'eth_getCode',
// params: ['0x1234', '0x2'],
// }, {
// method: 'eth_getCode',
// params: ['0x1234', '0x3'],
// }], true)

// cacheTest('getCode for an unspecified block, then for the latest, should return cached response on second request', [{
// method: 'eth_getCode',
// params: ['0x1234'],
// }, {
// method: 'eth_getCode',
// params: ['0x1234', 'latest'],
// }], true)

async function cacheTest(label, basePayloads, shouldCache) {
test(`block-cache - ${label}`, async (t) => {
try {
Expand Down
23 changes: 5 additions & 18 deletions test/block-ref.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ const { PollingBlockTracker } = require('eth-block-tracker');
const GanacheCore = require('ganache-core');
const pify = require('pify');
const EthQuery = require('ethjs-query');
const createBlockRefMiddleware = require('../dist/block-ref');
const providerFromEngine = require('../dist/providerFromEngine');
const providerAsMiddleware = require('../dist/providerAsMiddleware');
const {
createBlockRefMiddleware,
providerFromEngine,
providerAsMiddleware,
} = require('../dist');
const createHitTrackerMiddleware = require('./util/createHitTrackerMiddleware');

test('contructor - no opts', (t) => {
Expand Down Expand Up @@ -35,21 +37,6 @@ test('contructor - empty opts', (t) => {
t.end();
});

// test('provider not ready - shouldnt hang non-"latest" requests', async (t) => {
// t.plan(3)
// const { engine } = createTestSetup()
//
// try {
// const res = await pify(engine.handle).call(engine, { id: 1, method: 'net_listening', params: [] })
// console.log(res)
// t.ok(res, 'Has response')
// t.equal(res.result, true, 'Response result is correct.')
// } catch (err) {
// t.ifError(err, 'No error in response')
// }
// t.end()
// })

test('should rewrite "latest" blockRef to current block', async (t) => {
t.plan(4);
const { engine, query, hitTracker } = createTestSetup();
Expand Down
5 changes: 1 addition & 4 deletions test/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ const test = require('tape');
const concat = require('concat-stream');
const series = require('async/series');
const btoa = require('btoa');
const {
createFetchMiddleware,
createFetchConfigFromReq,
} = require('../dist/fetch');
const { createFetchMiddleware, createFetchConfigFromReq } = require('../dist');

test('fetch - basic', (t) => {
const req = {
Expand Down
6 changes: 4 additions & 2 deletions test/inflight-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ const test = require('tape');
const { JsonRpcEngine } = require('json-rpc-engine');
const { PollingBlockTracker } = require('eth-block-tracker');
const GanacheCore = require('ganache-core');
const providerFromEngine = require('../dist/providerFromEngine');
const createInflightCacheMiddleware = require('../dist/inflight-cache');
const {
providerFromEngine,
createInflightCacheMiddleware,
} = require('../dist');

test('inflight-cache - basic', (t) => {
const { engine } = createTestSetup();
Expand Down
3 changes: 1 addition & 2 deletions test/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ const { JsonRpcEngine } = require('json-rpc-engine');
const EthQuery = require('ethjs-query');
const GanacheCore = require('ganache-core');
const pify = require('pify');
const providerFromEngine = require('../dist/providerFromEngine');
const createWalletMiddleware = require('../dist/wallet');
const { providerFromEngine, createWalletMiddleware } = require('../dist');

const testAddresses = [
'0xbe93f9bacbcffc8ee6663f2647917ed7a20a57bb',
Expand Down

0 comments on commit fc1fd5d

Please sign in to comment.