Skip to content

Commit

Permalink
refactor: taco react and nextjs example (#419)
Browse files Browse the repository at this point in the history
  • Loading branch information
piotr-roslaniec authored Nov 27, 2023
2 parents 111897a + 413f1b5 commit b891d08
Show file tree
Hide file tree
Showing 11 changed files with 302 additions and 127 deletions.
1 change: 1 addition & 0 deletions examples/taco/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"type-check": "tsc -p tsconfig.build.json"
},
"dependencies": {
"@nucypher/shared": "workspace:*",
"@nucypher/taco": "workspace:*",
"@types/node": "20.6.3",
"@types/react": "18.2.37",
Expand Down
1 change: 1 addition & 0 deletions examples/taco/nextjs/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import '../../styles/global.css'

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

Expand Down
136 changes: 72 additions & 64 deletions examples/taco/nextjs/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,34 @@
'use client';
import {
conditions,
decrypt,
domains,
encrypt,
fromBytes,
getPorterUri,
initialize,
} from '@nucypher/taco';
import { ethers } from 'ethers';
import { hexlify } from "ethers/lib/utils";
import { useEffect, useState } from 'react';
import {fromHexString} from "@nucypher/shared";
import {conditions, domains, fromBytes, toHexString} from '@nucypher/taco';
import {ethers} from 'ethers';
import {hexlify} from 'ethers/lib/utils';
import {useEffect, useState} from 'react';

import useTaco from '../hooks/useTaco';



// eslint-disable-next-line @typescript-eslint/no-explicit-any
declare const window: any;

const message = 'this is a secret';
const ritualId = 5; // Replace with your own ritual ID
const domain = domains.TESTNET;

function App() {
const [isInit, setIsInit] = useState(false);
const [provider, setProvider] = useState<
ethers.providers.Web3Provider | undefined
>();
const [message, setMessage] = useState('this is a secret')
const [encrypting, setEncrypting] = useState(false)
const [encryptedText, setEncryptedText] = useState<string | undefined>(
'',
);
const [decrypting, setDecrypting] = useState(false)
const [decryptedMessage, setDecryptedMessage] = useState<string | undefined>(
'',
);

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

const loadWeb3Provider = async () => {
if (!window.ethereum) {
console.error('You need to connect to your wallet first');
Expand All @@ -52,64 +50,74 @@ function App() {
};

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

const { isInit, encryptDataToBytes, decryptDataFromBytes } = useTaco({
domain,
provider,
ritualId,
});

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

const runExample = async () => {
if (!window.ethereum) {
console.error('You need to connect to your wallet first');
}

await initialize();
const encryptMessage = async () => {
if(!provider) return;
setEncrypting(true)
try {
const signer = provider.getSigner();
const hasPositiveBalance = new conditions.RpcCondition({
chain: 80001,
method: 'eth_getBalance',
parameters: [':userAddress', 'latest'],
returnValueTest: {
comparator: '>',
value: 0,
},
});

const ritualId = 5; // Replace with your own ritual ID
const domain = domains.TESTNET;
console.log('Encrypting message...');
const encryptedBytes = await encryptDataToBytes(
message,
hasPositiveBalance,
signer,
);
if (encryptedBytes) {
setEncryptedText(toHexString(encryptedBytes))
}
} catch (e) {
console.log(e)
}
setEncrypting(false)
}

const provider = new ethers.providers.Web3Provider(window.ethereum!, 'any');
await provider.send('eth_requestAccounts', []);
const signer = provider.getSigner();

console.log('Encrypting message...');
const hasPositiveBalance = new conditions.RpcCondition({
chain: 80001,
method: 'eth_getBalance',
parameters: [':userAddress', 'latest'],
returnValueTest: {
comparator: '>',
value: 0,
},
});
const messageKit = await encrypt(
provider,
domain,
message,
hasPositiveBalance,
ritualId,
signer,
);

console.log('Decrypting message...');
const decryptedMessage = await decrypt(
provider,
domain,
messageKit,
getPorterUri(domain),
signer,
);

setDecryptedMessage(fromBytes(decryptedMessage));
const decryptMessage = async () => {
if(!encryptedText || !provider) return
try {
setDecrypting(true)
const signer = provider.getSigner();

console.log('Decrypting message...');
const decryptedMessage = await decryptDataFromBytes(
fromHexString(encryptedText),
signer,
);
if (decryptedMessage) {
setDecryptedMessage(fromBytes(decryptedMessage));
}
} catch (e) {
console.log(e)
}
setDecrypting(false)
};

return (
<div>
<h1>Secret message: {message}</h1>
{decryptedMessage && <h1>Decrypted message: {decryptedMessage}</h1>}
<button onClick={runExample}>Run example</button>
<h2>Secret message: <input value={message} onChange={(e) => setMessage(e.target.value)} onClick={encryptMessage}/> <button onClick={encryptMessage}>Encrypt</button> {encrypting && 'Encrypting...'}</h2>
<h2>Encrypted message: <input value={encryptedText} onChange={(e) => setEncryptedText(e.target.value)} /> <button onClick={decryptMessage}>Decrypt</button> {decrypting && 'Decrypting...'}</h2>
{decryptedMessage && <h2>Decrypted message: {decryptedMessage}</h2>}
</div>
);
}
Expand Down
68 changes: 68 additions & 0 deletions examples/taco/nextjs/src/hooks/useTaco.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import {
conditions,
decrypt,
Domain,
encrypt,
getPorterUri,
initialize,
ThresholdMessageKit,
} from '@nucypher/taco';
import { ethers } from 'ethers';
import { useCallback, useEffect, useState } from 'react';

export default function useTaco({
ritualId,
domain,
provider,
}: {
ritualId: number;
domain: Domain;
provider: ethers.providers.Provider | undefined;
}) {
const [isInit, setIsInit] = useState(false);

useEffect(() => {
initialize().then(() => setIsInit(true));
}, []);

const decryptDataFromBytes = useCallback(
async (encryptedBytes: Uint8Array, signer?: ethers.Signer) => {
if (!isInit || !provider) return;
const messageKit = ThresholdMessageKit.fromBytes(encryptedBytes);
return decrypt(
provider,
domain,
messageKit,
getPorterUri(domain),
signer,
);
},
[isInit, provider, domain],
);

const encryptDataToBytes = useCallback(
async (
message: string,
condition: conditions.Condition,
encryptorSigner: ethers.Signer,
) => {
if (!isInit || !provider) return;
const messageKit = await encrypt(
provider,
domain,
message,
condition,
ritualId,
encryptorSigner,
);
return messageKit.toBytes();
},
[isInit, provider, domain, ritualId],
);

return {
isInit,
decryptDataFromBytes,
encryptDataToBytes,
};
}
7 changes: 7 additions & 0 deletions examples/taco/nextjs/styles/global.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
input {
font-size: 20px;
}

button {
font-size: 15px;
}
1 change: 1 addition & 0 deletions examples/taco/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
]
},
"dependencies": {
"@nucypher/shared": "workspace:*",
"@nucypher/taco": "workspace:*",
"react": "^18.2.0",
"react-dom": "^18.2.0"
Expand Down
Loading

0 comments on commit b891d08

Please sign in to comment.