-
Notifications
You must be signed in to change notification settings - Fork 0
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
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
35bc102
refactor: use the Failover Provider
jtourkos 46b959f
Merge branch 'main' into use-failover-provider
jtourkos 67c931d
refactor: use one rpc config env var
jtourkos 834edc0
refactor: remove leftovers
jtourkos a871221
build: add script for checking env vars on build
jtourkos File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,8 @@ dotenv.config(); | |
type RpcConfig = { | ||
url: string; | ||
accessToken?: string; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. not related to this PR, but does anything actually validate that |
||
fallbackUrl?: string; | ||
fallbackAccessToken?: string; | ||
}; | ||
|
||
export default { | ||
|
@@ -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(',') || [], | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
inappSettings
?either way, for now I think this is still OK — gonna get a bit crazy when we add more networks soon though.
There was a problem hiding this comment.
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?