Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RPC provider: Infura #7286

Open
wants to merge 10 commits into
base: 4.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/web3-rpc-providers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { QuickNodeProvider } from './web3_provider_quicknode.js';

export * from './types.js';
export * from './web3_provider_quicknode.js';
export * from './web3_provider_infura.js';
export * from './web3_provider.js';
export * from './errors.js';

Expand Down
7 changes: 7 additions & 0 deletions packages/web3-rpc-providers/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,22 @@ export enum Network {

ARBITRUM_MAINNET = 'arbitrum_mainnet',
ARBITRUM_SEPOLIA = 'arbitrum_sepolia',
ARBITRUM_GOERLI = 'arbitrum_goerli',

BASE_MAINNET = 'base_mainnet',
BASE_SEPOLIA = 'base_sepolia',
BASE_GOERLI = 'base_foerli',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
BASE_GOERLI = 'base_foerli',
BASE_GOERLI = 'base_goerli',


OPTIMISM_MAINNET = 'optimism_mainnet',
OPTIMISM_SEPOLIA = 'optimism_sepolia',
OPTIMISM_GOERLI = 'optimism_goerli',

BNB_MAINNET = 'bnb_mainnet',
BNB_TESTNET = 'bnb_testnet',

LINEA_MAINNET = 'linea_mainnet',
LINEA_SEPOLIA = 'linea_sepolia',
LINEA_GOERLI = 'linea_goerli',
}

// Combining the ws types
Expand Down
158 changes: 158 additions & 0 deletions packages/web3-rpc-providers/src/web3_provider_infura.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
This file is part of web3.js.

web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

import {
EthExecutionAPI,
JsonRpcResponseWithResult,
Web3APIMethod,
Web3APIPayload,
Web3APIReturnType,
Web3APISpec,
} from 'web3-types';
import { ResponseError } from 'web3-errors';
import { HttpProviderOptions } from 'web3-providers-http';
import { Transport, Network, SocketOptions } from './types.js';
import { Web3ExternalProvider } from './web3_provider.js';
import { QuickNodeRateLimitError } from './errors.js';

const isValid = (str: string) => str !== undefined && str.trim().length > 0;

export class InfuraProvider<
API extends Web3APISpec = EthExecutionAPI,
> extends Web3ExternalProvider {
// eslint-disable-next-line default-param-last
public constructor(
network: Network = Network.ETH_MAINNET,
transport: Transport = Transport.HTTPS,
token = '',
host = '',
providerConfigOptions?: HttpProviderOptions | SocketOptions,
) {
super(network, transport, token, host, providerConfigOptions);
}

public async request<
Method extends Web3APIMethod<API>,
ResultType = Web3APIReturnType<API, Method>,
>(
payload: Web3APIPayload<EthExecutionAPI, Method>,
requestOptions?: RequestInit,
): Promise<JsonRpcResponseWithResult<ResultType>> {
try {
return await super.request(payload, requestOptions);
} catch (error) {
if (error instanceof ResponseError && error.statusCode === 429) {
throw new QuickNodeRateLimitError(error);
avkos marked this conversation as resolved.
Show resolved Hide resolved
}
throw error;
}
}

// eslint-disable-next-line class-methods-use-this
public getRPCURL(network: Network, transport: Transport, _token: string, _host: string) {
let host = '';
let token = '';

switch (network) {
avkos marked this conversation as resolved.
Show resolved Hide resolved
case Network.ETH_MAINNET:
host = isValid(_host) ? _host : 'mainnet.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.ETH_GOERLI:
host = isValid(_host) ? _host : 'goerli.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.ETH_SEPOLIA:
host = isValid(_host) ? _host : 'sepolia.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;

case Network.ARBITRUM_MAINNET:
host = isValid(_host) ? _host : 'arbitrum-mainnet.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.ARBITRUM_GOERLI:
host = isValid(_host) ? _host : 'arbitrum-goerli.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.ARBITRUM_SEPOLIA:
host = isValid(_host) ? _host : 'arbitrum-sepolia.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.BASE_MAINNET:
host = isValid(_host) ? _host : 'base-mainnet.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.BASE_GOERLI:
host = isValid(_host) ? _host : 'base-goerli.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.BASE_SEPOLIA:
host = isValid(_host) ? _host : 'base-sepolia.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.BNB_MAINNET:
host = isValid(_host) ? _host : 'bnbsmartchain-mainnet.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.BNB_TESTNET:
host = isValid(_host) ? _host : 'bnbsmartchain-testnet.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.LINEA_MAINNET:
host = isValid(_host) ? _host : 'linea-mainnet.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.LINEA_GOERLI:
host = isValid(_host) ? _host : 'linea-goerli.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.LINEA_SEPOLIA:
host = isValid(_host) ? _host : 'linea-sepolia.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.POLYGON_MAINNET:
host = isValid(_host) ? _host : 'polygon-mainnet.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.POLYGON_AMONY:
host = isValid(_host) ? _host : 'polygon-amoy.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.POLYGON_MUMBAI:
host = isValid(_host) ? _host : 'polygon-mumbai.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.OPTIMISM_MAINNET:
host = isValid(_host) ? _host : 'optimism-mainnet.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.OPTIMISM_GOERLI:
host = isValid(_host) ? _host : 'optimism-goerli.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
case Network.OPTIMISM_SEPOLIA:
host = isValid(_host) ? _host : 'optimism-sepolia.infura.io';
token = isValid(_token) ? _token : '3240624a343867035925ff7561eb60dfdba2a668';
break;
default:
throw new Error('Network info not avalible.');
}

return `${transport}://${host}/${token}`;
}
}
43 changes: 42 additions & 1 deletion packages/web3-rpc-providers/test/unit/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { Network, Transport } from '../../src/types';
import { Web3ExternalProvider } from '../../src/web3_provider';
import { QuickNodeRateLimitError } from '../../src/errors';
import { QuickNodeProvider } from '../../src/web3_provider_quicknode';
import { InfuraProvider } from '../../src/web3_provider_infura';

jest.mock('web3-providers-ws', () => {
return {
Expand Down Expand Up @@ -82,7 +83,7 @@ describe('Web3ExternalProvider', () => {
expect(result).toEqual({ result: 'mock-result' });
});

it('should throw a rate limiting error when status code is 429', async () => {
it('QuickNodeProvider: should throw a rate limiting error when status code is 429', async () => {
const network: Network = Network.ETH_MAINNET;
const transport: Transport = Transport.HTTPS;
const token = 'your-token';
Expand Down Expand Up @@ -116,6 +117,46 @@ describe('Web3ExternalProvider', () => {
const provider = new QuickNodeProvider(network, transport, token);
(provider as any).provider = mockHttpProvider;

const payload: Web3APIPayload<EthExecutionAPI, Web3APIMethod<EthExecutionAPI>> = {
method: 'eth_getBalance',
params: ['0x0123456789012345678901234567890123456789', 'latest'],
};
await expect(provider.request(payload)).rejects.toThrow(QuickNodeRateLimitError);
});
it('InfuraProvider: should throw a rate limiting error when status code is 429', async () => {
const network: Network = Network.ETH_MAINNET;
const transport: Transport = Transport.HTTPS;
const token = 'your-token';

const mockHttpProvider = {
request: jest.fn(),
};

// Create a mock ResponseError with status code 429
// Create a mock JsonRpcResponse to pass to ResponseError
const mockJsonRpcResponse: JsonRpcResponse = {
jsonrpc: '2.0',
id: '458408f4-7e2c-43f1-b61d-1fe09a9ee25a',
error: {
code: 429,
message: 'Rate limit exceeded',
},
};

// Create a mock ResponseError with status code 429
const mockError = new ResponseError(
mockJsonRpcResponse,
undefined,
undefined, // request can be undefined
429, // statusCode
);

// Mock the request method to throw the ResponseError
mockHttpProvider.request.mockRejectedValue(mockError);

const provider = new InfuraProvider(network, transport, token);
(provider as any).provider = mockHttpProvider;

const payload: Web3APIPayload<EthExecutionAPI, Web3APIMethod<EthExecutionAPI>> = {
method: 'eth_getBalance',
params: ['0x0123456789012345678901234567890123456789', 'latest'],
Expand Down

This file was deleted.

45 changes: 42 additions & 3 deletions packages/web3/test/integration/web3RPCProviders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

import { mainnet, Network, QuickNodeProvider, Transport } from 'web3-rpc-providers';
import { mainnet, Network, QuickNodeProvider, InfuraProvider, Transport } from 'web3-rpc-providers';
import { Web3 } from '../../src/index';

describe('Web3 RPC Provider Integration tests', () => {
const transports = Object.values(Transport);
const networks = [
const quickNodeNetworks = [
Network.ETH_MAINNET,
Network.ETH_HOLESKY,
Network.ETH_SEPOLIA,
Expand All @@ -33,7 +33,7 @@ describe('Web3 RPC Provider Integration tests', () => {
];

transports.forEach(transport => {
networks.forEach(network => {
quickNodeNetworks.forEach(network => {
it(`QuickNodeProvider should work with ${transport} transport and ${network} network`, async () => {
const provider = new QuickNodeProvider(network, transport);
const web3 = new Web3(provider);
Expand All @@ -48,6 +48,45 @@ describe('Web3 RPC Provider Integration tests', () => {
});
});
});

const infuraNetworks = [
Network.ETH_MAINNET,
Network.ETH_GOERLI,
Network.ETH_SEPOLIA,
Network.ARBITRUM_MAINNET,
Network.ARBITRUM_GOERLI,
Network.ARBITRUM_SEPOLIA,
Network.BASE_MAINNET,
Network.BASE_GOERLI,
Network.BASE_SEPOLIA,
Network.BNB_MAINNET,
Network.BNB_TESTNET,
Network.LINEA_MAINNET,
Network.LINEA_GOERLI,
Network.LINEA_SEPOLIA,
Network.POLYGON_MAINNET,
Network.POLYGON_AMONY,
Network.POLYGON_MUMBAI,
Network.OPTIMISM_MAINNET,
Network.OPTIMISM_GOERLI,
Network.OPTIMISM_SEPOLIA,
];
transports.forEach(transport => {
infuraNetworks.forEach(network => {
it(`InfuraProvider should work with ${transport} transport and ${network} network`, async () => {
const provider = new InfuraProvider(network, transport);
const web3 = new Web3(provider);
const result = await web3.eth.getBlockNumber();

expect(typeof result).toBe('bigint');
expect(result > 0).toBe(true);

if (transport === Transport.WebSocket) {
web3.provider?.disconnect();
}
});
});
});
it(`should work with mainnet provider`, async () => {
const web3 = new Web3(mainnet);
const result = await web3.eth.getBlockNumber();
Expand Down
Loading