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

refactor: use the Failover Provider #28

Merged
merged 5 commits into from
Oct 15, 2024
Merged
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
15 changes: 15 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,31 @@ PORT=string # Optional. The API server port. Defaults to 8080.
NETWORK=string # Required. The network to connect to. See `SupportedChains` in `types.ts` for supported networks.

# You should provide at least one of the following RPC URLs:

RPC_URL_MAINNET=string # The RPC URL for the Mainnet provider.
RPC_ACCESS_TOKEN_MAINNET=string # Optional. The access token to use for the RPC. If specified, it will be used as a bearer token in the `Authorization` header.
FALLBACK_RPC_URL_MAINNET=string # Optional. The fallback RPC URL for the Mainnet provider. If specified, it will be used if the main RPC URL fails.
FALLBACK_RPC_ACCESS_TOKEN_MAINNET=string # Optional. The access token to use for the fallback RPC. If specified, it will be used as a bearer token in the `Authorization` header.

RPC_URL_SEPOLIA=string # The RPC URL for the Sepolia provider.
RPC_ACCESS_TOKEN_SEPOLIA=string # Optional. The access token to use for the RPC. If specified, it will be used as a bearer token in the `Authorization` header.
FALLBACK_RPC_URL_SEPOLIA=string # Optional. The fallback RPC URL for the Sepolia provider. If specified, it will be used if the main RPC URL fails.
FALLBACK_RPC_ACCESS_TOKEN_SEPOLIA=string # Optional. The access token to use for the fallback RPC. If specified, it will be used as a bearer token in the `Authorization` header.

RPC_URL_OPTIMISM_SEPOLIA=string # The RPC URL for the Optimism Sepolia provider.
RPC_ACCESS_TOKEN_OPTIMISM_SEPOLIA=string # Optional. The access token to use for the RPC. If specified, it will be used as a bearer token in the `Authorization` header.
FALLBACK_RPC_URL_OPTIMISM_SEPOLIA=string # Optional. The fallback RPC URL for the Optimism Sepolia provider. If specified, it will be used if the main RPC URL fails.
FALLBACK_RPC_ACCESS_TOKEN_OPTIMISM_SEPOLIA=string # Optional. The access token to use for the fallback RPC. If specified, it will be used as a bearer token in the `Authorization` header.

RPC_URL_POLYGON_AMOY=string # The RPC URL for the Polygon Amoy provider.
RPC_ACCESS_TOKEN_POLYGON_AMOY=string # Optional. The access token to use for the RPC. If specified, it will be used as a bearer token in the `Authorization` header.
FALLBACK_RPC_URL_POLYGON_AMOY=string # Optional. The fallback RPC URL for the Polygon Amoy provider. If specified, it will be used if the main RPC URL fails.
FALLBACK_RPC_ACCESS_TOKEN_POLYGON_AMOY=string # Optional. The access token to use for the fallback RPC. If specified, it will be used as a bearer token in the `Authorization` header.

RPC_URL_FILECOIN=string # The RPC URL for the Filecoin provider.
RPC_ACCESS_TOKEN_FILECOIN=string # Optional. The access token to use for the RPC. If specified, it will be used as a bearer token in the `Authorization` header.
FALLBACK_RPC_URL_FILECOIN=string # Optional. The fallback RPC URL for the Filecoin provider. If specified, it will be used if the main RPC URL fails.
FALLBACK_RPC_ACCESS_TOKEN_FILECOIN=string # Optional. The access token to use for the fallback RPC. If specified, it will be used as a bearer token in the `Authorization` header.
Copy link
Contributor

Choose a reason for hiding this comment

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

so many env vars! what do you think about taking a single RPC_CONFIG env var that takes a JSON string with a strict schema that we validate with e.g. zod in appSettings?

either way, for now I think this is still OK — gonna get a bit crazy when we add more networks soon though.

Copy link
Contributor Author

@jtourkos jtourkos Oct 14, 2024

Choose a reason for hiding this comment

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

Yes, I agree. Take a look at this commit (67c931d). Was this what you had in mind?


PUBLIC_API_KEYS=string # Required. Comma-separated list of strings API keys that rate limit is applied to.
DRIPS_API_KEY=string # Required. API key withouth rate limit.
Expand Down
102 changes: 102 additions & 0 deletions src/common/FailoverProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import type {
JsonRpcApiProviderOptions,
JsonRpcPayload,
JsonRpcResult,
Networkish,
} from 'ethers';
import { JsonRpcProvider, FetchRequest } from 'ethers';

/**
* A `JsonRpcProvider` that transparently fails over to a list of backup JSON-RPC endpoints.
*/
export default class FailoverJsonRpcProvider extends JsonRpcProvider {
private readonly _rpcEndpoints: (string | FetchRequest)[];

/**
* @param rpcEndpoints An array of JSON-RPC endpoints. The order determines the failover order.
*/
constructor(
rpcEndpoints: (string | FetchRequest)[],
network?: Networkish,
options?: JsonRpcApiProviderOptions,
) {
super(rpcEndpoints[0], network, options);

this._rpcEndpoints = rpcEndpoints;
}

/**
* Overrides the `_send` method to try each endpoint until the request succeeds.
*
* @param payload - The JSON-RPC payload or array of payloads to send.
* @returns A promise that resolves to the result of the first successful JSON-RPC call.
*/
public override async _send(
payload: JsonRpcPayload | Array<JsonRpcPayload>,
): Promise<Array<JsonRpcResult>> {
// The actual sending of the request is the same as in the base class.
// The only difference is that we're creating a new `FetchRequest` for each endpoint,
// instead of getting the `request` from `_getConnection()`, which will return the *primary* (first) endpoint.

const errors: { rpcEndpoint: string; error: any }[] = [];

// Try each endpoint, in order.
for (const rpcEndpoint of this._rpcEndpoints) {
try {
let request: FetchRequest;

if (typeof rpcEndpoint === 'string') {
request = new FetchRequest(rpcEndpoint);
} else {
request = rpcEndpoint.clone();
}

request.body = JSON.stringify(payload);
request.setHeader('content-type', 'application/json');
const response = await request.send();
response.assertOk();

let resp = response.bodyJson;
if (!Array.isArray(resp)) {
resp = [resp];
}

return resp;
} catch (error: any) {
const endpointUrl = this._getRpcEndpointUrl(rpcEndpoint);
errors.push({ rpcEndpoint: endpointUrl, error });
}
}

// All endpoints failed. Throw an error containing the details.
const errorMessages = errors
.map(
(e) =>
`Endpoint '${e.rpcEndpoint}' failed with error: ${e.error.message}.`,
)
.join('\n');

const aggregatedError = new Error(
`All RPC endpoints failed:\n${errorMessages}`,
) as Error & { errors: { rpcEndpoint: string; error: any }[] };

aggregatedError.errors = errors;

throw aggregatedError;
}

/**
* Returns a copy of the endpoint URLs used by the provider.
*/
public getRpcEndpointUrls(): string[] {
return this._rpcEndpoints.map(this._getRpcEndpointUrl);
}

private _getRpcEndpointUrl(rpcEndpoint: string | FetchRequest): string {
if (typeof rpcEndpoint === 'string') {
return rpcEndpoint;
}

return rpcEndpoint.url;
}
}
13 changes: 13 additions & 0 deletions src/common/appSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ dotenv.config();
type RpcConfig = {
url: string;
accessToken?: string;
Copy link
Contributor

Choose a reason for hiding this comment

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

not related to this PR, but does anything actually validate that url exists? if the env var is undefined, it'll be undefined at runtime too, no?

fallbackUrl?: string;
fallbackAccessToken?: string;
};

export default {
Expand All @@ -14,22 +16,33 @@ export default {
MAINNET: {
url: process.env.RPC_URL_MAINNET,
accessToken: process.env.RPC_ACCESS_TOKEN_MAINNET,
fallbackUrl: process.env.FALLBACK_RPC_URL_MAINNET,
fallbackAccessToken: process.env.FALLBACK_RPC_ACCESS_TOKEN_MAINNET,
},
SEPOLIA: {
url: process.env.RPC_URL_SEPOLIA,
accessToken: process.env.RPC_ACCESS_TOKEN_SEPOLIA,
fallbackUrl: process.env.FALLBACK_RPC_URL_SEPOLIA,
fallbackAccessToken: process.env.FALLBACK_RPC_ACCESS_TOKEN_SEPOLIA,
},
OPTIMISM_SEPOLIA: {
url: process.env.RPC_URL_OPTIMISM_SEPOLIA,
accessToken: process.env.RPC_ACCESS_TOKEN_OPTIMISM_SEPOLIA,
fallbackUrl: process.env.FALLBACK_RPC_URL_OPTIMISM_SEPOLIA,
fallbackAccessToken:
process.env.FALLBACK_RPC_ACCESS_TOKEN_OPTIMISM_SEPOLIA,
},
POLYGON_AMOY: {
url: process.env.RPC_URL_POLYGON_AMOY,
fallbackUrl: process.env.FALLBACK_RPC_URL_POLYGON_AMOY,
accessToken: process.env.RPC_ACCESS_TOKEN_POLYGON_AMOY,
fallbackAccessToken: process.env.FALLBACK_RPC_ACCESS_TOKEN_POLYGON_AMOY,
},
FILECOIN: {
url: process.env.RPC_URL_FILECOIN,
fallbackUrl: process.env.FALLBACK_RPC_URL_FILECOIN,
accessToken: process.env.RPC_ACCESS_TOKEN_FILECOIN,
fallbackAccessToken: process.env.FALLBACK_RPC_ACCESS_TOKEN_FILECOIN,
},
} as Record<SupportedChain, RpcConfig | undefined>,
publicApiKeys: process.env.PUBLIC_API_KEYS?.split(',') || [],
Expand Down
41 changes: 19 additions & 22 deletions src/common/dripsContracts.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
FetchRequest,
JsonRpcProvider,
WebSocketProvider,
ethers,
} from 'ethers';
import { FetchRequest, ethers } from 'ethers';
import appSettings from './appSettings';
import type { AddressDriver, Drips, RepoDriver } from '../generated/contracts';
import {
Expand All @@ -21,6 +16,7 @@ import type {
ProjectId,
} from './types';
import queryableChains from './queryableChains';
import FailoverJsonRpcProvider from './FailoverProvider';

const chainConfigs: Record<
SupportedChain,
Expand Down Expand Up @@ -65,7 +61,7 @@ const chainConfigs: Record<
const { rpcConfigs } = appSettings;

const providers: {
[network in SupportedChain]?: JsonRpcProvider | WebSocketProvider;
[network in SupportedChain]?: FailoverJsonRpcProvider;
} = {};

function createAuthFetchRequest(rpcUrl: string, token: string): FetchRequest {
Expand All @@ -79,25 +75,26 @@ function createAuthFetchRequest(rpcUrl: string, token: string): FetchRequest {
Object.values(SupportedChain).forEach((network) => {
const rpcConfig = rpcConfigs[network];

if (rpcConfig?.url) {
const rpcUrl = rpcConfig.url;
if (!rpcConfig) {
return;
}

const { url, accessToken, fallbackUrl, fallbackAccessToken } = rpcConfig;

let provider: JsonRpcProvider | WebSocketProvider | null = null;
const primaryEndpoint = accessToken
? createAuthFetchRequest(url, accessToken)
: url;

if (rpcUrl.startsWith('http')) {
provider = rpcConfig?.accessToken
? new JsonRpcProvider(
createAuthFetchRequest(rpcUrl, rpcConfig.accessToken),
)
: new JsonRpcProvider(rpcUrl);
} else if (rpcUrl.startsWith('wss')) {
provider = new WebSocketProvider(rpcUrl);
} else {
shouldNeverHappen(`Invalid RPC URL: ${rpcUrl}`);
}
const rpcEndpoints = [primaryEndpoint];

providers[network] = provider;
if (fallbackUrl) {
const fallbackEndpoint = fallbackAccessToken
? createAuthFetchRequest(fallbackUrl, fallbackAccessToken)
: fallbackUrl;
rpcEndpoints.push(fallbackEndpoint);
}

providers[network] = new FailoverJsonRpcProvider(rpcEndpoints);
});

const dripsContracts: {
Expand Down
10 changes: 10 additions & 0 deletions src/environment.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,28 @@ declare global {

RPC_URL_MAINNET: string | undefined;
RPC_ACCESS_TOKEN_MAINNET: string | undefined;
FALLBACK_RPC_URL_MAINNET: string | undefined;
FALLBACK_RPC_ACCESS_TOKEN_MAINNET: string | undefined;

RPC_URL_SEPOLIA: string | undefined;
FALLBACK_RPC_URL_SEPOLIA: string | undefined;
RPC_ACCESS_TOKEN_SEPOLIA: string | undefined;
FALLBACK_RPC_ACCESS_TOKEN_SEPOLIA: string | undefined;

RPC_URL_OPTIMISM_SEPOLIA: string | undefined;
FALLBACK_RPC_URL_OPTIMISM_SEPOLIA: string | undefined;
RPC_ACCESS_TOKEN_OPTIMISM_SEPOLIA: string | undefined;
FALLBACK_RPC_ACCESS_TOKEN_OPTIMISM_SEPOLIA: string | undefined;

RPC_URL_POLYGON_AMOY: string | undefined;
FALLBACK_RPC_URL_POLYGON_AMOY: string | undefined;
RPC_ACCESS_TOKEN_POLYGON_AMOY: string | undefined;
FALLBACK_RPC_ACCESS_TOKEN_POLYGON_AMOY: string | undefined;

RPC_URL_FILECOIN: string | undefined;
FALLBACK_RPC_URL_FILECOIN: string;
RPC_ACCESS_TOKEN_FILECOIN: string | undefined;
FALLBACK_RPC_ACCESS_TOKEN_FILECOIN: string | undefined;

PUBLIC_API_KEYS: string;
DRIPS_API_KEY: string;
Expand Down
Loading