Skip to content

Commit

Permalink
JsonRpcProvider: Basic access authentication support
Browse files Browse the repository at this point in the history
With this patch, `JsonRpcProvider` accepts a url with basic authentication
credentials like this:

```
const PoktEndpoint = 'https://scott:[email protected]';
const provider = new JsonRpcProvider({
  rpcUrl: PoktEndpoint,
  dispatchers: [PoktEndpoint],
});
```
  • Loading branch information
msmania committed Feb 16, 2024
1 parent f13a37e commit ca11c1c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ import {
} from "./config.js";

// Instantiate a provider for querying information on the chain!
//
// MAINNET_RPC_URL and an element of DISPATCHERS is a string representing an
// endpoint URL to the Pocket Network which may or may not contains basic
// authentication credentials e.g. "https://scott:[email protected]".
export const provider = new JsonRpcProvider({
rpcUrl: MAINNET_RPC_URL,
// If you'll Instantiate a relayer, you need to add dispatchers as well
Expand Down
19 changes: 15 additions & 4 deletions packages/provider/src/json-rpc-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,25 @@ export class JsonRpcProvider implements AbstractProvider {
]
: this.rpcUrl

const routedRpcUrl = `${finalRpcUrl}${route}`
const headers = {
'Content-Type': 'application/json',
};

const url = new URL(route, finalRpcUrl);
if (url.username || url.password) {
const credential =
Buffer.from(`${url.username}:${url.password}`).toString('base64');
headers['Authorization'] = `Basic ${credential}`;
url.username = '';
url.password = '';
}

const routedRpcUrl = url.toString();

const rpcResponse = await fetch(routedRpcUrl, {
method: 'POST',
signal: controller.signal as AbortSignal,
headers: {
'Content-Type': 'application/json',
},
headers: headers,
body: JSON.stringify(body),
}).catch((error) => {
debug(`${routedRpcUrl} attempt ${retriesPerformed + 1} failure`)
Expand Down

0 comments on commit ca11c1c

Please sign in to comment.