Skip to content
This repository has been archived by the owner on Aug 1, 2024. It is now read-only.

Commit

Permalink
chore(examples): add a nextjs example
Browse files Browse the repository at this point in the history
  • Loading branch information
piotr-roslaniec committed Sep 21, 2023
1 parent 0b7ba57 commit 6f1567a
Show file tree
Hide file tree
Showing 18 changed files with 729 additions and 304 deletions.
3 changes: 2 additions & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# `integration-examples`

This directory contains a set of examples showing how to integrate `@nucypher/*` into your application.
This directory contains a set of examples showing how to integrate `@nucypher/*`
into your application.
3 changes: 3 additions & 0 deletions examples/nextjs/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
35 changes: 35 additions & 0 deletions examples/nextjs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
48 changes: 48 additions & 0 deletions examples/nextjs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with
[`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the
result.

You can start editing the page by modifying `app/page.tsx`. The page
auto-updates as you edit the file.

This project uses
[`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to
automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js
features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out
[the Next.js GitHub repository](https://github.com/vercel/next.js/) - your
feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the
[Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme)
from the creators of Next.js.

Check out our
[Next.js deployment documentation](https://nextjs.org/docs/deployment) for more
details.
4 changes: 4 additions & 0 deletions examples/nextjs/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};

module.exports = nextConfig;
29 changes: 29 additions & 0 deletions examples/nextjs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"private": true,
"scripts": {
"build": "next build",
"check": "pnpm lint && pnpm type-check && pnpm build",
"dev": "next dev",
"lint": "next lint",
"start": "next start",
"type-check": "tsc -p tsconfig.build.json"
},
"dependencies": {
"@nucypher/shared": "workspace:*",
"@types/node": "20.6.3",
"@types/react": "18.2.22",
"@types/react-dom": "18.2.7",
"eslint": "8.49.0",
"eslint-config-next": "13.5.2",
"ethers": "^5.7.2",
"next": "13.5.2",
"react": "18.2.0",
"react-dom": "18.2.0",
"typescript": "5.2.2"
},
"peerDependencies": {
"@nucypher/shared": "workspace:*",
"ethers": "^5.7.2",
"typescript": "5.2.2"
}
}
21 changes: 21 additions & 0 deletions examples/nextjs/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';

const inter = Inter({ subsets: ['latin'] });

export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
};

export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
);
}
161 changes: 161 additions & 0 deletions examples/nextjs/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
'use client';
import {
Alice,
Bob,
EnactedPolicy,
getPorterUri,
initialize,
SecretKey,
toHexString,
} from '@nucypher/shared';
import { ethers } from 'ethers';
import { useEffect, useState } from 'react';

function App() {
const [isInit, setIsInit] = useState<boolean>(false);
const [provider, setProvider] = useState<
ethers.providers.Web3Provider | undefined
>();
const [alice, setAlice] = useState<Alice | undefined>();
const [bob, setBob] = useState<Bob | undefined>();
const [policy, setPolicy] = useState<EnactedPolicy>();

const initNucypher = async () => {
// await initialize();
await initialize();
setIsInit(true);
};

const loadWeb3Provider = async () => {
if (!window.ethereum) {
console.error('You need to connect to the MetaMask extension');
}
const provider = new ethers.providers.Web3Provider(window.ethereum, 'any');

const { chainId } = await provider.getNetwork();
if (![137, 80001].includes(chainId)) {
console.error('You need to connect to the Mumbai or Polygon network');
}

await provider.send('eth_requestAccounts', []);
setProvider(provider);
};

useEffect(() => {
initNucypher();
loadWeb3Provider();
}, []);

if (!isInit || !provider) {
return <div>Loading...</div>;
}

console.log({ Alice, Bob, getPorterUri, SecretKey, toHexString });

const makeAlice = () => {
const alice = Alice.fromSecretKey(SecretKey.random());
setAlice(alice);
};

const makeBob = () => {
const bob = Bob.fromSecretKey(SecretKey.random());
setBob(bob);
};

const makeRemoteBob = (bob: Bob) => {
const { decryptingKey, verifyingKey } = bob;
return { decryptingKey, verifyingKey };
};

const makeCharacters = () => {
makeAlice();
makeBob();
};

const getRandomLabel = () => `label-${new Date().getTime()}`;

const runExample = async () => {
if (!provider) {
console.error('You need to connect to the MetaMask extension');
return;
}

if (!alice || !bob) {
console.error('You need to create Alice and Bob');
return;
}

const remoteBob = makeRemoteBob(bob);
const threshold = 2;
const shares = 3;
const startDate = new Date();
const endDate = new Date(Date.now() + 1000 * 60 * 60 * 24 * 30); // In 30 days
const policyParams = {
bob: remoteBob,
label: getRandomLabel(),
threshold,
shares,
startDate,
endDate,
};

const policy = await alice.grant(
provider,
provider.getSigner(),
getPorterUri('tapir'), // Testnet porter
policyParams,
);

console.log('Policy created');
setPolicy(policy);
};

return (
<div className="App">
<header className="App-header">
<div className="stack left">
<div>
<div>Create Alice and Bob</div>
<button onClick={() => makeCharacters()}>Go</button>
<div>
{alice && (
<span>
Alice:{' '}
{`0x${toHexString(alice.verifyingKey.toCompressedBytes())}`}
</span>
)}
</div>
<div>
{bob && (
<span>
Bob:{' '}
{`0x${toHexString(bob.verifyingKey.toCompressedBytes())}`}
</span>
)}
</div>
</div>

{alice && bob && (
<div>
<div>Create a policy</div>
<button onClick={() => runExample()}>Go</button>
</div>
)}

{policy && (
<div>
<div>
Policy id: <div>{toHexString(policy.id.toBytes())}</div>
</div>
<div>
Policy: <div>{JSON.stringify(policy)}</div>
</div>
</div>
)}
</div>
</header>
</div>
);
}

export default App;
14 changes: 14 additions & 0 deletions examples/nextjs/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"extends": "./tsconfig.json",
"include": ["src"],
"compilerOptions": {
"outDir": "dist",
"rootDir": "src",
"noEmit": true
},
"references": [
{
"path": "../../packages/shared/tsconfig.es.json"
}
]
}
27 changes: 27 additions & 0 deletions examples/nextjs/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
8 changes: 5 additions & 3 deletions examples/react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

Shows how to integrate `@nucypher/*` into a React application.

In order to load WASM dependencies of `@nucypher/*`, we override the `react-scripts` configuration with `craco`. For
more details, see the `craco.config.js` file.
In order to load WASM dependencies of `@nucypher/*`, we override the
`react-scripts` configuration with `craco`. For more details, see the
`craco.config.js` file.

## Usage

Expand All @@ -12,4 +13,5 @@ pnpm install
pnpm start
```

Next, go to [http://127.0.0.1:3000/](http://127.0.0.1:8080/) in your browser and inspect the UI and the JS console.
Next, go to [http://127.0.0.1:3000/](http://127.0.0.1:8080/) in your browser and
inspect the UI and the JS console.
2 changes: 1 addition & 1 deletion examples/react/public/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
Expand Down
Loading

0 comments on commit 6f1567a

Please sign in to comment.