Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catalyst: Web3Auth demo (do not merge & keep alive) #2

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .env.local.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
BLOCKFROST_PROJECT_ID_PREPROD=preprod...
BLOCKFROST_PROJECT_ID_PREPROD=preprodDkyO5HSu39HrUocYBAuo1wJ7axRmZSJz
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=See https://next-auth.js.org/configuration/options#nextauth_secret
NEXTAUTH_SECRET=my-secret
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
# How to run

```
yarn
cp .env.local.example .env.local
yarn dev
```

# 🎲 adaplays.xyz

Place to play staked games with moves verified by blockchain.
Expand Down
78 changes: 46 additions & 32 deletions components/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
import type { User } from "next-auth"
import type { SupportedWallets } from '../types/types'

import { useState, useRef } from 'react';
import { useState, useRef, useEffect } from 'react';
import NextLink from 'next/link';
import { navHeight } from 'constants/global';
import { WalletApi, Lucid } from "lucid-cardano";
import GoogleButton from 'react-google-button'
import {
Heading,
Flex,
Expand Down Expand Up @@ -41,7 +42,7 @@ YupPassword(yup)
import { brandButtonStyle } from 'theme/simple'
import { getApi, getLucid } from "utils/lucid/lucid";

export default function Navbar() {
export default function Navbar({hideWidget}: {hideWidget?: () => void}) {
const [logoHover, setLogoHover] = useState<boolean>(false);

return (
Expand All @@ -64,7 +65,7 @@ export default function Navbar() {
onMouseLeave={() => setLogoHover(false)}
>
<HStack>
<Heading variant='brand' position='relative' left='10px' bg='white' zIndex='1' borderRightRadius='full'>
<Heading variant='brand' position='relative' left='10px' bg='white' borderRightRadius='full'>
adaplays
</Heading>
<Logo />
Expand Down Expand Up @@ -96,17 +97,18 @@ export default function Navbar() {
<Icon pt='10px' height='36px' width='36px' as={FaGithub}></Icon>
</Box> */}
</Link>
<ConnectButton />
<ConnectButton hideWidget={hideWidget} />
</HStack>
</Flex>
);
}

const ConnectButton = () => {
const ConnectButton = ({hideWidget}: {hideWidget?: () => void}) => {
const { status } = useSession()
const [_walletName, _setWalletName] = useState<SupportedWallets>('nami')
const [_walletName, _setWalletName] = useState<SupportedWallets>('nufi')
const [walletConnected, setWalletConnected] = useState<boolean>(false)
const [selectWalletTapped, setSelectWalletTapped] = useState<boolean>(false)
const [isConnecting, setIsConnecting] = useState<boolean>(false)
const [isDisconnecting, setIsDisconnecting] = useState<boolean>(false)

// I have two alert setup, one fires up when selected wallet is not installed in the browser and other one when enabled wallet is on wrong network
Expand All @@ -122,7 +124,7 @@ const ConnectButton = () => {
setSelectWalletTapped(false);
}, 200)
}
const supportedWallets: SupportedWallets[] = ['nami', 'eternl']
const supportedWallets: SupportedWallets[] = ['nufi']

const createPasswordSchema = yup.object().shape({
password: yup
Expand Down Expand Up @@ -157,25 +159,43 @@ const ConnectButton = () => {
resetStatus();
await signOut({ redirect: false });
setIsDisconnecting(false);
hideWidget?.()
setIsConnecting(false)
}

useEffect(() => {
const fn = async () => {
if (status === 'authenticated') {
const isEnabled = await window.cardano.nufi.isEnabled()
if (!isEnabled) {
await disconnecting()
}
}
}
fn()
}, [status])

const connectWallet = async (walletName: SupportedWallets) => {
if (!hasWalletExtension(walletName)) {
walletNotFound.onOpen();
} else {
try {
setIsConnecting(true)
const api: WalletApi = await getApi(walletName)
// In case the above connection fails, the whole component fails so I guess nothing to worry.
const networkId = await api.getNetworkId();
if (networkId !== 0) {
wrongNetwork.onOpen()
} else {
_setWalletName(walletName)
setWalletConnected(await window.cardano.nami.isEnabled())
const enabled = await window.cardano.nufi.isEnabled()
setWalletConnected(enabled)
}
} catch (e) {
console.error(e);
resetStatus();
} finally {
setIsDisconnecting(false)
}
}
}
Expand All @@ -188,32 +208,19 @@ const ConnectButton = () => {
<>
<SimpleAlert {...{ isOpen: walletNotFound.isOpen, onClose: () => { resetStatus(); walletNotFound.onClose() }, cancelRef: cancelRefWalletNotFound, message: "You don't have the selected wallet installed." }} />
<SimpleAlert {...{ isOpen: wrongNetwork.isOpen, onClose: () => { resetStatus(); wrongNetwork.onClose() }, cancelRef: cancelRefWrongNetwork, message: "You have selected wrong network, please switch to Preprod." }} />

<Popover onClose={resetStatus}>
<PopoverTrigger>
<Button {...connectbuttonStyle}>
Connect
<Button {...connectbuttonStyle} border="none">
<GoogleButton
style={{background: '#333', width: 250}}
label={isConnecting ? 'Connecting ...' : 'Sign in with Google'}
onClick={() => connectWallet('nufi')}
/>
</Button>
</PopoverTrigger>
{walletConnected === false
? <PopoverContent>
<PopoverHeader {...popoverHeaderStyle}>
Select wallet
</PopoverHeader>
<PopoverArrow />
<PopoverCloseButton />
<PopoverBody>
<VStack>
{supportedWallets.map((walletName) => (
<Button key={walletName} onClick={() => { setSelectWalletTapped(true); connectWallet(walletName) }} variant='link' colorScheme='black' isLoading={selectWalletTapped}>
{walletName[0].toUpperCase() + walletName.slice(1)}
</Button>
))}
</VStack>
<PopoverFooter {...popoverFooterStyle}>
<Text align='center'> ✤ step 1 of 2 ✤ </Text>
</PopoverFooter>
</PopoverBody>
</PopoverContent>
? null
: <PopoverContent>
<PopoverHeader {...popoverHeaderStyle}>
Create session password
Expand Down Expand Up @@ -270,8 +277,15 @@ const ConnectButton = () => {
</Popover>
</>
); else return (
<Button {...connectbuttonStyle} onClick={() => disconnecting()} isLoading={isDisconnecting} >
Disconnect
</Button>
<div style={{display: 'flex', alignItems: 'center'}}>
<GoogleButton
style={{background: '#333', width: 250}}
label='Connected'
onClick={() => connectWallet('nufi')}
/>
<Button {...connectbuttonStyle} height="50px" marginLeft="8px" onClick={() => disconnecting()} isLoading={isDisconnecting} >
Disconnect
</Button>
</div>
);
}
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"@emotion/react": "^11.10.5",
"@emotion/styled": "^11.10.5",
"@fontsource/jetbrains-mono": "^4.5.11",
"@nufi/dapp-client-cardano": "file:packages/nufi-dapp-client-cardano-v7.1.2.tgz",
"formik": "^2.2.9",
"framer-motion": "^6",
"lucid-cardano": "^0.7.6",
Expand All @@ -23,6 +24,7 @@
"react": "18.2.0",
"react-countdown": "^2.3.3",
"react-dom": "18.2.0",
"react-google-button": "^0.7.2",
"react-icons": "^4.6.0",
"yup": "^0.32.11",
"yup-password": "^0.2.2",
Expand All @@ -35,5 +37,8 @@
"eslint": "8.26.0",
"eslint-config-next": "12.3.1",
"typescript": "4.8.4"
},
"resolutions": {
"@nufi/dapp-client-core": "file:packages/nufi-dapp-client-core-v7.1.2.tgz"
}
}
Binary file added packages/nufi-dapp-client-cardano-v7.1.2.tgz
Binary file not shown.
Binary file added packages/nufi-dapp-client-core-v7.1.2.tgz
Binary file not shown.
22 changes: 20 additions & 2 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useEffect, useState } from 'react';
import type { AppProps } from 'next/app'
import { ChakraProvider, extendTheme, Container } from '@chakra-ui/react'
import Head from 'next/head'
Expand All @@ -6,6 +7,7 @@ import Navbar from '../components/navbar'
import { SessionProvider } from "next-auth/react"
import { Session } from 'next-auth'
import { headingTheme } from 'theme/components/heading'
import { nufiAdapter } from '@nufi/dapp-client-cardano';

const theme = extendTheme({
fonts: {
Expand All @@ -17,13 +19,28 @@ const theme = extendTheme({
}
})

// TODO: adjust SDK so that it prevents injecting iframe multiple times
let didInject = false;

// https://stackoverflow.com/questions/73668032/nextauth-type-error-property-session-does-not-exist-on-type
function MyApp({ Component, pageProps }: AppProps<{ session: Session }>) {
const [hideWidget, setHideWidget] = useState<() => void>()

useEffect(() => {
if (didInject === false) {
// TODO: adjust SDK so that iframe is visible only after user choose NuFi wallet
// (relies on proper batching of requests).
const {hideWidget} = nufiAdapter('web3Auth');
setHideWidget(() => hideWidget)
didInject = true;
}
}, []);

return (
<SessionProvider session={pageProps.session}>
<ChakraProvider theme={theme}>
<Head>
<title>adaplays.xyz</title>
<title>adaplays.com</title>
<meta name="description" content="Place to play simple games with ada" />
<link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png"/>
<link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png"/>
Expand All @@ -36,8 +53,9 @@ function MyApp({ Component, pageProps }: AppProps<{ session: Session }>) {
<meta name="theme-color" content="#ffffff"/>
</Head>
<Container maxWidth='container.md'>
<Navbar/>
<Navbar hideWidget={hideWidget} />
<Component {...pageProps} />
<div style={{position: 'fixed', bottom: 10, right: 10}}>Copyright (c) 2022 Sourabh Aggarwal</div>
</Container>
</ChakraProvider>
</SessionProvider>
Expand Down
2 changes: 1 addition & 1 deletion types/types.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export type SupportedWallets = "nami" | "eternl";
export type SupportedWallets = "nufi";
17 changes: 17 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1140,6 +1140,16 @@
"@nodelib/fs.scandir" "2.1.5"
fastq "^1.6.0"

"@nufi/dapp-client-cardano@file:packages/nufi-dapp-client-cardano-v7.1.2.tgz":
version "7.1.2"
resolved "file:packages/nufi-dapp-client-cardano-v7.1.2.tgz#db0a9c06cceb00412d5f49cbc9ac43c8a5cd0e0b"
dependencies:
"@nufi/dapp-client-core" "7.1.2"

"@nufi/[email protected]", "@nufi/dapp-client-core@file:packages/nufi-dapp-client-core-v7.1.2.tgz":
version "7.1.2"
resolved "file:packages/nufi-dapp-client-core-v7.1.2.tgz#6964221b554fadb818a668b3a19dfcb3e5b8d655"

"@panva/hkdf@^1.0.1":
version "1.0.2"
resolved "https://registry.yarnpkg.com/@panva/hkdf/-/hkdf-1.0.2.tgz#bab0f09d09de9fd83628220d496627681bc440d6"
Expand Down Expand Up @@ -2943,6 +2953,13 @@ react-focus-lock@^2.9.1:
use-callback-ref "^1.3.0"
use-sidecar "^1.1.2"

react-google-button@^0.7.2:
version "0.7.2"
resolved "https://registry.yarnpkg.com/react-google-button/-/react-google-button-0.7.2.tgz#5bb2bcb0d54e36da3cd3b712a6fac4f9209b764c"
integrity sha512-LPIqU2hIlc212kqks8MtKjRstquVkP3SIjxlK5B1nIfg2R7YqSusJAxZUkJA5dv/z6QeSuGyI9ujwV/VWMTyAA==
dependencies:
prop-types "^15.7.2"

react-icons@^4.6.0:
version "4.6.0"
resolved "https://registry.yarnpkg.com/react-icons/-/react-icons-4.6.0.tgz#f83eda179af5d02c047449a20b702c858653d397"
Expand Down