Skip to content

Commit

Permalink
Merge pull request #38 from NillionNetwork/timhm/release-tweaks-and-f…
Browse files Browse the repository at this point in the history
…ixes-0-2-0
  • Loading branch information
tim-hm authored Nov 12, 2024
2 parents 57b5395 + 4060b7b commit fe06676
Show file tree
Hide file tree
Showing 19 changed files with 516 additions and 205 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,15 @@ yarn add @nillion/client-wasm @nillion/client-vms @nillion/client-react-hooks

- 📚 [Official Documentation](https://docs.nillion.com/) - Learn about blind computation and our tooling.
- 💻 [Code examples](./client-vms/tests/) - See the TypeScript client in action
- ⚛️ [React Hooks](./client-react-hooks/)- Learn how to use our React hooks
- ⚛️ [React Hooks](./client-react-hooks/) - Learn how to use our React hooks

## Packages

- `@nillion/client-react-hooks` - React hooks built on `@nillion/client-vms` and `@tanstack/react-query`
- `@nillion/client-vms` - Primary gRPC client combining payments and network operations into a simple API (supports web and Node.js)
- `@nillion/client-vms` - Primary gRPC client combining payments and network operations into a simple API (supports web
and Node.js)
- `@nillion/client-wasm` - Utility functions exported from Rust to WebAssembly

## Contributing

We welcome contributions! Here's how you can help:
Expand Down
6 changes: 2 additions & 4 deletions client-react-hooks/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,14 @@
"dependencies": {
"@nillion/client-vms": "workspace:^",
"@tanstack/react-query": "^5.59.20",
"debug": "^4.3.7",
"pino": "^9.5.0",
"pino-caller": "^3.4.0",
"pino-pretty": "^13.0.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
"react-dom": "^18.3.1",
"zod": "^3.23.8"
},
"devDependencies": {
"@tsconfig/vite-react": "^3.0.2",
"@types/debug": "^4.1.12",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"browserslist": "^4.24.2",
Expand Down
71 changes: 57 additions & 14 deletions client-react-hooks/src/create-client.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,67 @@
import { VmClientBuilder, createSignerFromKey } from "@nillion/client-vms";
import type { VmClientBuilderConfig } from "@nillion/client-vms";
import {
PrivateKeyBase16,
VmClientBuilder,
createSignerFromKey,
} from "@nillion/client-vms";
import { z } from "zod";

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

export const ClientConfig = z.object({
bootnodeUrl: z.string().url(),
chainUrl: z.string().url(),
seed: z.string().min(1),
nilchainPrivateKey0: PrivateKeyBase16,
});
export type ClientConfig = z.infer<typeof ClientConfig>;

const NamedConfig = {
// use with `$ nillion-devnet` default seed
devnet: {
bootnodeUrl: "http://127.0.0.1:37939",
chainUrl: "http://127.0.0.1:48102",
seed: "user-devnet-seed",
nilchainPrivateKey0:
"9a975f567428d054f2bf3092812e6c42f901ce07d9711bc77ee2cd81101f42c5",
},
};

export async function createClient(
network: Network,
_overrides?: Partial<VmClientBuilderConfig>,
overrides?: Partial<ClientConfig>,
) {
switch (network) {
const builder = new VmClientBuilder();
switch (network.toLowerCase()) {
case "devnet": {
const config = { ...NamedConfig.devnet };
const singer = await createSignerFromKey(config.nilchainPrivateKey0);
builder
.seed(config.seed)
.bootnodeUrl(config.bootnodeUrl)
.chainUrl(config.chainUrl)
.signer(singer);
break;
}
case "custom": {
const { nilchainPrivateKey0, seed, bootnodeUrl, chainUrl } =
ClientConfig.parse(overrides);

if (!nilchainPrivateKey0 || !seed || !bootnodeUrl || !chainUrl) {
throw new Error("Missing required config");
}

const singer = await createSignerFromKey(nilchainPrivateKey0);
builder
.seed(seed)
.bootnodeUrl(bootnodeUrl)
.chainUrl(chainUrl)
.signer(singer);
break;
}
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();
throw new Error(`Unsupported network: ${network}`);
}
}

return builder.build();
}
20 changes: 8 additions & 12 deletions client-react-hooks/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
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 { useNilOverwritePermissions } from "./use-nil-overwrite-permissions";
export { useNilPoolStatus } from "./use-nil-pool-status";
export { useNilRetrieveComputeResults } from "./use-nil-retrieve-compute-results";
export { useNilRetrievePermissions } from "./use-nil-retrieve-permissions";
export { useNilRetrieveValues } from "./use-nil-retrieve-values";
export { useNilStoreProgram } from "./use-nil-store-program";
export { useNilStoreValues } from "./use-nil-store-values";
export { useNilUpdatePermissions } from "./use-nil-update-permissions";
export { useNillion } from "./use-nillion";
3 changes: 3 additions & 0 deletions client-react-hooks/src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { createLogger } from "@nillion/client-vms/logger";

export const Log = createLogger("@nillion/client-react-hooks");
51 changes: 0 additions & 51 deletions client-react-hooks/src/logging.ts

This file was deleted.

16 changes: 1 addition & 15 deletions client-react-hooks/src/nillion-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,7 @@ import {
QueryClientContext,
QueryClientProvider,
} from "@tanstack/react-query";
// biome-ignore lint/style/useImportType: NillionContext.Provider requires the React value in scope but biome thinks only the type is needed
import React from "react";
import {
type ReactNode,
createContext,
useContext,
useEffect,
useState,
} from "react";
import { Log } from "./logging";
import { type ReactNode, createContext, useContext, useState } from "react";

export interface NillionContext {
client: VmClient;
Expand All @@ -35,11 +26,6 @@ export const NillionProvider: React.FC<NillionProviderProps> = (
const [queryClient] = useState<QueryClient>(new QueryClient());
const { children } = props;

useEffect(() => {
if (existingQueryClient) Log.debug("Reusing react query context");
else Log.debug("Creating react query context");
}, []);

const context: NillionContext = {
client: props.client,
};
Expand Down
10 changes: 4 additions & 6 deletions client-react-hooks/src/use-nil-store-values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ import type {
ValuesPermissions,
} from "@nillion/client-vms";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Log } from "./logging";
import { type UseNilHook, nilHookBaseResult } from "./nil-hook-base";
import { createStoreCacheKey } from "./query-cache";
import { useNillion } from "./use-nillion";

type ExecuteArgs = {
values: { name: string; value: NadaValue }[];
ttl: TtlDays;
update?: Uuid;
id?: Uuid;
permissions?: ValuesPermissions;
};

Expand All @@ -26,7 +25,7 @@ export const useNilStoreValues = (): UseNilStoreValues => {
const queryClient = useQueryClient();

const mutationFn = async (args: ExecuteArgs): Promise<ExecuteResult> => {
const { values, ttl, update, permissions } = args;
const { values, ttl, id: updateId, permissions } = args;

if (!values.length) {
throw new Error("Values cannot be empty");
Expand All @@ -38,9 +37,8 @@ export const useNilStoreValues = (): UseNilStoreValues => {
builder.permissions(permissions);
}

if (update) {
Log.info("Updating value: %O", update);
builder.update(update);
if (updateId) {
builder.id(updateId);
}

for (const { name, value } of values) {
Expand Down
2 changes: 2 additions & 0 deletions client-vms/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
export * from "./logger";
export * from "./payment";
export * from "./types";
export * from "./util";
export * from "./vm";

export { NadaValue } from "@nillion/client-wasm";
62 changes: 58 additions & 4 deletions client-vms/src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,74 @@
import pino, { type Logger } from "pino";

export const Log = createLogger();
export const Log = createLogger("@nillion/client-vm");

function createLogger(): Logger<never, boolean> {
type PinoWriteFnArgs = {
time: number;
level: string;
module: string;
msg: string | object;
[index: string]: unknown;
};

const levelColors: Record<string, string> = {
debug: "#808080",
info: "#0099ff",
warn: "#ffa500",
error: "#ff0000",
fatal: "#800000",
trace: "#a0a0a0",
};

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

if (isBrowser) {
return pino({
level: "debug",
});
browser: {
asObject: true,
formatters: {
level(label, _numerical) {
return { level: label };
},
},
// @ts-expect-error args type is customised through `child` and `formatters` which pino doesn't recognize
write: (args: PinoWriteFnArgs) => {
if (!localStorage.debug?.includes("@nillion")) {
return;
}

const time = new Date(args.time).toLocaleTimeString();
const { level, module, msg, time: _, ...rest } = args;
const color = levelColors[level.toLowerCase()] || "#000000";
const style = `color: ${color}; font-weight: bold`;
const baseMsg = `${time} %c${level.toUpperCase().padEnd(5)}%c ${module}:`;

const logArgs: unknown[] = [baseMsg, style, ""];

if (typeof msg === "object") {
logArgs[0] += " %O";
logArgs.push({ ...msg, ...rest });
} else {
if (msg) {
logArgs[0] += ` ${msg}`;
}
if (Object.keys(rest).length > 0) {
logArgs[0] += " %O";
logArgs.push(rest);
}
}

console.log(...logArgs);
},
},
}).child({ module });
}

return pino({
level: "debug",
transport: {
target: "pino-pretty",
},
});
}).child({ module });
}
6 changes: 5 additions & 1 deletion client-vms/src/payment/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,11 @@ export class PaymentClient {
{ ...quotePb, request, signed },
{ path: ["client.quote"] },
);
Log.info("Got quote for %s: %O", request.operation.case, quote.fees);
Log.info(
"Quoted %s unil for %s",
quote.fees.total.toString(),
request.operation.case,
);
return quote;
}

Expand Down
2 changes: 1 addition & 1 deletion client-vms/src/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export type OutputBindings = z.infer<typeof OutputBindings>;
export const NadaValuesRecord = z.record(
z.object({
type: z.string(),
value: z.string(),
value: z.union([z.string(), z.instanceof(Uint8Array)]),
}),
);
export type NadaValuesRecord = z.infer<typeof NadaValuesRecord>;
Loading

0 comments on commit fe06676

Please sign in to comment.