Skip to content

Commit

Permalink
Merge pull request #34 from NillionNetwork/timhm/feat-react-hooks-to-…
Browse files Browse the repository at this point in the history
…grpc-client
  • Loading branch information
tim-hm authored Nov 11, 2024
2 parents 9c02539 + 418ab56 commit 6d94db4
Show file tree
Hide file tree
Showing 126 changed files with 3,047 additions and 3,092 deletions.
3 changes: 1 addition & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ jobs:
aws-region: "eu-west-1"
- uses: NillionNetwork/nillion-setup-action@main
with:
version: "v0.7.0-rc.38"
version: "v0.7.0-rc.42"
- uses: actions/setup-python@v5
with:
python-version: "3.12"
Expand All @@ -55,7 +55,6 @@ jobs:
cd client-vms
pnpm vitest --coverage
killall -9 nillion-devnet
- run: cat client-vms/coverage/coverage-summary.json
- uses: davelosert/vitest-coverage-report-action@v2
if: always()
with:
Expand Down
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@
.husky

**/gen-proto
!client-wasm/dist

node_modules
dist
**/coverage
.next
!client-wasm/dist

__pycache__
venv
115 changes: 2 additions & 113 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,114 +1,3 @@
<!-- @formatter:off -->
# &middot; [Nillion](https://nillion.com) &middot;
# Nillion client-ts

[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/facebook/react/blob/main/LICENSE) [![Docs](https://img.shields.io/badge/reference-docs-blue)](https://nillion.pub/client-ts) [![GitHub Issues or Pull Requests](https://img.shields.io/github/issues/NillionNetwork/client-ts)](https://github.com/NillionNetwork/client-ts/issues) [![NPM Version](https://img.shields.io/npm/v/@nillion/client-wasm?label=client-wasm)](https://www.npmjs.com/package/@nillion/client-wasm) [![NPM Version](https://img.shields.io/npm/v/@nillion/client-core?label=client-core)](https://www.npmjs.com/package/@nillion/client-core) [![NPM Version](https://img.shields.io/npm/v/@nillion/client-payments?label=client-payments)](https://www.npmjs.com/package/@nillion/client-payments) [![NPM Version](https://img.shields.io/npm/v/@nillion/client-vms?label=client-vms)](https://www.npmjs.com/package/@nillion/client-vms) [![NPM Version](https://img.shields.io/npm/v/@nillion/client-react-hooks?label=client-react-hooks)](https://www.npmjs.com/package/@nillion/client-react-hooks)

TypeScript client libraries for interacting with a Nillion cluster.

## Table of Contents

- [Prerequisites](#prerequisites)
- [Quick Start](#quick-start)
- [Packages and Package Hierarchy](#packages-and-package-hierarchy)
- [Client Creation and Configuration](#client-creation-and-configuration)
- [React Hooks](#react-hooks)
- [Logging](#logging)
- [Nada Types](#nada-types)
- [Getting Help](#getting-help)

## Prerequisites

- Only browser environments are supported
- All packages are ES modules
- Install a local development cluster with [nilup](https://docs.nillion.com/nilup) and run it with `nillion`
- HTTP headers are needed in order for the browser to load the wasm bundle:
- `Cross-Origin-Embedder-Policy: require-corp`
- `Cross-Origin-Opener-Policy: same-origin`
- The nilchain spawned with [nillion-devnet](https://docs.nillion.com/nillion-devnet) does not support CORS, therefore the recommended workaround is proxy requests to nilchain for local development

## Quick Start

To get started, checkout the full nextjs + react + nillion example is at [examples/nextjs](https://github.com/NillionNetwork/client-ts/tree/main/examples/nextjs).

1. `cd examples/nextjs`
2. In one terminal start a local devnet with `$ nillion-devnet`
3. In another terminal start the nextjs app `$ npm run dev`
4. Browse to `http://localhost:4321`

Note: The keplr browser extension is recommended for production apps.

## Installation

```shell
npm i -P @nillion/client-react-hooks@^0.1.0 @nillion/client-payments@^0.1.0 @nillion/client-vms@^0.1.0 @nillion/client-core@^0.1.0
```

## React

1. Wrap your app with the `NillionProvider`:

```tsx
import { type FC } from "react";

import { NillionProvider } from "@nillion/client-react-hooks";

export const App: FC = () => {
return (
<NillionProvider network="devnet">
{/* your components */}
</NillionProvider>
);
};
```

2. Before using nillion, authenticate the client as show in [Login.tsx](examples/nextjs/app/components/login.tsx)
3. Once authenticated the following hooks can be used:

- `useNillion()`
- `useNilStoreValue()`
- `useNilStoreValues()`
- `useNilUpdateValue()`
- `useNilDeleteValue()`
- `useNilFetchValue()`
- `useNilStoreProgram()`
- `useNilCompute()`
- `useNilComputeOutput()`

## Logging

Logging is on by default for all networks except `Photon`. To enable it for `Photon`:

- Enable the `nillion:*` namespace: `const config: NillionClientConfig = { overrides: () => ({ logging : true }) }` or invoke the global helper: `window.__NILLION.enableLogging()`; or
- If you want granular control, include `nillion:*` in your localStorage debug key: `localStorage.debug = "foo:*,nillion:*"`.

Disable logging with `window.__NILLION.disableLogging()` or remove `nillion:*` from `localStorage.debug`. You may need to reload the window for changes to take effect.

Wasm logging is also an option, but not enabled by default. To enable it:

- Start a websocket server, eg, `websocat -s 11100`
- After the client is initialized run `window__NILLION.enableWasmLogging()`


## Packages and Package Hierarchy

This guide focuses on `@nillion/client-vms` and `@nillion/client-react-hooks` -- other libraries are not intended for direct consumption by the end user.

1. `@nillion/client-wasm` a wasm bundle and web worker for communicating with the cluster
2. `@nillion/client-core` manages wasm initialization and provides a wrapper for wasm functionality
3. `@nillion/client-payments` the nilchain gRPC client
4. `@nillion/client-vms` combines functionality from `client-core` and `client-payments` into a single user-facing API
5. `@nillion/client-react-hooks` based on [ReactQuery](https://github.com/TanStack/query): this package provides convenience react hooks for building frontend apps

```mermaid
graph BT
core["@nillion/client-core"] --> wasm["@nillion/client-wasm"]
payments["@nillion/client-payments"] --> core["@nillion/client-core"]
client["@nillion/client-vms"] --> payments["@nillion/client-payments"]
client["@nillion/client-vms"] --> core["@nillion/client-core"]
react["@nillion/client-react-hooks"] --> core["@nillion/client-core"]
react["@nillion/client-react-hooks"] --> client["@nillion/client-vms"]
```

## Getting Help

Ask for help in the [Nillion Github Discussions](https://github.com/orgs/NillionNetwork/discussions), or if you've found a bug with `client-ts`, [file an issue](https://github.com/NillionNetwork/client-ts/issues).
// TODO: re-write required
31 changes: 17 additions & 14 deletions biome.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
},
"files": {
"ignoreUnknown": false,
"include": ["client-vms/**/*.ts", "client-vms/*.mjs", "**/*.json"],
"ignore": ["client-vms/src/gen-proto"]
"include": ["**/*.ts", "**/*.mjs", "**/*.json", "**/*.tsx"],
"ignore": ["client-vms/src/gen-proto", "client-wasm/dist"]
},
"formatter": {
"enabled": true,
Expand All @@ -20,24 +20,27 @@
"linter": {
"enabled": true,
"rules": {
"all": true,
"recommended": true,
"correctness": {
"all": true,
"noUndeclaredDependencies": "off",
"useImportExtensions": "off",
"noNodejsModules": "off"
"useExhaustiveDependencies": "off"
},
"style": {
"all": true,
"noNonNullAssertion": "off",
"useNamingConvention": "off",
"noParameterProperties": "off"
},
"suspicious": {
"all": false
"noNonNullAssertion": "warn"
}
}
},
"overrides": [
{
"include": ["**/*.test.ts"],
"linter": {
"rules": {
"style": {
"noNonNullAssertion": "off"
}
}
}
}
],
"javascript": {
"formatter": {
"quoteStyle": "double",
Expand Down
18 changes: 15 additions & 3 deletions client-react-hooks/esbuild.config.mjs
Original file line number Diff line number Diff line change
@@ -1,14 +1,26 @@
import { main } from "../esbuild.base.config.mjs";
// @ts-check

import browserslist from "browserslist";
import esbuild from "esbuild";
import { resolveToEsbuildTarget } from "esbuild-plugin-browserslist";

/** @type {esbuild.BuildOptions} */
const config = {
bundle: true,
entryPoints: ["src/index.ts"],
external: [],
format: "esm",
loader: { ".tsx": "tsx", ".ts": "ts" },
logLevel: "info",
outfile: "dist/index.mjs",
packages: "external",
target: resolveToEsbuildTarget(browserslist("defaults"), {
printUnknownTargets: false,
}),
};

await main(config);
if (process.argv.includes("--watch")) {
const ctx = await esbuild.context(config);
await ctx.watch();
} else {
await esbuild.build(config);
}
20 changes: 13 additions & 7 deletions client-react-hooks/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "@nillion/client-react-hooks",
"license": "MIT",
"author": "[email protected]",
"version": "0.1.0",
"version": "0.2.0-rc.1",
"homepage": "https://nillion.pub/client-ts",
"repository": {
"type": "git",
Expand All @@ -16,20 +16,26 @@
}
},
"scripts": {
"clean": "rm -rf dist dist-test",
"typecheck": "tsc",
"build": "node esbuild.config.mjs",
"build:watch": "node esbuild.config.mjs --watch"
},
"dependencies": {
"@nillion/client-vms": "0.1.0",
"@tanstack/react-query": "^5.59.0",
"@nillion/client-vms": "workspace:^",
"@tanstack/react-query": "^5.59.20",
"debug": "^4.3.7",
"react": "^18.3.1"
"pino": "^9.5.0",
"pino-caller": "^3.4.0",
"pino-pretty": "^13.0.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@tsconfig/vite-react": "^3.0.2",
"@types/debug": "^4.1.12",
"@types/react": "^18.3.11",
"browserslist": "^4.24.0",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"browserslist": "^4.24.2",
"esbuild-plugin-browserslist": "^0.15.0"
},
"files": ["dist", "src"]
Expand Down
15 changes: 0 additions & 15 deletions client-react-hooks/src/cache-key.ts

This file was deleted.

24 changes: 24 additions & 0 deletions client-react-hooks/src/create-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { VmClientBuilder, createSignerFromKey } from "@nillion/client-vms";
import type { VmClientBuilderConfig } from "@nillion/client-vms";

export type Network = "testnet" | "devnet" | "custom";

export async function createClient(
network: Network,
_overrides?: Partial<VmClientBuilderConfig>,
) {
switch (network) {
default: {
const singer = await createSignerFromKey(
"9a975f567428d054f2bf3092812e6c42f901ce07d9711bc77ee2cd81101f42c5",
);
return await new VmClientBuilder()
.authTokenTtl(1)
.seed("tests")
.bootnodeUrl("http://127.0.0.1:43207")
.chainUrl("http://127.0.0.1:48102")
.signer(singer)
.build();
}
}
}
30 changes: 17 additions & 13 deletions client-react-hooks/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
export * from "./nillion-provider";
export * from "./use-nil-compute";
export * from "./use-nil-compute-output";
export * from "./use-nil-delete-value";
export * from "./use-nil-fetch-store-acl";
export * from "./use-nil-fetch-value";
export * from "./use-nil-set-store-acl";
export * from "./use-nil-store-program";
export * from "./use-nil-store-value";
export * from "./use-nil-store-values";
export * from "./use-nil-update-value";
export * from "./use-nillion";
export * from "./use-nillion-auth";
export { Log } from "./logging";

export { NillionProvider } from "./nillion-provider";

export { createClient } from "./create-client";

export { useNillion } from "./use-nillion";
export { useNilPoolStatus } from "./use-nil-pool-status";
export { useNilStoreValues } from "./use-nil-store-values";
export { useNilRetrieveValues } from "./use-nil-retrieve-values";
export { useNilDeleteValues } from "./use-nil-delete-values";
export { useNilRetrievePermissions } from "./use-nil-retrieve-permissions";
export { useNilUpdatePermissions } from "./use-nil-update-permissions";
export { useNilOverwritePermissions } from "./use-nil-overwrite-permissions";
export { useNilStoreProgram } from "./use-nil-store-program";
export { useNilInvokeCompute } from "./use-nil-invoke-compute";
export { useNilRetrieveComputeResults } from "./use-nil-retrieve-compute-results";
52 changes: 50 additions & 2 deletions client-react-hooks/src/logging.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,51 @@
import debug from "debug";
import pino, { type Logger } from "pino";

export const Log = debug("nillion:react-hooks");
export const Log = createLogger();

function createLogger(): Logger<never, boolean> {
const isBrowser = Boolean(globalThis.window);

if (isBrowser) {
// @ts-ignore
return pino({
level: "debug",
browser: {
asObject: true,
formatters: {
level(label, _numberical) {
return { level: label };
},
},
// write: (obj: {
// level: string;
// module: string;
// msg: string | object;
// time: number | string;
// [key: string]: any;
// }) => {
// debugger;
// const time = new Date(obj.time).toLocaleTimeString();
// const { level, module, msg, time: _, ...rest } = obj;
// const baseMsg = `${time} ${level.toUpperCase()} ${module}:`;
//
// if (typeof msg === "object") {
// console.log(`${baseMsg} %O`, { ...msg, ...rest });
// } else if (Object.keys(rest).length > 0) {
// console.log(`${baseMsg} ${msg ?? ""} %O`, rest);
// } else {
// console.log(`${baseMsg} ${msg ?? ""}`.trim());
// }
//
// console.log(baseMsg);
// },
},
}).child({ module: "client-react-hooks" });
}

return pino({
level: "debug",
transport: {
target: "pino-pretty",
},
}).child({ module: "client-react-hooks" });
}
Loading

0 comments on commit 6d94db4

Please sign in to comment.