Skip to content

Commit

Permalink
Fix metamask auth flow (#12)
Browse files Browse the repository at this point in the history
* Fix metamask auth flow

* Fix lint
  • Loading branch information
raymondjacobson authored and michellebrier committed Oct 9, 2023
1 parent fc1d1ba commit 3315415
Show file tree
Hide file tree
Showing 7 changed files with 96 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@
cursor: pointer;
}

.misconfigured {
cursor: default;
}

.connectMetaMaskDot {
width: 14px;
height: 14px;
Expand Down
69 changes: 48 additions & 21 deletions packages/protocol-dashboard/src/components/AppBar/AppBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import ConnectMetaMaskModal from 'components/ConnectMetaMaskModal'
import { ReactComponent as Logo } from 'assets/img/audiusLogoHorizontal.svg'
import { useAccount } from 'store/account/hooks'
import { useUser } from 'store/cache/user/hooks'
import { Address, Status } from 'types'
import { Address } from 'types'
import { formatWei, formatShortAud, formatShortWallet } from 'utils/format'
import { usePushRoute } from 'utils/effects'
import { accountPage, isCryptoPage } from 'utils/routes'
Expand All @@ -25,38 +25,57 @@ const messages = {
name: 'PROTOCOL DASHBOARD',
launchApp: 'LAUNCH THE APP',
connectMetaMask: 'Connect Metamask',
metaMaskMisconfigured: 'Metamask Misconfigured',
block: 'Block'
}

// TODO:
// * Replace account img, wallet & tokens from store
type UserAccountSnippetProps = { wallet: Address }
type MisconfiguredProps = {
isAccountMisconfigured: boolean
isMisconfigured: boolean
}

const UserAccountSnippet = ({ wallet }: UserAccountSnippetProps) => {
const { user, status } = useUser({ wallet })
const Misconfigured = ({
isAccountMisconfigured,
isMisconfigured
}: MisconfiguredProps) => {
const [isOpen, setIsOpen] = useState(false)
const onClick = useCallback(() => setIsOpen(true), [setIsOpen])
const onClose = useCallback(() => setIsOpen(false), [setIsOpen])

const onClickHandler = isMisconfigured ? undefined : onClick
return (
<>
<div
onClick={onClickHandler}
className={clsx(styles.connectMetaMaskContainer, {
[styles.misconfigured]: isMisconfigured
})}
>
<div className={styles.connectMetaMaskDot}></div>
<div className={styles.connectMetaMask}>
{isMisconfigured
? messages.metaMaskMisconfigured
: messages.connectMetaMask}
</div>
</div>
<ConnectMetaMaskModal isOpen={isOpen} onClose={onClose} />
</>
)
}

const UserAccountSnippet = ({ wallet }: UserAccountSnippetProps) => {
const { user } = useUser({ wallet })
const pushRoute = usePushRoute()
const onClickUser = useCallback(() => {
if (user) {
pushRoute(accountPage(user.wallet))
}
}, [user, pushRoute])

if (!user || status !== Status.Success) {
return (
<>
<div onClick={onClick} className={styles.connectMetaMaskContainer}>
<div className={styles.connectMetaMaskDot}></div>
<div className={styles.connectMetaMask}>
{messages.connectMetaMask}
</div>
</div>
<ConnectMetaMaskModal isOpen={isOpen} onClose={onClose} />
</>
)
}
if (!user) return null

return (
<div className={styles.snippetContainer} onClick={onClickUser}>
Expand Down Expand Up @@ -100,6 +119,9 @@ const AppBar: React.FC<AppBarProps> = (props: AppBarProps) => {
const ethBlock = useEthBlockNumber()
const { pathname } = useLocation()
const showBlock = isCryptoPage(pathname) && ethBlock

const { isMisconfigured, isAccountMisconfigured } = window.aud

return (
<div className={styles.appBar}>
<div className={styles.left}>
Expand All @@ -116,11 +138,16 @@ const AppBar: React.FC<AppBarProps> = (props: AppBarProps) => {
<div className={styles.title}>{messages.block}</div>
<div className={styles.block}>{ethBlock}</div>
</div>
{isLoggedIn && wallet && (
<div className={styles.userAccountSnippetContainer}>
<UserAccountSnippet wallet={wallet} />
</div>
)}
<div className={styles.userAccountSnippetContainer}>
{isMisconfigured || isAccountMisconfigured ? (
<Misconfigured
isMisconfigured={isMisconfigured}
isAccountMisconfigured={isAccountMisconfigured}
/>
) : (
isLoggedIn && wallet && <UserAccountSnippet wallet={wallet} />
)}
</div>
<LaunchTheAppButton />
</div>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ const ConnectMetaMaskModal: React.FC<ConnectMetaMaskModalProps> = ({
onClose
}: ConnectMetaMaskModalProps) => {
const onOpenMetaMask = useCallback(() => {
// TODO: figure out how to do this....
if (window.ethereum) {
window.ethereum.request({ method: 'eth_requestAccounts' })
}
}, [])
return (
<Modal
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ export class AudiusClient {

isSetup = false // If the setup is complete
hasValidAccount = false // If metamask is set up correctly
isAccountMisconfgured = false // If metamask is present and misconfigured
isAccountMisconfigured = false // If metamask is present and account is not connected
isMisconfigured = false // If metamask is present and misconfigured (wrong network)
isViewOnly = false // If metamask is not present

// Class helpers
Expand Down
49 changes: 28 additions & 21 deletions packages/protocol-dashboard/src/services/Audius/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ declare global {
ethereum: any
dataWeb3: any
configuredMetamaskWeb3: any
isAccountMisconfigured: boolean
}
}

Expand All @@ -29,48 +30,49 @@ const ethNetworkId = process.env.REACT_APP_ETH_NETWORK_ID

export async function setup(this: AudiusClient): Promise<void> {
if (!window.web3 || !window.ethereum) {
// metamask is not installed
this.isAccountMisconfgured = true
// Metamask is not installed
this.isViewOnly = true
this.libs = await configureReadOnlyLibs()
} else {
// Metamask is installed
window.web3 = new Web3(window.ethereum)
try {
if (window.ethereum) {
const isUnlocked = await window.ethereum._metamask.isUnlocked()
if (!isUnlocked) {
// If the user changes metamask accounts, reload and init
window.ethereum.on('accountsChanged', () => {
window.location.reload()
})
}
// Reload anytime the accounts change
window.ethereum.on('accountsChanged', () => {
window.location.reload()
})
// Reload anytime the network changes
window.ethereum.on('chainChanged', () => {
window.location.reload()
})
}

let metamaskWeb3Network = await getMetaMaskNetwork()
let metamaskWeb3Network = window.ethereum.networkVersion
if (metamaskWeb3Network !== ethNetworkId) {
this.isAccountMisconfgured = true
this.isMisconfigured = true
this.libs = await configureReadOnlyLibs()
} else {
this.libs = await configureLibsWithAccount()
this.hasValidAccount = true

// Failed to pull necessary info from metamask, configure read only
if (!this.libs) {
this.libs = await configureReadOnlyLibs()
this.isAccountMisconfigured = true
}
}
} catch (err) {
console.error(err)
this.libs = await configureReadOnlyLibs()
this.isMisconfigured = true
}
}

window.audiusLibs = this.libs
this.isSetup = true
}

const getMetaMaskNetwork = async () => {
// Below is an async version of the web3 version check since metamask 0.20.7 getNetwork doesn't work async
return new Promise(async (resolve, reject) => {
window.web3.version.getNetwork((error: any, result: any) => {
if (error) reject(error)
resolve(result)
})
})
}

const configureReadOnlyLibs = async () => {
const ethWeb3Config = audius.configEthWeb3(
ethTokenAddress,
Expand Down Expand Up @@ -101,6 +103,11 @@ const configureLibsWithAccount = async () => {
})
})
let metamaskAccount = metamaskAccounts[0]

// Not connected or no accounts, return
if (!metamaskAccount) {
return null
}
let audiusLibsConfig = {
ethWeb3Config: audius.configEthWeb3(
ethTokenAddress,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,15 @@ export function fetchDiscoveryProviders(
const discoveryProviders = await aud.ServiceProviderClient.getServiceProviderList(
ServiceType.DiscoveryProvider
)
const legacy = (
await aud.ServiceProviderClient.getServiceProviderList(
// @ts-ignore
'discovery-provider'
)
).map((d, i) => ({ ...d, spID: 100 + i }))

const discoveryProviderVersions = await Promise.all(
discoveryProviders.map(node => processDP(node, aud))
discoveryProviders.concat(legacy).map(node => processDP(node, aud))
)
const nodes = discoveryProviderVersions.reduce(
(acc: { [spId: number]: DiscoveryProvider }, dp) => {
Expand All @@ -110,6 +117,7 @@ export function fetchDiscoveryProviders(
},
{}
)

dispatch(
setNodes({
status: Status.Success,
Expand Down
6 changes: 2 additions & 4 deletions packages/protocol-dashboard/src/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,8 @@ declare global {
}

const aud = new Audius()
// TODO: Move this
aud.setup().then(() => {
window.aud = aud
})
window.aud = aud
aud.setup()

const getReducer = (history: History) => {
return combineReducers({
Expand Down

0 comments on commit 3315415

Please sign in to comment.