Skip to content

Commit

Permalink
feat: new method to get the first available RPC
Browse files Browse the repository at this point in the history
  • Loading branch information
gentlementlegen committed Aug 18, 2024
1 parent 5ca9ba3 commit f19192c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
12 changes: 12 additions & 0 deletions tests/rpc-handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,16 @@ describe("RPCHandler", () => {
}, 10000);
}
});

it("Should return the first available RPC", async () => {
const module = await import("../types/rpc-handler");
const rpcHandler = new module.RPCHandler({
...testConfig,
networkId: "1",
rpcTimeout: 1000,
});

const provider = await rpcHandler.getFirstAvailableRpcProvider();
expect(provider).not.toBeNull();
});
});
28 changes: 28 additions & 0 deletions types/rpc-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ import { StorageService } from "./storage-service";

const NO_RPCS_AVAILABLE = "No RPCs available";

function shuffleArray(array: object[]) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}

export class RPCHandler implements HandlerInterface {
private static _instance: RPCHandler | null = null;
private _provider: JsonRpcProvider | null = null;
Expand Down Expand Up @@ -55,6 +62,27 @@ export class RPCHandler implements HandlerInterface {
this.testRpcPerformance.bind(this);
}

/**
* Loops through all RPCs for a given network id and returns a provider with the first successful network.
*/
public async getFirstAvailableRpcProvider() {
const rpcList = [...networkRpcs[this._networkId].rpcs];
shuffleArray(rpcList);
for (const rpc of rpcList) {
try {
const result = await RPCService.makeRpcRequest(rpc.url, this._rpcTimeout, { "Content-Type": "application/json" });
if (result.success) {
return this.createProviderProxy(new JsonRpcProvider({ url: rpc.url, skipFetchSetup: true }, Number(this._networkId)), this);
} else {
console.error(`Failed to reach endpoint ${rpc.url}. ${result.error}`);
}
} catch (err) {
console.error(`Failed to reach endpoint ${rpc.url}. ${err}`);
}
}
return null;
}

public async getFastestRpcProvider(): Promise<JsonRpcProvider> {
let fastest = await this.testRpcPerformance();

Expand Down

0 comments on commit f19192c

Please sign in to comment.