Skip to content

Commit

Permalink
WIP: Update after dependency updates
Browse files Browse the repository at this point in the history
  • Loading branch information
legobeat committed Sep 9, 2023
1 parent 57331a1 commit b71f0fa
Show file tree
Hide file tree
Showing 18 changed files with 302 additions and 203 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ module.exports = {
files: ['*.ts'],
extends: ['@metamask/eslint-config-typescript'],
rules: {
'@typescript-eslint/prefer-nullish-coalescing': 'off',
// TODO: resolve warnings and remove to make into errors
'@typescript-eslint/consistent-type-definitions': 'off',
'@typescript-eslint/naming-convention': 'off',
Expand Down
2 changes: 1 addition & 1 deletion src/block-cache.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { providerFromEngine } from '@metamask/eth-json-rpc-provider';
import { JsonRpcEngine } from '@metamask/json-rpc-engine';
import { PollingBlockTracker } from 'eth-block-tracker';
import { JsonRpcEngine } from 'json-rpc-engine';
import pify from 'pify';

import { createBlockCacheMiddleware } from '.';
Expand Down
19 changes: 11 additions & 8 deletions src/block-cache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';
import type { PollingBlockTracker } from 'eth-block-tracker';
import type { JsonRpcRequest } from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';

import { projectLogger, createModuleLogger } from './logging-utils';
import type {
Expand Down Expand Up @@ -51,7 +51,7 @@ class BlockCacheStrategy {
}

async get(
request: JsonRpcRequest<unknown>,
request: JsonRpcRequest,
requestedBlockNumber: string,
): Promise<Block | undefined> {
// lookup block cache
Expand All @@ -62,7 +62,7 @@ class BlockCacheStrategy {
}

async set(
request: JsonRpcRequest<unknown>,
request: JsonRpcRequest,
requestedBlockNumber: string,
result: Block,
): Promise<void> {
Expand All @@ -81,7 +81,7 @@ class BlockCacheStrategy {
blockCache[identifier] = result;
}

canCacheRequest(request: JsonRpcRequest<unknown>): boolean {
canCacheRequest(request: JsonRpcRequest): boolean {
// check request method
if (!canCache(request.method)) {
return false;
Expand All @@ -96,7 +96,7 @@ class BlockCacheStrategy {
return true;
}

canCacheResult(request: JsonRpcRequest<unknown>, result: Block): boolean {
canCacheResult(request: JsonRpcRequest, result: Block): boolean {
// never cache empty values (e.g. undefined)
if (emptyValues.includes(result as any)) {
return false;
Expand Down Expand Up @@ -135,7 +135,10 @@ class BlockCacheStrategy {

export function createBlockCacheMiddleware({
blockTracker,
}: BlockCacheMiddlewareOptions = {}): JsonRpcCacheMiddleware<unknown, unknown> {
}: BlockCacheMiddlewareOptions = {}): JsonRpcCacheMiddleware<
JsonRpcParams,
Json
> {
// validate options
if (!blockTracker) {
throw new Error(
Expand All @@ -153,7 +156,7 @@ export function createBlockCacheMiddleware({
};

return createAsyncMiddleware(
async (req: JsonRpcRequestToCache<unknown>, res, next) => {
async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {
// allow cach to be skipped if so specified
if (req.skipCache) {
return next();
Expand Down
22 changes: 12 additions & 10 deletions src/block-ref-rewrite.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type { Json, JsonRpcParams } from '@metamask/utils';
import type { PollingBlockTracker } from 'eth-block-tracker';
import type { JsonRpcMiddleware } from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';

import { blockTagParamIndex } from './utils/cache';

Expand All @@ -10,7 +11,10 @@ interface BlockRefRewriteMiddlewareOptions {

export function createBlockRefRewriteMiddleware({
blockTracker,
}: BlockRefRewriteMiddlewareOptions = {}): JsonRpcMiddleware<unknown, unknown> {
}: BlockRefRewriteMiddlewareOptions = {}): JsonRpcMiddleware<
JsonRpcParams,
Json
> {
if (!blockTracker) {
throw Error(
'BlockRefRewriteMiddleware - mandatory "blockTracker" option is missing.',
Expand All @@ -24,13 +28,11 @@ export function createBlockRefRewriteMiddleware({
return next();
}
// skip if not "latest"
let blockRef: string | undefined = Array.isArray(req.params)
? req.params[blockRefIndex]
: undefined;
// omitted blockRef implies "latest"
if (blockRef === undefined) {
blockRef = 'latest';
}
const blockRef: string | undefined =
Array.isArray(req.params) && req.params[blockRefIndex]
? (req.params[blockRefIndex] as string)
: // omitted blockRef implies "latest"
'latest';

if (blockRef !== 'latest') {
return next();
Expand Down
4 changes: 2 additions & 2 deletions src/block-ref.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { providerFromEngine } from '@metamask/eth-json-rpc-provider';
import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { JsonRpcEngine } from '@metamask/json-rpc-engine';
import { PollingBlockTracker } from 'eth-block-tracker';
import type { JsonRpcMiddleware } from 'json-rpc-engine';
import { JsonRpcEngine } from 'json-rpc-engine';

import { createBlockRefMiddleware } from '.';
import {
Expand Down
14 changes: 8 additions & 6 deletions src/block-ref.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import clone from 'clone';
import type { PollingBlockTracker } from 'eth-block-tracker';
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type {
JsonRpcMiddleware,
Json,
JsonRpcParams,
PendingJsonRpcResponse,
} from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';
} from '@metamask/utils';
import clone from 'clone';
import type { PollingBlockTracker } from 'eth-block-tracker';
import pify from 'pify';

import { projectLogger, createModuleLogger } from './logging-utils';
Expand All @@ -22,7 +24,7 @@ const log = createModuleLogger(projectLogger, 'block-ref');
export function createBlockRefMiddleware({
provider,
blockTracker,
}: BlockRefMiddlewareOptions = {}): JsonRpcMiddleware<unknown, unknown> {
}: BlockRefMiddlewareOptions = {}): JsonRpcMiddleware<JsonRpcParams, Json> {
if (!provider) {
throw Error('BlockRefMiddleware - mandatory "provider" option is missing.');
}
Expand Down
14 changes: 6 additions & 8 deletions src/block-tracker-inspector.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type { JsonRpcParams, PendingJsonRpcResponse } from '@metamask/utils';
import type { PollingBlockTracker } from 'eth-block-tracker';
import type {
JsonRpcMiddleware,
PendingJsonRpcResponse,
} from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';

import { projectLogger, createModuleLogger } from './logging-utils';

Expand Down Expand Up @@ -37,7 +35,7 @@ function hasProperty<ObjectToCheck, Property extends ValidPropertyType>(
}

function getResultBlockNumber(
response: PendingJsonRpcResponse<unknown>,
response: PendingJsonRpcResponse<JsonRpcParams>,
): string | undefined {
const { result } = response;
if (
Expand All @@ -58,8 +56,8 @@ function getResultBlockNumber(
export function createBlockTrackerInspectorMiddleware({
blockTracker,
}: BlockTrackerInspectorMiddlewareOptions): JsonRpcMiddleware<
unknown,
unknown
JsonRpcParams,
JsonRpcParams
> {
return createAsyncMiddleware(async (req, res, next) => {
if (!futureBlockRefRequests.includes(req.method)) {
Expand Down
19 changes: 10 additions & 9 deletions src/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { EthereumRpcError } from 'eth-rpc-errors';
import { ethErrors } from 'eth-rpc-errors';
import type { JsonRpcMiddleware, JsonRpcRequest } from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type { JsonRpcError, DataWithOptionalCause } from '@metamask/rpc-errors';
import { rpcErrors } from '@metamask/rpc-errors';
import type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';

import type { Block } from './types';
import { timeout } from './utils/timeout';
Expand All @@ -17,7 +18,7 @@ const RETRIABLE_ERRORS: string[] = [
'Failed to fetch',
];

export interface PayloadWithOrigin extends JsonRpcRequest<unknown> {
export interface PayloadWithOrigin extends JsonRpcRequest {
origin?: string;
}
interface Request {
Expand Down Expand Up @@ -53,7 +54,7 @@ export function createFetchMiddleware({
fetch: typeof global.fetch;
rpcUrl: string;
originHttpHeaderKey?: string;
}): JsonRpcMiddleware<unknown, unknown> {
}): JsonRpcMiddleware<JsonRpcParams, Json> {
return createAsyncMiddleware(async (req, res, _next) => {
const { fetchUrl, fetchParams } = createFetchConfigFromReq({
btoa,
Expand Down Expand Up @@ -165,7 +166,7 @@ export function createFetchConfigFromReq({

// prepare payload
// copy only canonical json rpc properties
const payload: JsonRpcRequest<unknown> = {
const payload: JsonRpcRequest = {
id: req.id,
jsonrpc: req.jsonrpc,
method: req.method,
Expand Down Expand Up @@ -215,11 +216,11 @@ function normalizeUrlFromParsed(parsedUrl: URL): string {
return result;
}

function createRatelimitError(): EthereumRpcError<unknown> {
function createRatelimitError(): JsonRpcError<DataWithOptionalCause> {
return rpcErrors.internal({ message: `Request is being rate limited.` });
}

function createTimeoutError(): EthereumRpcError<unknown> {
function createTimeoutError(): JsonRpcError<DataWithOptionalCause> {
let msg = `Gateway timeout. The request took too long to process. `;
msg += `This can happen when querying logs over too wide a block range.`;
return rpcErrors.internal({ message: msg });
Expand Down
2 changes: 1 addition & 1 deletion src/inflight-cache.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { JsonRpcEngine } from 'json-rpc-engine';
import { JsonRpcEngine } from '@metamask/json-rpc-engine';
import pify from 'pify';

import { createInflightCacheMiddleware } from '.';
Expand Down
34 changes: 18 additions & 16 deletions src/inflight-cache.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,30 @@
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type {
JsonRpcParams,
Json,
PendingJsonRpcResponse,
} from '@metamask/utils';
import clone from 'clone';
import type { PendingJsonRpcResponse } from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';

import { projectLogger, createModuleLogger } from './logging-utils';
import type { JsonRpcRequestToCache, JsonRpcCacheMiddleware } from './types';
import { cacheIdentifierForRequest } from './utils/cache';

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

const log = createModuleLogger(projectLogger, 'inflight-cache');

export function createInflightCacheMiddleware(): JsonRpcCacheMiddleware<
unknown,
unknown
JsonRpcParams,
Json
> {
const inflightRequests: InflightRequest = {};

return createAsyncMiddleware(
async (req: JsonRpcRequestToCache<unknown>, res, next) => {
async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {
// allow cach to be skipped if so specified
if (req.skipCache) {
return next();
Expand Down Expand Up @@ -68,23 +72,21 @@ export function createInflightCacheMiddleware(): JsonRpcCacheMiddleware<
);

async function createActiveRequestHandler(
res: PendingJsonRpcResponse<unknown>,
res: PendingJsonRpcResponse<Json>,
activeRequestHandlers: RequestHandlers[],
): Promise<void> {
const { resolve, promise } = deferredPromise();
activeRequestHandlers.push(
(handledRes: PendingJsonRpcResponse<unknown>) => {
// append a copy of the result and error to the response
res.result = clone(handledRes.result);
res.error = clone(handledRes.error);
resolve();
},
);
activeRequestHandlers.push((handledRes: PendingJsonRpcResponse<Json>) => {
// append a copy of the result and error to the response
res.result = clone(handledRes.result);
res.error = clone(handledRes.error);
resolve();
});
return promise;
}

function handleActiveRequest(
res: PendingJsonRpcResponse<unknown>,
res: PendingJsonRpcResponse<Json>,
activeRequestHandlers: RequestHandlers[],
): void {
// use setTimeout so we can resolve our original request first
Expand Down
12 changes: 7 additions & 5 deletions src/providerAsMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import type {
JsonRpcMiddleware,
Json,
JsonRpcParams,
PendingJsonRpcResponse,
} from 'json-rpc-engine';
} from '@metamask/utils';

export function providerAsMiddleware(
provider: SafeEventEmitterProvider,
): JsonRpcMiddleware<unknown, unknown> {
): JsonRpcMiddleware<JsonRpcParams, Json> {
return (req, res, _next, end) => {
// send request to provider
provider.sendAsync(
Expand All @@ -26,15 +28,15 @@ export function providerAsMiddleware(

export function ethersProviderAsMiddleware(
provider: SafeEventEmitterProvider,
): JsonRpcMiddleware<unknown, unknown> {
): JsonRpcMiddleware<JsonRpcParams, Json> {
return (req, res, _next, end) => {
// send request to provider
provider.send(
req,
(err: unknown, providerRes: PendingJsonRpcResponse<any>) => {
// forward any error
if (err) {
// TODO: Remove this cast when next major `json-rpc-engine` release is out
// TODO: Remove this cast when next major `@metamask/json-rpc-engine` release is out
// The next release changes how errors are propogated.
return end(err as Error);
}
Expand Down
7 changes: 5 additions & 2 deletions src/retryOnEmpty.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { providerFromEngine } from '@metamask/eth-json-rpc-provider';
import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import type {
JsonRpcMiddleware,
JsonRpcRequest,
} from '@metamask/json-rpc-engine';
import { JsonRpcEngine } from '@metamask/json-rpc-engine';
import { PollingBlockTracker } from 'eth-block-tracker';
import type { JsonRpcMiddleware, JsonRpcRequest } from 'json-rpc-engine';
import { JsonRpcEngine } from 'json-rpc-engine';

import { createRetryOnEmptyMiddleware } from '.';
import type { ProviderRequestStub } from '../test/util/helpers';
Expand Down
Loading

0 comments on commit b71f0fa

Please sign in to comment.