From 146fd2d0c6e732f56ff31e20271aa37a2bc403c7 Mon Sep 17 00:00:00 2001 From: enekoox Date: Fri, 6 Dec 2024 08:54:32 +0100 Subject: [PATCH] Add failover RPC transport example (#3614) * Add failover RPC transport example * removing unnecessary sleep from failover example --- README.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c5e9ae1db138..aca8df190356 100644 --- a/README.md +++ b/README.md @@ -304,7 +304,36 @@ const rpc = createSolanaRpcFromTransport(retryingTransport); Support for handling network failures can be implemented in the transport itself. Here’s an example of some failover logic integrated into a transport: ```ts -// TODO: Your turn; send us a pull request with an example. +import { createDefaultRpcTransport, createSolanaRpcFromTransport, type RpcTransport } from '@solana/web3.js'; + +// List of RPC endpoints for failover. +const rpcEndpoints = [ + 'https://mainnet-beta.my-server-1.com', + 'https://mainnet-beta.my-server-2.com', + 'https://mainnet-beta.my-server-3.com', + 'https://mainnet-beta.my-server-3.com', +]; + +// Create an array of transports from the endpoints. +const transports = rpcEndpoints.map((url) => createDefaultRpcTransport({ url })); + +// A failover transport that switches to the next transport on failure. +async function failoverTransport(...args: Parameters): Promise { + let lastError; + for (const transport of transports) { + try { + return await transport(...args); + } catch (err) { + lastError = err; + console.warn(`Transport failed: ${err}. Trying next transport...`); + } + } + // If all transports fail, throw the last error. + throw lastError; +} + +// Create the RPC client using the failover transport. +const rpc = createSolanaRpcFromTransport(failoverTransport); ``` ### Augmenting/Constraining the RPC API