Skip to content

Commit

Permalink
fix bug (#1012)
Browse files Browse the repository at this point in the history
  • Loading branch information
wow-sven authored Oct 21, 2023
1 parent d7b1870 commit d3a8f47
Show file tree
Hide file tree
Showing 8 changed files with 88 additions and 50 deletions.
11 changes: 6 additions & 5 deletions dashboard/src/@core/components/session/SessionGuard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@

import React, { ReactNode, useState } from 'react'
import {
Alert,
Button,
TextField,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
Snackbar,
Alert,
TextField,
} from '@mui/material'

// ** Next Import
Expand All @@ -20,11 +20,12 @@ import { useRouter } from 'next/router'
// ** Hooks Import
import { useAuth } from 'src/hooks/useAuth'
import { useSession } from 'src/hooks/useSessionAccount'
import { AccountType } from '../../../context/auth/types'

interface Props {
open: boolean
onReqAuthorize: (scope: Array<string>, maxInactiveInterval: number) => void
onLogout: () => void
onLogout?: () => void
}

const AuthDialog: React.FC<Props> = ({ open, onReqAuthorize, onLogout }) => {
Expand Down Expand Up @@ -75,7 +76,7 @@ const AuthDialog: React.FC<Props> = ({ open, onReqAuthorize, onLogout }) => {
/>
</DialogContent>
<DialogActions>
<Button onClick={onLogout}>Logout</Button>
{onLogout ? <Button onClick={onLogout}>Logout</Button> : null}
<Button onClick={handleAuth}>Authorize</Button>
</DialogActions>
</Dialog>
Expand Down Expand Up @@ -121,7 +122,7 @@ const SessionGuard = (props: SessionGuardProps) => {
<AuthDialog
open={isSessionInvalid()}
onReqAuthorize={handleAuth}
onLogout={hanleLogout}
onLogout={auth.defaultAccount?.type === AccountType.ROOCH ? hanleLogout : undefined}
></AuthDialog>
<Snackbar
open={errorMsg !== null}
Expand Down
1 change: 1 addition & 0 deletions dashboard/src/configs/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

export default {
secretKey: 'secret_key',
roochAccountMap: 'rooch_account_map',
activeChain: 'activeChain',
chains: 'chains',
roochChain: {
Expand Down
56 changes: 41 additions & 15 deletions dashboard/src/context/auth/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ const AuthProvider = ({ children }: Props) => {
const rooch = useRooch()

// ** States
const [roochAddressMap, setRoochAddressMap] = useState<Map<string, string>>(new Map())
const [defaultAccount, setDefaultAccount] = useState<AccountDataType | null>(() => {
if (defaultProvider.accounts && defaultProvider.accounts.size > 0) {
return defaultProvider.accounts.values().next().value
Expand All @@ -75,6 +76,12 @@ const AuthProvider = ({ children }: Props) => {
const initAuth = async (): Promise<void> => {
setLoading(true)

const roochAddressMapStr = window.localStorage.getItem(authConfig.roochAccountMap)

if (roochAddressMapStr) {
setRoochAddressMap(new Map<string, string>(JSON.parse(roochAddressMapStr)))
}

const secretKey = window.localStorage.getItem(authConfig.secretKey)

if (secretKey) {
Expand Down Expand Up @@ -187,9 +194,10 @@ const AuthProvider = ({ children }: Props) => {
throw new Error('resolve rooch address fail')
}

const updateETHAccount = async () => {
if (metamask.accounts.length > 0) {
const ethAddress = metamask.accounts[0]
const updateETHAccount = async (account?: string[]) => {
const _account = account ?? metamask.accounts
if (_account.length > 0) {
const ethAddress = _account[0]
const roochAddress = await resoleRoochAddress(ethAddress)

setAccountWrapper({
Expand All @@ -199,6 +207,14 @@ const AuthProvider = ({ children }: Props) => {
kp: null,
type: AccountType.ETH,
})

// TODO: clear
roochAddressMap.set(ethAddress, roochAddress)

window.localStorage.setItem(
authConfig.roochAccountMap,
JSON.stringify(Array.from(roochAddressMap.entries())),
)
}
}

Expand All @@ -207,8 +223,8 @@ const AuthProvider = ({ children }: Props) => {
case WalletType.Metamask:
metamask
.connect()
.then(() => {
updateETHAccount().then(() => {
.then((v: any) => {
updateETHAccount(v).then(() => {
loginSuccess && loginSuccess()
})
})
Expand Down Expand Up @@ -281,7 +297,7 @@ const AuthProvider = ({ children }: Props) => {
if (metamask.accounts.length > 0) {
metamask.accounts.forEach((v) => {
allAccounts.set(v, {
roochAddress: v,
roochAddress: roochAddressMap.get(v) ?? v,
address: v,
activate: true,
kp: null,
Expand All @@ -290,19 +306,29 @@ const AuthProvider = ({ children }: Props) => {
})
}

console.log('all acc', allAccounts)

return allAccounts.size > 0 ? allAccounts : null
}

const getDefaultAccount = (): AccountDataType | null => {
return defaultAccount ?? metamask.accounts.length > 0
? {
roochAddress: metamask.accounts[0],
address: metamask.accounts[0],
kp: null,
activate: true,
type: AccountType.ETH,
}
: null
if (defaultAccount) {
return defaultAccount
}

if (metamask.accounts.length > 0) {
const account = metamask.accounts[0]

return {
roochAddress: roochAddressMap.get(account) ?? account,
address: account,
kp: null,
activate: true,
type: AccountType.ETH,
}
}

return null
}

const values = {
Expand Down
60 changes: 33 additions & 27 deletions dashboard/src/context/session/SessionContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const SessionContext = createContext<Session>({
loading: false,
account: null,
errorMsg: null,
defaultSession: '',
requestAuthorize: undefined,
close: () => {},
})
Expand Down Expand Up @@ -334,33 +335,31 @@ const SessionProvider = ({ children }: Props) => {
return
}

if (defaultAccount != null) {
if (defaultAccount.kp != null) {
const roochAddress = defaultAccount.address
const authorizer = new PrivateKeyAuth(defaultAccount.kp)
const account = new Account(rooch.provider!, roochAddress, authorizer)

const sessionAccount = await requestPrivateCreateSessionKey(
filterdProvider,
account,
scope,
maxInactiveInterval,
)

if (sessionAccount) {
setSessionAccount(sessionAccount)
}
} else if (defaultAccount.type === 'ETH') {
const sessionAccount = await requestWalletCreateSessionKey(
filterdProvider,
defaultAccount,
scope,
maxInactiveInterval,
)

if (sessionAccount) {
setSessionAccount(sessionAccount)
}
if (defaultAccount.kp != null) {
const roochAddress = defaultAccount.address
const authorizer = new PrivateKeyAuth(defaultAccount.kp)
const account = new Account(rooch.provider!, roochAddress, authorizer)

const sessionAccount = await requestPrivateCreateSessionKey(
filterdProvider,
account,
scope,
maxInactiveInterval,
)

if (sessionAccount) {
setSessionAccount(sessionAccount)
}
} else if (defaultAccount.type === 'ETH') {
const sessionAccount = await requestWalletCreateSessionKey(
filterdProvider,
defaultAccount,
scope,
maxInactiveInterval,
)

if (sessionAccount) {
setSessionAccount(sessionAccount)
}
}
} catch (e: any) {
Expand All @@ -380,11 +379,18 @@ const SessionProvider = ({ children }: Props) => {
}
}

const getDefaultSession = (): string => {
return ''

// return window.sessionStorage.getItem(makeSessionAccountStoreKey(rooch.provider!.getChainId(), auth.defaultAccount?.roochAddress ?? '')) ?? ''
}

const session = {
loading,
account: sessionAccount,
errorMsg,
requestAuthorize,
defaultSession: getDefaultSession(),
close: closeSession,
} as Session

Expand Down
1 change: 1 addition & 0 deletions dashboard/src/context/session/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { IAccount } from '@rooch/sdk'
export interface Session {
account: IAccount | null
loading: boolean
defaultSession: string
errorMsg: string | null
requestAuthorize?: (scope: Array<string>, maxInactiveInterval: number) => Promise<void>
close: () => void
Expand Down
3 changes: 2 additions & 1 deletion dashboard/src/context/wallet/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ const ETHProvider = ({ children }: Props) => {
updateWallet([])
}
}

const refreshChina = (chainId: any) => {
setChainId(chainId)

Expand Down Expand Up @@ -111,6 +110,8 @@ const ETHProvider = ({ children }: Props) => {
})
.then((accounts: any) => {
updateWallet(accounts)

return accounts
})
}

Expand Down
3 changes: 2 additions & 1 deletion dashboard/src/store/session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,11 @@ export const fetchData = createAsyncThunk('state/fetchData', async (params: Data
try {
const accessPath = `/resource/${account_address}/0x3::session_key::SessionKeys`
const stateResult = await params.provider.getStates(accessPath)

if (stateResult) {
const stateView = stateResult as any
if (stateView && stateView.length > 0 && stateView[0]) {
const tableId = stateView[0].state.value
const tableId = stateView[0].decoded_value.value.keys.value.handle

const accessPath = `/table/${tableId}`
const pageView = await params.provider.listStates(accessPath, cursor, limit)
Expand Down
3 changes: 2 additions & 1 deletion dashboard/src/views/feature/SessionKeyList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ export default function SessionKeyList() {
}

const handleConfirmRemove = (authentication_key: string | undefined) => {
// Todo: how to handle current session key
setConfirmDeleteDialog({
open: false,
authKey: undefined,
Expand Down Expand Up @@ -233,7 +234,7 @@ export default function SessionKeyList() {
<Card>
<CardHeader title="Session Keys" />
<CardContent>
<Box sx={{ textAlign: 'right', marginBottom: '10px' }}>
<Box sx={{ textAlign: 'right', marginBottom: '10px', mr: '20px' }}>
<Button
variant="contained"
color="primary"
Expand Down

0 comments on commit d3a8f47

Please sign in to comment.