Skip to content

Commit

Permalink
Iterate
Browse files Browse the repository at this point in the history
  • Loading branch information
serefyarar committed Aug 31, 2024
1 parent 7433b8c commit 7e4ad37
Show file tree
Hide file tree
Showing 12 changed files with 1,092 additions and 93 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/web-app-ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ jobs:
DOCKER_TAG: indexnetwork/web3-web-app:${{ steps.build-time.outputs.time }}
DOCKER_REGISTRY: 236785930124.dkr.ecr.us-east-1.amazonaws.com
run: |
docker build --build-arg API_URL=${API_URL} -t $DOCKER_TAG .
docker build --build-arg INFURA_API_KEY=${{ secrets.INFURA_API_KEY }} --build-arg API_URL=${API_URL} -t $DOCKER_TAG .
docker tag $DOCKER_TAG $DOCKER_REGISTRY/$DOCKER_TAG
docker push $DOCKER_REGISTRY/$DOCKER_TAG
docker tag $DOCKER_TAG $DOCKER_REGISTRY/indexnetwork/web3-web-app:latest-${GITHUB_REF#refs/heads/}
Expand Down
2 changes: 2 additions & 0 deletions web-app/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ WORKDIR /app
ARG API_URL
ENV NEXT_PUBLIC_API_URL=$API_URL

ARG INFURA_API_KEY
ENV INFURA_API_KEY=$INFURA_API_KEY
COPY . .
RUN yarn
RUN yarn build
Expand Down
1 change: 1 addition & 0 deletions web-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@lit-protocol/contracts-sdk": "4.1.1",
"@lit-protocol/lit-node-client": "4.1.1",
"@lit-protocol/uint8arrays": "4.1.1",
"@metamask/sdk-react": "^0.28.0",
"@nanostores/react": "ai/react",
"@radix-ui/react-alert-dialog": "^1.0.4",
"@radix-ui/react-dialog": "^1.0.4",
Expand Down
2 changes: 2 additions & 0 deletions web-app/src/app/new/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ import { useAuth } from "@/context/AuthContext";
import { DIDSession } from "did-session";
import { createIndex } from "@/store/api";
import { useAppDispatch } from "@/store/store";
import { useSDK } from "@metamask/sdk-react";

const Home: NextPage = () => {
const { transactionApprovalWaiting, handleTransactionCancel } = useApp();

const { provider: ethProvider, sdk } = useSDK();
const { setSession } = useAuth();

const { api, ready: apiReady } = useApi();
Expand Down
10 changes: 0 additions & 10 deletions web-app/src/components/layout/base/Navbar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,6 @@ const Navbar = ({
const router = useRouter();
const { leftSidebarOpen, setLeftTabKey, setLeftSidebarOpen } = useApp();

/*
const [showTestnetWarning, setShowTestnetWarning] = useState(false);
useEffect(() => {
const handleChainChanged = (newChainId: string) => setShowTestnetWarning(newChainId !== appConfig.testNetwork.chainId);
handleChainChanged(window.ethereum?.chainId);
window.ethereum?.on("chainChanged", handleChainChanged);
return () => window.ethereum?.removeListener("chainChanged", handleChainChanged);
}, []);
*/

useEffect(() => {
if (sticky) {
if (typeof yOffSet === "number") {
Expand Down
13 changes: 13 additions & 0 deletions web-app/src/components/layout/site/AppLayout/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,25 @@ import { ReactNode } from "react";
import { Toaster } from "react-hot-toast";
import { Provider } from "react-redux";
import store from "@/store/store";
import { MetaMaskProvider } from "@metamask/sdk-react";

interface AppLayoutProps {
children: ReactNode;
}

export const AppLayout = ({ children }: AppLayoutProps) => (
<Provider store={store}>
<MetaMaskProvider
debug={false}
sdkOptions={{
dappMetadata: {
name: "Index Network",
url: window.location.href,
},
infuraAPIKey: process.env.INFURA_API_KEY,
}}
>

<AuthProvider>
<APIProvider>
<PlausibleProvider domain="index.network">
Expand All @@ -25,5 +37,6 @@ export const AppLayout = ({ children }: AppLayoutProps) => (
</PlausibleProvider>
</APIProvider>
</AuthProvider>
</MetaMaskProvider>
</Provider>
);
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import Image from "next/image";
import Link from "next/link";
import React, { useCallback, useState } from "react";
import toast from "react-hot-toast";
import { useSDK } from "@metamask/sdk-react";
import { CodeSnippetReact, CodeSnippetsWithTabs } from "./CodeSnippets";
import SettingsModal, { SettingsModalStep } from "./SettingsModal";

Expand All @@ -17,6 +18,7 @@ const IndexSettingsTabSection: React.FC<IndexSettingsTabSectionProps> = () => {
const [secretKey, setSecretKey] = useState<string | undefined>();
const { isOwner } = useRole();
const [showModal, setShowModal] = useState(false);
const { provider: ethProvider, sdk } = useSDK();

const [step, setStep] = useState<SettingsModalStep>("waiting");

Expand All @@ -29,7 +31,11 @@ const IndexSettingsTabSection: React.FC<IndexSettingsTabSectionProps> = () => {
const handleCreate = useCallback(async () => {
setShowModal(true);
try {
const sessionResponse = await didService.getNewDIDSession();
if (!ethProvider || !sdk) {
throw new Error(`No metamask`);
}

const sessionResponse = await didService.getNewDIDSession(ethProvider, sdk);
setSecretKey(sessionResponse);
setStep("done");
} catch (e) {
Expand Down
63 changes: 33 additions & 30 deletions web-app/src/context/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,7 @@ import { randomBytes, randomString } from "@stablelib/random";
import { DIDSession, createDIDCacao, createDIDKey } from "did-session";
import React, { useCallback, useEffect, useState } from "react";
import toast from "react-hot-toast";

declare global {
interface Window {
ethereum: any;
}
}
import { useSDK } from "@metamask/sdk-react";

export enum AuthStatus {
CONNECTED = "CONNECTED",
Expand Down Expand Up @@ -54,6 +49,9 @@ export const AuthContext =
export const AuthProvider = ({ children }: any) => {
const SESSION_KEY = "did";

const { provider: ethProvider, sdk } = useSDK();


const [session, setSession] = useState<DIDSession | undefined>();
const [status, setStatus] = useState<AuthStatus>(AuthStatus.IDLE);

Expand Down Expand Up @@ -92,26 +90,19 @@ export const AuthProvider = ({ children }: any) => {
return !existingSession.isExpired;
}, [session]);

const startSession = useCallback(async (): Promise<void> => {
const ethProvider = window.ethereum;

// if (ethProvider.chainId !== appConfig.testNetwork.chainId) {
/*const switchRes = await switchTestNetwork();
if (!switchRes) {
throw new Error("Network error.");
}*/
// }
const startSession = useCallback(async (): Promise<boolean> => {

if (!ethProvider) {
return false
}

// request ethereum accounts.
const addresses = await ethProvider.enable({
method: "eth_requestAccounts",
});
const accounts = await sdk?.connect();

const accountId = await getAccountId(ethProvider, addresses[0]);
const accountId = await getAccountId(ethProvider, accounts?.[0]);
const normAccount = normalizeAccountId(accountId);
const keySeed = randomBytes(32);
const didKey = await createDIDKey(keySeed);

console.log(didKey)
const now = new Date();
const twentyFiveDaysLater = new Date(
now.getTime() + 365 * 24 * 60 * 60 * 1000,
Expand All @@ -130,21 +121,27 @@ export const AuthProvider = ({ children }: any) => {
resources: ["ceramic://*"],
});

siweMessage.signature = await ethProvider.request({
const signature = await ethProvider.request({
method: "personal_sign",
params: [siweMessage.signMessage(), getAddress(accountId.address)],
});
if (signature === null) {
throw new Error("Failed to sign message");
}

siweMessage.signature = signature as string
const cacao = Cacao.fromSiweMessage(siweMessage);
const did = await createDIDCacao(didKey, cacao);
const newSession = new DIDSession({ cacao, keySeed, did });

localStorage.setItem(SESSION_KEY, newSession.serialize());
setSession(newSession);
}, []);
return true
}, [ethProvider]);

const authenticate = useCallback(async () => {
if (!window.ethereum) {

if (!ethProvider) {
console.warn(
"Skipping wallet connection: No injected Ethereum provider found.",
);
Expand All @@ -162,20 +159,26 @@ export const AuthProvider = ({ children }: any) => {

if (!sessionIsValid) {
console.log("No valid session found, starting new session...");
await startSession();
const sessionResponse = await startSession();
if (sessionResponse) {
console.log("Session is valid, connecting...");

setStatus(AuthStatus.CONNECTED);
toast.success("Successfully connected to your wallet.");
trackEvent(WALLET_CONNECTED);
}else {
console.error("Error during authentication process");
setStatus(AuthStatus.FAILED);
}
}

console.log("Session is valid, connecting...");

setStatus(AuthStatus.CONNECTED);
toast.success("Successfully connected to your wallet.");
trackEvent(WALLET_CONNECTED);
} catch (err) {
console.error("Error during authentication process:", err);
setStatus(AuthStatus.FAILED);
toast.error("Failed to connect to your wallet. Please try again.");
}
}, [status, checkSession, startSession]);
}, [ethProvider, status, checkSession, startSession]);

return (
<AuthContext.Provider
Expand Down
11 changes: 7 additions & 4 deletions web-app/src/services/did-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@ import { getAddress } from "@ethersproject/address";
import { HDNodeWallet, Wallet } from "ethers";

class DIDService {
async getNewDIDSession() {
const ethProvider = window.ethereum;
async getNewDIDSession(ethProvider: any, sdk: any) {
// const { provider: ethProvider, sdk } = useSDK();

// request ethereum accounts.
const addresses = await ethProvider.enable({
const addresses = await ethProvider?.request({
method: "eth_requestAccounts",
});
const accountId = await getAccountId(ethProvider, addresses[0]);

const accounts = await sdk?.connect();

const accountId = await getAccountId(ethProvider, accounts?.[0]);
const normAccount = normalizeAccountId(accountId);
const keySeed = randomBytes(32);
const didKey = await createDIDKey(keySeed);
Expand Down
11 changes: 0 additions & 11 deletions web-app/src/utils/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,17 +72,6 @@ export const setDates = <
return obj;
};

export const switchNetwork = async (chainId: string) => {
try {
await window.ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId }],
});
return true;
} catch (e: any) {
if (e.code === 4001) return false; // Reject to switch
}
};
export const getCurrentDateTime = () => moment.utc().toISOString();

const isValidUrl = (url: string) => {
Expand Down
Loading

0 comments on commit 7e4ad37

Please sign in to comment.