Skip to content

Commit

Permalink
Merge pull request ubiquity#15 from Keyrxng/refactor/polymorphic-tests
Browse files Browse the repository at this point in the history
Refactor/polymorphic tests
  • Loading branch information
rndquu committed May 21, 2024
2 parents 04c51a6 + 7933f84 commit 5ea0d81
Show file tree
Hide file tree
Showing 28 changed files with 2,248 additions and 2,442 deletions.
2 changes: 1 addition & 1 deletion .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@
"dictionaries": ["typescript", "node", "software-terms"],
"import": ["@cspell/dict-typescript/cspell-ext.json", "@cspell/dict-node/cspell-ext.json", "@cspell/dict-software-terms"],
"ignoreRegExpList": ["[0-9a-fA-F]{6}"],
"ignoreWords": ["Rpcs", "ethersproject", "publicnode", "WXDAI", "XDAI", "chainlist", "Knip"]
"ignoreWords": ["Rpcs", "ethersproject", "publicnode", "WXDAI", "XDAI", "chainlist", "Knip", "LOCALSTORAGE"]
}
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"**/*.d.ts",
"**/*.test.ts",
"**/*-test.ts",
"tests/",
"jest.config.ts",
"knip.ts",
"build",
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/bump-version.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ on:
workflow_dispatch:
inputs:
bump:
description: 'bump type: major, minor or patch'
default: ''
description: "bump type: major, minor or patch"
default: ""

jobs:
release:
Expand All @@ -25,7 +25,7 @@ jobs:
with:
node-version: "20.10.0"
registry-url: https://registry.npmjs.org/

- name: Bump version
run: |
git config --global user.email "github-actions[bot]@users.noreply.github.com"
Expand Down
13 changes: 10 additions & 3 deletions .github/workflows/jest-testing.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
name: Run Jest testing suite
on:
workflow_dispatch:
pull_request_target:
push:
branches:
- main
pull_request:
types: [opened, synchronize]
workflow_dispatch:

env:
NODE_ENV: "test"
Expand All @@ -21,10 +24,14 @@ jobs:
- uses: actions/checkout@master
with:
fetch-depth: 0

- name: Install dependencies
run: yarn install

- name: Build & Run test suite
run: |
yarn && yarn build
yarn test | tee ./coverage.txt && exit ${PIPESTATUS[0]}
- name: Jest Coverage Comment
# Ensures this step is run even on previous step failure (e.g. test failed)
if: always()
Expand Down
26 changes: 13 additions & 13 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
nodeLinker: node-modules
supportedArchitectures:
supportedArchitectures:
os:
- 'current'
- 'darwin'
- 'linux'
- 'win32'
- "current"
- "darwin"
- "linux"
- "win32"
cpu:
- 'current'
- 'x64'
- 'x86'
- 'arm'
- 'ia32'
- "current"
- "x64"
- "x86"
- "arm"
- "ia32"
libc:
- 'current'
- 'glibc'
- 'musl'
- "current"
- "glibc"
- "musl"
5 changes: 2 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

## 1.0.0 (2024-03-22)


### Features

* Web3 RPC Handler (npm package) ([#1](https://github.com/ubiquity/rpc-handler/issues/1)) ([#4](https://github.com/ubiquity/rpc-handler/issues/4)) ([0d964b0](https://github.com/ubiquity/rpc-handler/commit/0d964b09871b09fa5ce441d3339254d171ecae62))
* workflow ([300603c](https://github.com/ubiquity/rpc-handler/commit/300603cbdc788b44c80a366021142f99842590ba))
- Web3 RPC Handler (npm package) ([#1](https://github.com/ubiquity/rpc-handler/issues/1)) ([#4](https://github.com/ubiquity/rpc-handler/issues/4)) ([0d964b0](https://github.com/ubiquity/rpc-handler/commit/0d964b09871b09fa5ce441d3339254d171ecae62))
- workflow ([300603c](https://github.com/ubiquity/rpc-handler/commit/300603cbdc788b44c80a366021142f99842590ba))
47 changes: 16 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,20 @@ yarn add @ubiquity-dao/rpc-handler

## Usage

- Import the handler for your environment

###### Browser
- Config options with null are optional, but still need to be passed as `null`

```typescript
import { HandlerConstructorConfig } from "@ubiquity-dao/rpc-handler/dist/esm/src/handler";
import { RPCHandler } from "@ubiquity-dao/rpc-handler/dist/esm/src/rpc-handler";
import { RPCHandler, HandlerConstructorConfig } from "@ubiquity-dao/rpc-handler/";

export function useHandler(networkId: number) {
const config: HandlerConstructorConfig = {
networkId,
autoStorage: true,
cacheRefreshCycles: 5,
networkId: 1,
rpcTimeout: 1500,
autoStorage: false,
cacheRefreshCycles: 10,
networkName: null, // the name will be deduced from the networkId, unless using a custom network
networkRpcs: null, // same as networkName, but for injecting additional RPCs
runtimeRpcs: null, // same as networkRpcs, although these are considered error-free
};
// No RPCs are tested at this point
return new RPCHandler(config);
Expand All @@ -46,32 +47,10 @@ const handler = useHandler(networkId);
app.provider = await handler.getFastestRpcProvider();
```

###### Node.js

```typescript
import { HandlerConstructorConfig } from "@ubiquity-dao/rpc-handler/dist/cjs/src/handler";
import { RPCHandler } from "@ubiquity-dao/rpc-handler/dist/cjs/src/rpc-handler";

const config: HandlerConstructorConfig = {
networkId: 100;
autoStorage: false, // only applies to local storage
cacheRefreshCycles: 5,
};

async function main() {
const handler = new RPCHandler(config);
return await handler.getFastestRpcProvider();
}

main().then(console.log).catch(console.error);
```

#### Notes

- The RPCs are not tested on instantiation, but are tested on each call to `handler.getFastestRpcProvider()` or `handler.testRpcPerformance()`

- `networkId` is the only required configuration option

- See the full [config](src\handler.ts) object (optionally passed in the constructor) for more options

- Local storage is not enabled by default, but can be enabled by passing `autoStorage: true` in the config object
Expand All @@ -80,8 +59,14 @@ main().then(console.log).catch(console.error);

## Testing

- In order to run the tests the package must first be built, this is required otherwise `networkRpcs` will be empty as the RPCs are injected at build time
- Tests have a specific build in order to run `yarn test` will produce this build and run the tests.
- After testing, re-build using `yarn build` for the original build

```bash
yarn test
```

- This below will only work after `yarn build` has been run and will fail under test conditions
```bash
npx tsx tests/script-test.ts
```
86 changes: 86 additions & 0 deletions build/esbuild-build-tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import esbuild from "esbuild";
import chainlist from "../lib/chainlist/constants/extraRpcs";
import chainIDList from "../lib/chainlist/constants/chainIds.json";
import path from "path";
import * as fs from "fs";

const typescriptEntries = ["tests/mocks/rpc-service.ts", "tests/mocks/rpc-handler.ts", "tests/mocks/handler.ts"];
export const entries = [...typescriptEntries];
const extraRpcs: Record<string, string[]> = {};
// this flattens all the rpcs into a single object, with key names that match the networkIds. The arrays are just of URLs per network ID.

Object.keys(chainlist).forEach((networkId) => {
const officialUrls = chainlist[networkId].rpcs.filter((rpc) => typeof rpc === "string");
const extraUrls: string[] = chainlist[networkId].rpcs.filter((rpc) => rpc.url !== undefined && rpc.tracking === "none").map((rpc) => rpc.url);

extraRpcs[networkId] = [...officialUrls, ...extraUrls].filter((rpc) => rpc.startsWith("https://"));
});

export const esBuildContext: esbuild.BuildOptions = {
entryPoints: entries,
bundle: true,

outdir: "dist",
define: createEnvDefines({ extraRpcs, chainIDList }),
};

async function main() {
try {
await buildForEnvironments();
await buildIndex();
} catch (err) {
console.error(err);
process.exit(1);
}
}

main();

async function buildForEnvironments() {
ensureDistDir();

await esbuild
.build({
...esBuildContext,
tsconfig: "tsconfig.tests.json",
platform: "node",
outdir: "dist/tests/mocks",
format: "cjs",
})
.then(() => {
console.log("Node.js esbuild complete");
})
.catch((err) => {
console.error(err);
process.exit(1);
});
}

async function buildIndex() {
await esbuild.build({
entryPoints: ["index.ts"],
bundle: true,
format: "cjs",
outfile: "dist/index.js",
define: createEnvDefines({ extraRpcs, chainIDList }),
});

console.log("Index build complete.");
}

function createEnvDefines(generatedAtBuild: Record<string, unknown>): Record<string, string> {
const defines: Record<string, string> = {};

Object.keys(generatedAtBuild).forEach((key) => {
defines[key] = JSON.stringify(generatedAtBuild[key]);
});

return defines;
}

function ensureDistDir() {
const distPath = path.resolve(__dirname, "dist");
if (!fs.existsSync(distPath)) {
fs.mkdirSync(distPath, { recursive: true });
}
}
Loading

0 comments on commit 5ea0d81

Please sign in to comment.